@walletconnect/ethereum-provider 2.4.9 → 2.4.10
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/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
12
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
13
|
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
-
***************************************************************************** */var Co=function(t,e){return Co=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Co(t,e)};function Cp(t,e){Co(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var So=function(){return So=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},So.apply(this,arguments)};function Sp(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Ip(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function Dp(t,e){return function(r,n){e(r,n,t)}}function Op(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Ap(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(m){o(m)}}function c(p){try{l(n.throw(p))}catch(m){o(m)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function $p(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(p){return c([l,p])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(p){l=[6,p],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Pp(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Tp(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Io(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ll(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function Np(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ll(arguments[e]));return t}function Rp(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function kn(t){return this instanceof kn?(this.v=t,this):new kn(t)}function Mp(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(w){n[w]&&(i[w]=function(y){return new Promise(function(E,T){s.push([w,y,E,T])>1||a(w,y)})})}function a(w,y){try{c(n[w](y))}catch(E){m(s[0][3],E)}}function c(w){w.value instanceof kn?Promise.resolve(w.value.v).then(l,p):m(s[0][2],w)}function l(w){a("next",w)}function p(w){a("throw",w)}function m(w,y){w(y),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Lp(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:kn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function Up(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Io=="function"?Io(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Fp(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function jp(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Bp(t){return t&&t.__esModule?t:{default:t}}function kp(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Hp(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var zp=Object.freeze({__proto__:null,__extends:Cp,get __assign(){return So},__rest:Sp,__decorate:Ip,__param:Dp,__metadata:Op,__awaiter:Ap,__generator:$p,__createBinding:Pp,__exportStar:Tp,__values:Io,__read:Ll,__spread:Np,__spreadArrays:Rp,__await:kn,__asyncGenerator:Mp,__asyncDelegator:Lp,__asyncValues:Up,__makeTemplateObject:Fp,__importStar:jp,__importDefault:Bp,__classPrivateFieldGet:kp,__classPrivateFieldSet:Hp}),ts=Pr(zp),Do={},Hn={},Ul;function Wp(){if(Ul)return Hn;Ul=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return Hn.delay=t,Hn}var Tr={},Oo={},Nr={},Fl;function qp(){return Fl||(Fl=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.ONE_THOUSAND=Nr.ONE_HUNDRED=void 0,Nr.ONE_HUNDRED=100,Nr.ONE_THOUSAND=1e3),Nr}var Ao={},jl;function Vp(){return jl||(jl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(Ao)),Ao}var Bl;function kl(){return Bl||(Bl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(qp(),t),e.__exportStar(Vp(),t)}(Oo)),Oo}var Hl;function Kp(){if(Hl)return Tr;Hl=1,Object.defineProperty(Tr,"__esModule",{value:!0}),Tr.fromMiliseconds=Tr.toMiliseconds=void 0;const t=kl();function e(n){return n*t.ONE_THOUSAND}Tr.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return Tr.fromMiliseconds=r,Tr}var zl;function Gp(){return zl||(zl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(Wp(),t),e.__exportStar(Kp(),t)}(Do)),Do}var un={},Wl;function Zp(){if(Wl)return un;Wl=1,Object.defineProperty(un,"__esModule",{value:!0}),un.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const n=this.get(r);if(typeof n.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const i=Date.now()-n.started;this.timestamps.set(r,{started:n.started,elapsed:i})}get(r){const n=this.timestamps.get(r);if(typeof n>"u")throw new Error(`No timestamp found for label: ${r}`);return n}elapsed(r){const n=this.get(r);return n.elapsed||Date.now()-n.started}}return un.Watch=t,un.default=t,un}var $o={},zn={},ql;function Yp(){if(ql)return zn;ql=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.IWatch=void 0;class t{}return zn.IWatch=t,zn}var Vl;function Jp(){return Vl||(Vl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),ts.__exportStar(Yp(),t)}($o)),$o}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(Gp(),t),e.__exportStar(Zp(),t),e.__exportStar(Jp(),t),e.__exportStar(kl(),t)})(fe);var ze={};Object.defineProperty(ze,"__esModule",{value:!0}),ze.getLocalStorage=ze.getLocalStorageOrThrow=ze.getCrypto=ze.getCryptoOrThrow=Gl=ze.getLocation=ze.getLocationOrThrow=Po=ze.getNavigator=ze.getNavigatorOrThrow=Kl=ze.getDocument=ze.getDocumentOrThrow=ze.getFromWindowOrThrow=ze.getFromWindow=void 0;function Rr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ze.getFromWindow=Rr;function hn(t){const e=Rr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ze.getFromWindowOrThrow=hn;function Xp(){return hn("document")}ze.getDocumentOrThrow=Xp;function Qp(){return Rr("document")}var Kl=ze.getDocument=Qp;function eg(){return hn("navigator")}ze.getNavigatorOrThrow=eg;function tg(){return Rr("navigator")}var Po=ze.getNavigator=tg;function rg(){return hn("location")}ze.getLocationOrThrow=rg;function ng(){return Rr("location")}var Gl=ze.getLocation=ng;function ig(){return hn("crypto")}ze.getCryptoOrThrow=ig;function sg(){return Rr("crypto")}ze.getCrypto=sg;function og(){return hn("localStorage")}ze.getLocalStorageOrThrow=og;function ag(){return Rr("localStorage")}ze.getLocalStorage=ag;var To={};Object.defineProperty(To,"__esModule",{value:!0});var Zl=To.getWindowMetadata=void 0;const Yl=ze;function cg(){let t,e;try{t=Yl.getDocumentOrThrow(),e=Yl.getLocationOrThrow()}catch{return null}function r(){const m=t.getElementsByTagName("link"),w=[];for(let y=0;y<m.length;y++){const E=m[y],T=E.getAttribute("rel");if(T&&T.toLowerCase().indexOf("icon")>-1){const N=E.getAttribute("href");if(N)if(N.toLowerCase().indexOf("https:")===-1&&N.toLowerCase().indexOf("http:")===-1&&N.indexOf("//")!==0){let U=e.protocol+"//"+e.host;if(N.indexOf("/")===0)U+=N;else{const C=e.pathname.split("/");C.pop();const D=C.join("/");U+=D+"/"+N}w.push(U)}else if(N.indexOf("//")===0){const U=e.protocol+N;w.push(U)}else w.push(N)}}return w}function n(...m){const w=t.getElementsByTagName("meta");for(let y=0;y<w.length;y++){const E=w[y],T=["itemprop","property","name"].map(N=>E.getAttribute(N)).filter(N=>N?m.includes(N):!1);if(T.length&&T){const N=E.getAttribute("content");if(N)return N}}return""}function i(){let m=n("name","og:site_name","og:title","twitter:title");return m||(m=t.title),m}function s(){return n("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,l=r();return{description:a,url:c,icons:l,name:o}}Zl=To.getWindowMetadata=cg;var Wn={},lg=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Jl="%[a-f0-9]{2}",Xl=new RegExp("("+Jl+")|([^%]+?)","gi"),Ql=new RegExp("("+Jl+")+","gi");function No(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],No(r),No(n))}function ug(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(Xl)||[],r=1;r<e.length;r++)t=No(e,r).join(""),e=t.match(Xl)||[];return t}}function hg(t){for(var e={"%FE%FF":"\uFFFD\uFFFD","%FF%FE":"\uFFFD\uFFFD"},r=Ql.exec(t);r;){try{e[r[0]]=decodeURIComponent(r[0])}catch{var n=ug(r[0]);n!==r[0]&&(e[r[0]]=n)}r=Ql.exec(t)}e["%C2"]="\uFFFD";for(var i=Object.keys(e),s=0;s<i.length;s++){var o=i[s];t=t.replace(new RegExp(o,"g"),e[o])}return t}var dg=function(t){if(typeof t!="string")throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof t+"`");try{return t=t.replace(/\+/g," "),decodeURIComponent(t)}catch{return hg(t)}},fg=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];const r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]},pg=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s<n.length;s++){var o=n[s],a=t[o];(i?e.indexOf(o)!==-1:e(o,a,t))&&(r[o]=a)}return r};(function(t){const e=lg,r=dg,n=fg,i=pg,s=C=>C==null,o=Symbol("encodeFragmentIdentifier");function a(C){switch(C.arrayFormat){case"index":return D=>(b,I)=>{const O=b.length;return I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,[p(D,C),"[",O,"]"].join("")]:[...b,[p(D,C),"[",p(O,C),"]=",p(I,C)].join("")]};case"bracket":return D=>(b,I)=>I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,[p(D,C),"[]"].join("")]:[...b,[p(D,C),"[]=",p(I,C)].join("")];case"colon-list-separator":return D=>(b,I)=>I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,[p(D,C),":list="].join("")]:[...b,[p(D,C),":list=",p(I,C)].join("")];case"comma":case"separator":case"bracket-separator":{const D=C.arrayFormat==="bracket-separator"?"[]=":"=";return b=>(I,O)=>O===void 0||C.skipNull&&O===null||C.skipEmptyString&&O===""?I:(O=O===null?"":O,I.length===0?[[p(b,C),D,p(O,C)].join("")]:[[I,p(O,C)].join(C.arrayFormatSeparator)])}default:return D=>(b,I)=>I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,p(D,C)]:[...b,[p(D,C),"=",p(I,C)].join("")]}}function c(C){let D;switch(C.arrayFormat){case"index":return(b,I,O)=>{if(D=/\[(\d*)\]$/.exec(b),b=b.replace(/\[\d*\]$/,""),!D){O[b]=I;return}O[b]===void 0&&(O[b]={}),O[b][D[1]]=I};case"bracket":return(b,I,O)=>{if(D=/(\[\])$/.exec(b),b=b.replace(/\[\]$/,""),!D){O[b]=I;return}if(O[b]===void 0){O[b]=[I];return}O[b]=[].concat(O[b],I)};case"colon-list-separator":return(b,I,O)=>{if(D=/(:list)$/.exec(b),b=b.replace(/:list$/,""),!D){O[b]=I;return}if(O[b]===void 0){O[b]=[I];return}O[b]=[].concat(O[b],I)};case"comma":case"separator":return(b,I,O)=>{const h=typeof I=="string"&&I.includes(C.arrayFormatSeparator),_=typeof I=="string"&&!h&&m(I,C).includes(C.arrayFormatSeparator);I=_?m(I,C):I;const H=h||_?I.split(C.arrayFormatSeparator).map(B=>m(B,C)):I===null?I:m(I,C);O[b]=H};case"bracket-separator":return(b,I,O)=>{const h=/(\[\])$/.test(b);if(b=b.replace(/\[\]$/,""),!h){O[b]=I&&m(I,C);return}const _=I===null?[]:I.split(C.arrayFormatSeparator).map(H=>m(H,C));if(O[b]===void 0){O[b]=_;return}O[b]=[].concat(O[b],_)};default:return(b,I,O)=>{if(O[b]===void 0){O[b]=I;return}O[b]=[].concat(O[b],I)}}}function l(C){if(typeof C!="string"||C.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function p(C,D){return D.encode?D.strict?e(C):encodeURIComponent(C):C}function m(C,D){return D.decode?r(C):C}function w(C){return Array.isArray(C)?C.sort():typeof C=="object"?w(Object.keys(C)).sort((D,b)=>Number(D)-Number(b)).map(D=>C[D]):C}function y(C){const D=C.indexOf("#");return D!==-1&&(C=C.slice(0,D)),C}function E(C){let D="";const b=C.indexOf("#");return b!==-1&&(D=C.slice(b)),D}function T(C){C=y(C);const D=C.indexOf("?");return D===-1?"":C.slice(D+1)}function N(C,D){return D.parseNumbers&&!Number.isNaN(Number(C))&&typeof C=="string"&&C.trim()!==""?C=Number(C):D.parseBooleans&&C!==null&&(C.toLowerCase()==="true"||C.toLowerCase()==="false")&&(C=C.toLowerCase()==="true"),C}function U(C,D){D=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},D),l(D.arrayFormatSeparator);const b=c(D),I=Object.create(null);if(typeof C!="string"||(C=C.trim().replace(/^[?#&]/,""),!C))return I;for(const O of C.split("&")){if(O==="")continue;let[h,_]=n(D.decode?O.replace(/\+/g," "):O,"=");_=_===void 0?null:["comma","separator","bracket-separator"].includes(D.arrayFormat)?_:m(_,D),b(m(h,D),_,I)}for(const O of Object.keys(I)){const h=I[O];if(typeof h=="object"&&h!==null)for(const _ of Object.keys(h))h[_]=N(h[_],D);else I[O]=N(h,D)}return D.sort===!1?I:(D.sort===!0?Object.keys(I).sort():Object.keys(I).sort(D.sort)).reduce((O,h)=>{const _=I[h];return Boolean(_)&&typeof _=="object"&&!Array.isArray(_)?O[h]=w(_):O[h]=_,O},Object.create(null))}t.extract=T,t.parse=U,t.stringify=(C,D)=>{if(!C)return"";D=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},D),l(D.arrayFormatSeparator);const b=_=>D.skipNull&&s(C[_])||D.skipEmptyString&&C[_]==="",I=a(D),O={};for(const _ of Object.keys(C))b(_)||(O[_]=C[_]);const h=Object.keys(O);return D.sort!==!1&&h.sort(D.sort),h.map(_=>{const H=C[_];return H===void 0?"":H===null?p(_,D):Array.isArray(H)?H.length===0&&D.arrayFormat==="bracket-separator"?p(_,D)+"[]":H.reduce(I(_),[]).join("&"):p(_,D)+"="+p(H,D)}).filter(_=>_.length>0).join("&")},t.parseUrl=(C,D)=>{D=Object.assign({decode:!0},D);const[b,I]=n(C,"#");return Object.assign({url:b.split("?")[0]||"",query:U(T(C),D)},D&&D.parseFragmentIdentifier&&I?{fragmentIdentifier:m(I,D)}:{})},t.stringifyUrl=(C,D)=>{D=Object.assign({encode:!0,strict:!0,[o]:!0},D);const b=y(C.url).split("?")[0]||"",I=t.extract(C.url),O=t.parse(I,{sort:!1}),h=Object.assign(O,C.query);let _=t.stringify(h,D);_&&(_=`?${_}`);let H=E(C.url);return C.fragmentIdentifier&&(H=`#${D[o]?p(C.fragmentIdentifier,D):C.fragmentIdentifier}`),`${b}${_}${H}`},t.pick=(C,D,b)=>{b=Object.assign({parseFragmentIdentifier:!0,[o]:!1},b);const{url:I,query:O,fragmentIdentifier:h}=t.parseUrl(C,b);return t.stringifyUrl({url:I,query:i(O,D),fragmentIdentifier:h},b)},t.exclude=(C,D,b)=>{const I=Array.isArray(D)?O=>!D.includes(O):(O,h)=>!D(O,h);return t.pick(C,I,b)}})(Wn);const gg={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe"}};function mg(t,e=[]){const r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;const i=t[n];r.push(...i.accounts)}),r}function eu(t,e){return t.includes(":")?[t]:e.chains||[]}const tu="base10",Ut="base16",Ro="base64pad",Mo="utf8",ru=0,Mr=1,wg=0,nu=1,Lo=12,Uo=32;function yg(){const t=bo.generateKeyPair();return{privateKey:Lt(t.secretKey,Ut),publicKey:Lt(t.publicKey,Ut)}}function Fo(){const t=ln.randomBytes(Uo);return Lt(t,Ut)}function bg(t,e){const r=bo.sharedKey(Mt(t,Ut),Mt(e,Ut)),n=new Mf(Qi.SHA256,r).expand(Uo);return Lt(n,Ut)}function vg(t){const e=Qi.hash(Mt(t,Ut));return Lt(e,Ut)}function rs(t){const e=Qi.hash(Mt(t,Mo));return Lt(e,Ut)}function _g(t){return Mt(`${t}`,tu)}function qn(t){return Number(Lt(t,tu))}function Eg(t){const e=_g(typeof t.type<"u"?t.type:ru);if(qn(e)===Mr&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?Mt(t.senderPublicKey,Ut):void 0,n=typeof t.iv<"u"?Mt(t.iv,Ut):ln.randomBytes(Lo),i=new ho.ChaCha20Poly1305(Mt(t.symKey,Ut)).seal(n,Mt(t.message,Mo));return Cg({type:e,sealed:i,iv:n,senderPublicKey:r})}function xg(t){const e=new ho.ChaCha20Poly1305(Mt(t.symKey,Ut)),{sealed:r,iv:n}=jo(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Lt(i,Mo)}function Cg(t){if(qn(t.type)===Mr){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Lt(vo([t.type,t.senderPublicKey,t.iv,t.sealed]),Ro)}return Lt(vo([t.type,t.iv,t.sealed]),Ro)}function jo(t){const e=Mt(t,Ro),r=e.slice(wg,nu),n=nu;if(qn(r)===Mr){const a=n+Uo,c=a+Lo,l=e.slice(n,a),p=e.slice(a,c),m=e.slice(c);return{type:r,sealed:m,iv:p,senderPublicKey:l}}const i=n+Lo,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Sg(t,e){const r=jo(t);return iu({type:qn(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Lt(r.senderPublicKey,Ut):void 0,receiverPublicKey:e?.receiverPublicKey})}function iu(t){const e=t?.type||ru;if(e===Mr){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function su(t){return t.type===Mr&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var Ig=Object.defineProperty,ou=Object.getOwnPropertySymbols,Dg=Object.prototype.hasOwnProperty,Og=Object.prototype.propertyIsEnumerable,au=(t,e,r)=>e in t?Ig(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cu=(t,e)=>{for(var r in e||(e={}))Dg.call(e,r)&&au(t,r,e[r]);if(ou)for(var r of ou(e))Og.call(e,r)&&au(t,r,e[r]);return t};const Ag="ReactNative",Vn={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},$g="js";function lu(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Pg(){return!Kl()&&!!Po()&&navigator.product===Ag}function Tg(){return!lu()&&!!Po()}function Ng(){return Pg()?Vn.reactNative:lu()?Vn.node:Tg()?Vn.browser:Vn.unknown}function Rg(t,e){let r=Wn.parse(t);return r=cu(cu({},r),e),t=Wn.stringify(r),t}function Mg(){return Zl()||{name:"",description:"",url:"",icons:[""]}}function Lg(){const t=bp();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function Ug(){var t;const e=Ng();return e===Vn.browser?[e,((t=Gl())==null?void 0:t.host)||"unknown"].join(":"):e}function Fg(t,e,r){const n=Lg(),i=Ug();return[[t,e].join("-"),[$g,r].join("-"),n,i].join("/")}function jg({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s}){const o=r.split("?"),a=Fg(t,e,n),c={auth:i,ua:a,projectId:s},l=Rg(o[1]||"",c);return o[0]+"?"+l}function Lr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function uu(t){return Object.fromEntries(t.entries())}function hu(t){return new Map(Object.entries(t))}function Ur(t=fe.FIVE_MINUTES,e){const r=fe.toMiliseconds(t||fe.FIVE_MINUTES);let n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,a)=>{s=setTimeout(()=>{a(new Error(e))},r),n=o,i=a})}}function Bo(t,e){return new Promise(async(r,n)=>{const i=setTimeout(()=>n(),e),s=await t;clearTimeout(i),r(s)})}function du(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Bg(t){return du("topic",t)}function kg(t){return du("id",t)}function fu(t){const[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function rr(t,e){return fe.fromMiliseconds((e||Date.now())+fe.toMiliseconds(t))}function yr(t){return Date.now()>=fe.toMiliseconds(t)}function et(t,e){return`${t}${e?`:${e}`:""}`}const Hg="irn";function ko(t){return t?.relay||{protocol:Hg}}function ns(t){const e=gg[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var zg=Object.defineProperty,pu=Object.getOwnPropertySymbols,Wg=Object.prototype.hasOwnProperty,qg=Object.prototype.propertyIsEnumerable,gu=(t,e,r)=>e in t?zg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vg=(t,e)=>{for(var r in e||(e={}))Wg.call(e,r)&&gu(t,r,e[r]);if(pu)for(var r of pu(e))qg.call(e,r)&&gu(t,r,e[r]);return t};function Kg(t,e="-"){const r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){const s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Gg(t){const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=Wn.parse(s);return{protocol:n,topic:i[0],version:parseInt(i[1],10),symKey:o.symKey,relay:Kg(o)}}function Zg(t,e="-"){const r="relay",n={};return Object.keys(t).forEach(i=>{const s=r+e+i;t[i]&&(n[s]=t[i])}),n}function Yg(t){return`${t.protocol}:${t.topic}@${t.version}?`+Wn.stringify(Vg({symKey:t.symKey},Zg(t.relay)))}function dn(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function Jg(t){const e=[];return Object.values(t).forEach(r=>{e.push(...dn(r.accounts))}),e}function Xg(t,e){const r=[];return Object.values(t).forEach(n=>{dn(n.accounts).includes(e)&&r.push(...n.methods)}),r}function Qg(t,e){const r=[];return Object.values(t).forEach(n=>{dn(n.accounts).includes(e)&&r.push(...n.events)}),r}function e3(t,e){const r=is(t,e);if(r)throw new Error(r.message);const n={};for(const[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}const t3={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},r3={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function ie(t,e){const{message:r,code:n}=r3[t];return{message:e?`${r} ${e}`:r,code:n}}function tt(t,e){const{message:r,code:n}=t3[t];return{message:e?`${r} ${e}`:r,code:n}}function br(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Kn(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function $t(t){return typeof t>"u"}function dt(t,e){return e&&$t(t)?!0:typeof t=="string"&&Boolean(t.trim().length)}function Ho(t,e){return e&&$t(t)?!0:typeof t=="number"&&!isNaN(t)}function n3(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return Lr(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],p=dn(a),m=r[o];(!Lr(eu(o,m),p)||!Lr(m.methods,c)||!Lr(m.events,l))&&(s=!1)}),s):!1}function zo(t){return dt(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function i3(t){if(dt(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&zo(r)}}return!1}function s3(t){if(dt(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function o3(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function a3(t){return t?.topic}function c3(t,e){let r=null;return dt(t?.publicKey,!1)||(r=ie("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function mu(t){let e=!0;return br(t)?t.length&&(e=t.every(r=>dt(r,!1))):e=!1,e}function l3(t,e,r){let n=null;return br(e)?e.forEach(i=>{n||(!zo(i)||!i.includes(t))&&(n=tt("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):n=tt("UNSUPPORTED_CHAINS",`${r}, chains ${e} should be an array of strings conforming to "namespace:chainId" format`),n}function u3(t,e){let r=null;return Object.entries(t).forEach(([n,i])=>{if(r)return;const s=l3(n,eu(n,i),`${e} requiredNamespace`);s&&(r=s)}),r}function h3(t,e){let r=null;return br(t)?t.forEach(n=>{r||i3(n)||(r=tt("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=tt("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function d3(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=h3(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function f3(t,e){let r=null;return mu(t?.methods)?mu(t?.events)||(r=tt("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=tt("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function wu(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=f3(n,`${e}, namespace`);i&&(r=i)}),r}function p3(t,e,r){let n=null;if(t&&Kn(t)){const i=wu(t,e);i&&(n=i);const s=u3(t,e);s&&(n=s)}else n=ie("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function is(t,e){let r=null;if(t&&Kn(t)){const n=wu(t,e);n&&(r=n);const i=d3(t,e);i&&(r=i)}else r=ie("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function yu(t){return dt(t.protocol,!0)}function g3(t,e){let r=!1;return e&&!t?r=!0:t&&br(t)&&t.length&&t.forEach(n=>{r=yu(n)}),r}function m3(t){return typeof t=="number"}function Ft(t){return typeof t<"u"&&typeof t!==null}function w3(t){return!(!t||typeof t!="object"||!t.code||!Ho(t.code,!1)||!t.message||!dt(t.message,!1))}function y3(t){return!($t(t)||!dt(t.method,!1))}function b3(t){return!($t(t)||$t(t.result)&&$t(t.error)||!Ho(t.id,!1)||!dt(t.jsonrpc,!1))}function v3(t){return!($t(t)||!dt(t.name,!1))}function bu(t,e){return!(!zo(e)||!Jg(t).includes(e))}function _3(t,e,r){return dt(r,!1)?Xg(t,e).includes(r):!1}function E3(t,e,r){return dt(r,!1)?Qg(t,e).includes(r):!1}function vu(t,e,r){let n=null;const i=x3(t),s=C3(e),o=Object.keys(i),a=Object.keys(s),c=_u(Object.keys(t)),l=_u(Object.keys(e)),p=c.filter(m=>!l.includes(m));return p.length&&(n=ie("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
|
|
14
|
+
***************************************************************************** */var Co=function(t,e){return Co=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Co(t,e)};function Cp(t,e){Co(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var So=function(){return So=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},So.apply(this,arguments)};function Sp(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Ip(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function Dp(t,e){return function(r,n){e(r,n,t)}}function Op(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Ap(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(m){o(m)}}function c(p){try{l(n.throw(p))}catch(m){o(m)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function $p(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(p){return c([l,p])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(p){l=[6,p],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Pp(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Tp(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Io(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ll(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function Np(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ll(arguments[e]));return t}function Rp(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function kn(t){return this instanceof kn?(this.v=t,this):new kn(t)}function Mp(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(w){n[w]&&(i[w]=function(y){return new Promise(function(E,T){s.push([w,y,E,T])>1||a(w,y)})})}function a(w,y){try{c(n[w](y))}catch(E){m(s[0][3],E)}}function c(w){w.value instanceof kn?Promise.resolve(w.value.v).then(l,p):m(s[0][2],w)}function l(w){a("next",w)}function p(w){a("throw",w)}function m(w,y){w(y),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Lp(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:kn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function Up(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Io=="function"?Io(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Fp(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function jp(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Bp(t){return t&&t.__esModule?t:{default:t}}function kp(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Hp(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var zp=Object.freeze({__proto__:null,__extends:Cp,get __assign(){return So},__rest:Sp,__decorate:Ip,__param:Dp,__metadata:Op,__awaiter:Ap,__generator:$p,__createBinding:Pp,__exportStar:Tp,__values:Io,__read:Ll,__spread:Np,__spreadArrays:Rp,__await:kn,__asyncGenerator:Mp,__asyncDelegator:Lp,__asyncValues:Up,__makeTemplateObject:Fp,__importStar:jp,__importDefault:Bp,__classPrivateFieldGet:kp,__classPrivateFieldSet:Hp}),ts=Pr(zp),Do={},Hn={},Ul;function Wp(){if(Ul)return Hn;Ul=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return Hn.delay=t,Hn}var Tr={},Oo={},Nr={},Fl;function qp(){return Fl||(Fl=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.ONE_THOUSAND=Nr.ONE_HUNDRED=void 0,Nr.ONE_HUNDRED=100,Nr.ONE_THOUSAND=1e3),Nr}var Ao={},jl;function Vp(){return jl||(jl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(Ao)),Ao}var Bl;function kl(){return Bl||(Bl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(qp(),t),e.__exportStar(Vp(),t)}(Oo)),Oo}var Hl;function Kp(){if(Hl)return Tr;Hl=1,Object.defineProperty(Tr,"__esModule",{value:!0}),Tr.fromMiliseconds=Tr.toMiliseconds=void 0;const t=kl();function e(n){return n*t.ONE_THOUSAND}Tr.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return Tr.fromMiliseconds=r,Tr}var zl;function Gp(){return zl||(zl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(Wp(),t),e.__exportStar(Kp(),t)}(Do)),Do}var un={},Wl;function Zp(){if(Wl)return un;Wl=1,Object.defineProperty(un,"__esModule",{value:!0}),un.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const n=this.get(r);if(typeof n.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const i=Date.now()-n.started;this.timestamps.set(r,{started:n.started,elapsed:i})}get(r){const n=this.timestamps.get(r);if(typeof n>"u")throw new Error(`No timestamp found for label: ${r}`);return n}elapsed(r){const n=this.get(r);return n.elapsed||Date.now()-n.started}}return un.Watch=t,un.default=t,un}var $o={},zn={},ql;function Yp(){if(ql)return zn;ql=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.IWatch=void 0;class t{}return zn.IWatch=t,zn}var Vl;function Jp(){return Vl||(Vl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),ts.__exportStar(Yp(),t)}($o)),$o}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(Gp(),t),e.__exportStar(Zp(),t),e.__exportStar(Jp(),t),e.__exportStar(kl(),t)})(fe);var ze={};Object.defineProperty(ze,"__esModule",{value:!0}),ze.getLocalStorage=ze.getLocalStorageOrThrow=ze.getCrypto=ze.getCryptoOrThrow=Gl=ze.getLocation=ze.getLocationOrThrow=Po=ze.getNavigator=ze.getNavigatorOrThrow=Kl=ze.getDocument=ze.getDocumentOrThrow=ze.getFromWindowOrThrow=ze.getFromWindow=void 0;function Rr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ze.getFromWindow=Rr;function hn(t){const e=Rr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ze.getFromWindowOrThrow=hn;function Xp(){return hn("document")}ze.getDocumentOrThrow=Xp;function Qp(){return Rr("document")}var Kl=ze.getDocument=Qp;function eg(){return hn("navigator")}ze.getNavigatorOrThrow=eg;function tg(){return Rr("navigator")}var Po=ze.getNavigator=tg;function rg(){return hn("location")}ze.getLocationOrThrow=rg;function ng(){return Rr("location")}var Gl=ze.getLocation=ng;function ig(){return hn("crypto")}ze.getCryptoOrThrow=ig;function sg(){return Rr("crypto")}ze.getCrypto=sg;function og(){return hn("localStorage")}ze.getLocalStorageOrThrow=og;function ag(){return Rr("localStorage")}ze.getLocalStorage=ag;var To={};Object.defineProperty(To,"__esModule",{value:!0});var Zl=To.getWindowMetadata=void 0;const Yl=ze;function cg(){let t,e;try{t=Yl.getDocumentOrThrow(),e=Yl.getLocationOrThrow()}catch{return null}function r(){const m=t.getElementsByTagName("link"),w=[];for(let y=0;y<m.length;y++){const E=m[y],T=E.getAttribute("rel");if(T&&T.toLowerCase().indexOf("icon")>-1){const N=E.getAttribute("href");if(N)if(N.toLowerCase().indexOf("https:")===-1&&N.toLowerCase().indexOf("http:")===-1&&N.indexOf("//")!==0){let U=e.protocol+"//"+e.host;if(N.indexOf("/")===0)U+=N;else{const C=e.pathname.split("/");C.pop();const D=C.join("/");U+=D+"/"+N}w.push(U)}else if(N.indexOf("//")===0){const U=e.protocol+N;w.push(U)}else w.push(N)}}return w}function n(...m){const w=t.getElementsByTagName("meta");for(let y=0;y<w.length;y++){const E=w[y],T=["itemprop","property","name"].map(N=>E.getAttribute(N)).filter(N=>N?m.includes(N):!1);if(T.length&&T){const N=E.getAttribute("content");if(N)return N}}return""}function i(){let m=n("name","og:site_name","og:title","twitter:title");return m||(m=t.title),m}function s(){return n("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,l=r();return{description:a,url:c,icons:l,name:o}}Zl=To.getWindowMetadata=cg;var Wn={},lg=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Jl="%[a-f0-9]{2}",Xl=new RegExp("("+Jl+")|([^%]+?)","gi"),Ql=new RegExp("("+Jl+")+","gi");function No(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],No(r),No(n))}function ug(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(Xl)||[],r=1;r<e.length;r++)t=No(e,r).join(""),e=t.match(Xl)||[];return t}}function hg(t){for(var e={"%FE%FF":"\uFFFD\uFFFD","%FF%FE":"\uFFFD\uFFFD"},r=Ql.exec(t);r;){try{e[r[0]]=decodeURIComponent(r[0])}catch{var n=ug(r[0]);n!==r[0]&&(e[r[0]]=n)}r=Ql.exec(t)}e["%C2"]="\uFFFD";for(var i=Object.keys(e),s=0;s<i.length;s++){var o=i[s];t=t.replace(new RegExp(o,"g"),e[o])}return t}var dg=function(t){if(typeof t!="string")throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof t+"`");try{return t=t.replace(/\+/g," "),decodeURIComponent(t)}catch{return hg(t)}},fg=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];const r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]},pg=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s<n.length;s++){var o=n[s],a=t[o];(i?e.indexOf(o)!==-1:e(o,a,t))&&(r[o]=a)}return r};(function(t){const e=lg,r=dg,n=fg,i=pg,s=C=>C==null,o=Symbol("encodeFragmentIdentifier");function a(C){switch(C.arrayFormat){case"index":return D=>(b,I)=>{const O=b.length;return I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,[p(D,C),"[",O,"]"].join("")]:[...b,[p(D,C),"[",p(O,C),"]=",p(I,C)].join("")]};case"bracket":return D=>(b,I)=>I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,[p(D,C),"[]"].join("")]:[...b,[p(D,C),"[]=",p(I,C)].join("")];case"colon-list-separator":return D=>(b,I)=>I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,[p(D,C),":list="].join("")]:[...b,[p(D,C),":list=",p(I,C)].join("")];case"comma":case"separator":case"bracket-separator":{const D=C.arrayFormat==="bracket-separator"?"[]=":"=";return b=>(I,O)=>O===void 0||C.skipNull&&O===null||C.skipEmptyString&&O===""?I:(O=O===null?"":O,I.length===0?[[p(b,C),D,p(O,C)].join("")]:[[I,p(O,C)].join(C.arrayFormatSeparator)])}default:return D=>(b,I)=>I===void 0||C.skipNull&&I===null||C.skipEmptyString&&I===""?b:I===null?[...b,p(D,C)]:[...b,[p(D,C),"=",p(I,C)].join("")]}}function c(C){let D;switch(C.arrayFormat){case"index":return(b,I,O)=>{if(D=/\[(\d*)\]$/.exec(b),b=b.replace(/\[\d*\]$/,""),!D){O[b]=I;return}O[b]===void 0&&(O[b]={}),O[b][D[1]]=I};case"bracket":return(b,I,O)=>{if(D=/(\[\])$/.exec(b),b=b.replace(/\[\]$/,""),!D){O[b]=I;return}if(O[b]===void 0){O[b]=[I];return}O[b]=[].concat(O[b],I)};case"colon-list-separator":return(b,I,O)=>{if(D=/(:list)$/.exec(b),b=b.replace(/:list$/,""),!D){O[b]=I;return}if(O[b]===void 0){O[b]=[I];return}O[b]=[].concat(O[b],I)};case"comma":case"separator":return(b,I,O)=>{const h=typeof I=="string"&&I.includes(C.arrayFormatSeparator),_=typeof I=="string"&&!h&&m(I,C).includes(C.arrayFormatSeparator);I=_?m(I,C):I;const H=h||_?I.split(C.arrayFormatSeparator).map(B=>m(B,C)):I===null?I:m(I,C);O[b]=H};case"bracket-separator":return(b,I,O)=>{const h=/(\[\])$/.test(b);if(b=b.replace(/\[\]$/,""),!h){O[b]=I&&m(I,C);return}const _=I===null?[]:I.split(C.arrayFormatSeparator).map(H=>m(H,C));if(O[b]===void 0){O[b]=_;return}O[b]=[].concat(O[b],_)};default:return(b,I,O)=>{if(O[b]===void 0){O[b]=I;return}O[b]=[].concat(O[b],I)}}}function l(C){if(typeof C!="string"||C.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function p(C,D){return D.encode?D.strict?e(C):encodeURIComponent(C):C}function m(C,D){return D.decode?r(C):C}function w(C){return Array.isArray(C)?C.sort():typeof C=="object"?w(Object.keys(C)).sort((D,b)=>Number(D)-Number(b)).map(D=>C[D]):C}function y(C){const D=C.indexOf("#");return D!==-1&&(C=C.slice(0,D)),C}function E(C){let D="";const b=C.indexOf("#");return b!==-1&&(D=C.slice(b)),D}function T(C){C=y(C);const D=C.indexOf("?");return D===-1?"":C.slice(D+1)}function N(C,D){return D.parseNumbers&&!Number.isNaN(Number(C))&&typeof C=="string"&&C.trim()!==""?C=Number(C):D.parseBooleans&&C!==null&&(C.toLowerCase()==="true"||C.toLowerCase()==="false")&&(C=C.toLowerCase()==="true"),C}function U(C,D){D=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},D),l(D.arrayFormatSeparator);const b=c(D),I=Object.create(null);if(typeof C!="string"||(C=C.trim().replace(/^[?#&]/,""),!C))return I;for(const O of C.split("&")){if(O==="")continue;let[h,_]=n(D.decode?O.replace(/\+/g," "):O,"=");_=_===void 0?null:["comma","separator","bracket-separator"].includes(D.arrayFormat)?_:m(_,D),b(m(h,D),_,I)}for(const O of Object.keys(I)){const h=I[O];if(typeof h=="object"&&h!==null)for(const _ of Object.keys(h))h[_]=N(h[_],D);else I[O]=N(h,D)}return D.sort===!1?I:(D.sort===!0?Object.keys(I).sort():Object.keys(I).sort(D.sort)).reduce((O,h)=>{const _=I[h];return Boolean(_)&&typeof _=="object"&&!Array.isArray(_)?O[h]=w(_):O[h]=_,O},Object.create(null))}t.extract=T,t.parse=U,t.stringify=(C,D)=>{if(!C)return"";D=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},D),l(D.arrayFormatSeparator);const b=_=>D.skipNull&&s(C[_])||D.skipEmptyString&&C[_]==="",I=a(D),O={};for(const _ of Object.keys(C))b(_)||(O[_]=C[_]);const h=Object.keys(O);return D.sort!==!1&&h.sort(D.sort),h.map(_=>{const H=C[_];return H===void 0?"":H===null?p(_,D):Array.isArray(H)?H.length===0&&D.arrayFormat==="bracket-separator"?p(_,D)+"[]":H.reduce(I(_),[]).join("&"):p(_,D)+"="+p(H,D)}).filter(_=>_.length>0).join("&")},t.parseUrl=(C,D)=>{D=Object.assign({decode:!0},D);const[b,I]=n(C,"#");return Object.assign({url:b.split("?")[0]||"",query:U(T(C),D)},D&&D.parseFragmentIdentifier&&I?{fragmentIdentifier:m(I,D)}:{})},t.stringifyUrl=(C,D)=>{D=Object.assign({encode:!0,strict:!0,[o]:!0},D);const b=y(C.url).split("?")[0]||"",I=t.extract(C.url),O=t.parse(I,{sort:!1}),h=Object.assign(O,C.query);let _=t.stringify(h,D);_&&(_=`?${_}`);let H=E(C.url);return C.fragmentIdentifier&&(H=`#${D[o]?p(C.fragmentIdentifier,D):C.fragmentIdentifier}`),`${b}${_}${H}`},t.pick=(C,D,b)=>{b=Object.assign({parseFragmentIdentifier:!0,[o]:!1},b);const{url:I,query:O,fragmentIdentifier:h}=t.parseUrl(C,b);return t.stringifyUrl({url:I,query:i(O,D),fragmentIdentifier:h},b)},t.exclude=(C,D,b)=>{const I=Array.isArray(D)?O=>!D.includes(O):(O,h)=>!D(O,h);return t.pick(C,I,b)}})(Wn);const gg={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe"}};function mg(t,e=[]){const r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;const i=t[n];r.push(...i.accounts)}),r}function eu(t,e){return t.includes(":")?[t]:e.chains||[]}const tu="base10",Ut="base16",Ro="base64pad",Mo="utf8",ru=0,Mr=1,wg=0,nu=1,Lo=12,Uo=32;function yg(){const t=bo.generateKeyPair();return{privateKey:Lt(t.secretKey,Ut),publicKey:Lt(t.publicKey,Ut)}}function Fo(){const t=ln.randomBytes(Uo);return Lt(t,Ut)}function bg(t,e){const r=bo.sharedKey(Mt(t,Ut),Mt(e,Ut)),n=new Mf(Qi.SHA256,r).expand(Uo);return Lt(n,Ut)}function vg(t){const e=Qi.hash(Mt(t,Ut));return Lt(e,Ut)}function rs(t){const e=Qi.hash(Mt(t,Mo));return Lt(e,Ut)}function _g(t){return Mt(`${t}`,tu)}function qn(t){return Number(Lt(t,tu))}function Eg(t){const e=_g(typeof t.type<"u"?t.type:ru);if(qn(e)===Mr&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?Mt(t.senderPublicKey,Ut):void 0,n=typeof t.iv<"u"?Mt(t.iv,Ut):ln.randomBytes(Lo),i=new ho.ChaCha20Poly1305(Mt(t.symKey,Ut)).seal(n,Mt(t.message,Mo));return Cg({type:e,sealed:i,iv:n,senderPublicKey:r})}function xg(t){const e=new ho.ChaCha20Poly1305(Mt(t.symKey,Ut)),{sealed:r,iv:n}=jo(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Lt(i,Mo)}function Cg(t){if(qn(t.type)===Mr){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Lt(vo([t.type,t.senderPublicKey,t.iv,t.sealed]),Ro)}return Lt(vo([t.type,t.iv,t.sealed]),Ro)}function jo(t){const e=Mt(t,Ro),r=e.slice(wg,nu),n=nu;if(qn(r)===Mr){const a=n+Uo,c=a+Lo,l=e.slice(n,a),p=e.slice(a,c),m=e.slice(c);return{type:r,sealed:m,iv:p,senderPublicKey:l}}const i=n+Lo,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Sg(t,e){const r=jo(t);return iu({type:qn(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Lt(r.senderPublicKey,Ut):void 0,receiverPublicKey:e?.receiverPublicKey})}function iu(t){const e=t?.type||ru;if(e===Mr){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function su(t){return t.type===Mr&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var Ig=Object.defineProperty,ou=Object.getOwnPropertySymbols,Dg=Object.prototype.hasOwnProperty,Og=Object.prototype.propertyIsEnumerable,au=(t,e,r)=>e in t?Ig(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cu=(t,e)=>{for(var r in e||(e={}))Dg.call(e,r)&&au(t,r,e[r]);if(ou)for(var r of ou(e))Og.call(e,r)&&au(t,r,e[r]);return t};const Ag="ReactNative",Vn={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},$g="js";function lu(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Pg(){return!Kl()&&!!Po()&&navigator.product===Ag}function Tg(){return!lu()&&!!Po()}function Ng(){return Pg()?Vn.reactNative:lu()?Vn.node:Tg()?Vn.browser:Vn.unknown}function Rg(t,e){let r=Wn.parse(t);return r=cu(cu({},r),e),t=Wn.stringify(r),t}function Mg(){return Zl()||{name:"",description:"",url:"",icons:[""]}}function Lg(){const t=bp();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function Ug(){var t;const e=Ng();return e===Vn.browser?[e,((t=Gl())==null?void 0:t.host)||"unknown"].join(":"):e}function Fg(t,e,r){const n=Lg(),i=Ug();return[[t,e].join("-"),[$g,r].join("-"),n,i].join("/")}function jg({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o}){const a=r.split("?"),c=Fg(t,e,n),l={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0},p=Rg(a[1]||"",l);return a[0]+"?"+p}function Lr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function uu(t){return Object.fromEntries(t.entries())}function hu(t){return new Map(Object.entries(t))}function Ur(t=fe.FIVE_MINUTES,e){const r=fe.toMiliseconds(t||fe.FIVE_MINUTES);let n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,a)=>{s=setTimeout(()=>{a(new Error(e))},r),n=o,i=a})}}function Bo(t,e){return new Promise(async(r,n)=>{const i=setTimeout(()=>n(),e),s=await t;clearTimeout(i),r(s)})}function du(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Bg(t){return du("topic",t)}function kg(t){return du("id",t)}function fu(t){const[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function rr(t,e){return fe.fromMiliseconds((e||Date.now())+fe.toMiliseconds(t))}function yr(t){return Date.now()>=fe.toMiliseconds(t)}function et(t,e){return`${t}${e?`:${e}`:""}`}const Hg="irn";function ko(t){return t?.relay||{protocol:Hg}}function ns(t){const e=gg[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var zg=Object.defineProperty,pu=Object.getOwnPropertySymbols,Wg=Object.prototype.hasOwnProperty,qg=Object.prototype.propertyIsEnumerable,gu=(t,e,r)=>e in t?zg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vg=(t,e)=>{for(var r in e||(e={}))Wg.call(e,r)&&gu(t,r,e[r]);if(pu)for(var r of pu(e))qg.call(e,r)&&gu(t,r,e[r]);return t};function Kg(t,e="-"){const r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){const s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Gg(t){const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=Wn.parse(s);return{protocol:n,topic:i[0],version:parseInt(i[1],10),symKey:o.symKey,relay:Kg(o)}}function Zg(t,e="-"){const r="relay",n={};return Object.keys(t).forEach(i=>{const s=r+e+i;t[i]&&(n[s]=t[i])}),n}function Yg(t){return`${t.protocol}:${t.topic}@${t.version}?`+Wn.stringify(Vg({symKey:t.symKey},Zg(t.relay)))}function dn(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function Jg(t){const e=[];return Object.values(t).forEach(r=>{e.push(...dn(r.accounts))}),e}function Xg(t,e){const r=[];return Object.values(t).forEach(n=>{dn(n.accounts).includes(e)&&r.push(...n.methods)}),r}function Qg(t,e){const r=[];return Object.values(t).forEach(n=>{dn(n.accounts).includes(e)&&r.push(...n.events)}),r}function e3(t,e){const r=is(t,e);if(r)throw new Error(r.message);const n={};for(const[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}const t3={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},r3={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function ie(t,e){const{message:r,code:n}=r3[t];return{message:e?`${r} ${e}`:r,code:n}}function tt(t,e){const{message:r,code:n}=t3[t];return{message:e?`${r} ${e}`:r,code:n}}function br(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Kn(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function $t(t){return typeof t>"u"}function dt(t,e){return e&&$t(t)?!0:typeof t=="string"&&Boolean(t.trim().length)}function Ho(t,e){return e&&$t(t)?!0:typeof t=="number"&&!isNaN(t)}function n3(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return Lr(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],p=dn(a),m=r[o];(!Lr(eu(o,m),p)||!Lr(m.methods,c)||!Lr(m.events,l))&&(s=!1)}),s):!1}function zo(t){return dt(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function i3(t){if(dt(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&zo(r)}}return!1}function s3(t){if(dt(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function o3(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function a3(t){return t?.topic}function c3(t,e){let r=null;return dt(t?.publicKey,!1)||(r=ie("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function mu(t){let e=!0;return br(t)?t.length&&(e=t.every(r=>dt(r,!1))):e=!1,e}function l3(t,e,r){let n=null;return br(e)?e.forEach(i=>{n||(!zo(i)||!i.includes(t))&&(n=tt("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):n=tt("UNSUPPORTED_CHAINS",`${r}, chains ${e} should be an array of strings conforming to "namespace:chainId" format`),n}function u3(t,e){let r=null;return Object.entries(t).forEach(([n,i])=>{if(r)return;const s=l3(n,eu(n,i),`${e} requiredNamespace`);s&&(r=s)}),r}function h3(t,e){let r=null;return br(t)?t.forEach(n=>{r||i3(n)||(r=tt("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=tt("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function d3(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=h3(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function f3(t,e){let r=null;return mu(t?.methods)?mu(t?.events)||(r=tt("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=tt("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function wu(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=f3(n,`${e}, namespace`);i&&(r=i)}),r}function p3(t,e,r){let n=null;if(t&&Kn(t)){const i=wu(t,e);i&&(n=i);const s=u3(t,e);s&&(n=s)}else n=ie("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function is(t,e){let r=null;if(t&&Kn(t)){const n=wu(t,e);n&&(r=n);const i=d3(t,e);i&&(r=i)}else r=ie("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function yu(t){return dt(t.protocol,!0)}function g3(t,e){let r=!1;return e&&!t?r=!0:t&&br(t)&&t.length&&t.forEach(n=>{r=yu(n)}),r}function m3(t){return typeof t=="number"}function Ft(t){return typeof t<"u"&&typeof t!==null}function w3(t){return!(!t||typeof t!="object"||!t.code||!Ho(t.code,!1)||!t.message||!dt(t.message,!1))}function y3(t){return!($t(t)||!dt(t.method,!1))}function b3(t){return!($t(t)||$t(t.result)&&$t(t.error)||!Ho(t.id,!1)||!dt(t.jsonrpc,!1))}function v3(t){return!($t(t)||!dt(t.name,!1))}function bu(t,e){return!(!zo(e)||!Jg(t).includes(e))}function _3(t,e,r){return dt(r,!1)?Xg(t,e).includes(r):!1}function E3(t,e,r){return dt(r,!1)?Qg(t,e).includes(r):!1}function vu(t,e,r){let n=null;const i=x3(t),s=C3(e),o=Object.keys(i),a=Object.keys(s),c=_u(Object.keys(t)),l=_u(Object.keys(e)),p=c.filter(m=>!l.includes(m));return p.length&&(n=ie("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
|
|
15
15
|
Required: ${p.toString()}
|
|
16
16
|
Received: ${Object.keys(e).toString()}`)),Lr(o,a)||(n=ie("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
|
|
17
17
|
Required: ${o.toString()}
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
70
70
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
71
71
|
PERFORMANCE OF THIS SOFTWARE.
|
|
72
|
-
***************************************************************************** */var aa=function(t,e){return aa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},aa(t,e)};function Fm(t,e){aa(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ca=function(){return ca=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},ca.apply(this,arguments)};function jm(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Bm(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function km(t,e){return function(r,n){e(r,n,t)}}function Hm(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function zm(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(m){o(m)}}function c(p){try{l(n.throw(p))}catch(m){o(m)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function Wm(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(p){return c([l,p])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(p){l=[6,p],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function qm(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Vm(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function la(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function rh(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function Km(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(rh(arguments[e]));return t}function Gm(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function li(t){return this instanceof li?(this.v=t,this):new li(t)}function Zm(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(w){n[w]&&(i[w]=function(y){return new Promise(function(E,T){s.push([w,y,E,T])>1||a(w,y)})})}function a(w,y){try{c(n[w](y))}catch(E){m(s[0][3],E)}}function c(w){w.value instanceof li?Promise.resolve(w.value.v).then(l,p):m(s[0][2],w)}function l(w){a("next",w)}function p(w){a("throw",w)}function m(w,y){w(y),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Ym(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:li(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function Jm(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof la=="function"?la(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Xm(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Qm(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function ew(t){return t&&t.__esModule?t:{default:t}}function tw(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function rw(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var nw=Object.freeze({__proto__:null,__extends:Fm,get __assign(){return ca},__rest:jm,__decorate:Bm,__param:km,__metadata:Hm,__awaiter:zm,__generator:Wm,__createBinding:qm,__exportStar:Vm,__values:la,__read:rh,__spread:Km,__spreadArrays:Gm,__await:li,__asyncGenerator:Zm,__asyncDelegator:Ym,__asyncValues:Jm,__makeTemplateObject:Xm,__importStar:Qm,__importDefault:ew,__classPrivateFieldGet:tw,__classPrivateFieldSet:rw}),iw=Pr(nw),hr={},nh;function sw(){if(nh)return hr;nh=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.isBrowserCryptoAvailable=hr.getSubtleCrypto=hr.getBrowerCrypto=void 0;function t(){return ht?.crypto||ht?.msCrypto||{}}hr.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}hr.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return hr.isBrowserCryptoAvailable=r,hr}var dr={},ih;function ow(){if(ih)return dr;ih=1,Object.defineProperty(dr,"__esModule",{value:!0}),dr.isBrowser=dr.isNode=dr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}dr.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}dr.isNode=e;function r(){return!t()&&!e()}return dr.isBrowser=r,dr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=iw;e.__exportStar(sw(),t),e.__exportStar(ow(),t)})(th);function aw(){const t=Date.now()*Math.pow(10,3),e=Math.floor(Math.random()*Math.pow(10,3));return t+e}function us(t,e,r){return{id:r||aw(),jsonrpc:"2.0",method:t,params:e}}function ua(t,e){return{id:t,jsonrpc:"2.0",result:e}}function hs(t,e,r){return{id:t,jsonrpc:"2.0",error:cw(e,r)}}function cw(t,e){return typeof t>"u"?Qu(Ju):(typeof t=="string"&&(t=Object.assign(Object.assign({},Qu(oa)),{message:t})),typeof e<"u"&&(t.data=e),Lm(t.code)&&(t=Um(t.code)),t)}class lw{}class uw extends lw{constructor(){super()}}class hw extends uw{constructor(e){super()}}const dw="^https?:",fw="^wss?:";function pw(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function sh(t,e){const r=pw(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function oh(t){return sh(t,dw)}function ah(t){return sh(t,fw)}function gw(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function ch(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function ha(t){return ch(t)&&"method"in t}function da(t){return ch(t)&&(fr(t)||Qt(t))}function fr(t){return"result"in t}function Qt(t){return"error"in t}class ui extends hw{constructor(e){super(e),this.events=new xt.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(us(e.method,e.params||[]),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Qt(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),da(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",()=>this.events.emit("disconnect")),this.connection.on("error",e=>this.events.emit("error",e)),this.hasRegisteredEventListeners=!0)}}const lh=10,mw=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),ww=()=>typeof window<"u",yw=mw();class bw{constructor(e){if(this.url=e,this.events=new xt.exports.EventEmitter,this.registering=!1,!ah(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=()=>{this.onClose(),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ai(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!ah(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=th.isReactNative()?void 0:{rejectUnauthorized:!gw(e)},s=new yw(e,[],i);ww()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=()=>this.onClose(),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(){this.socket=void 0,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ia(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=hs(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return eh(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>lh&&this.events.setMaxListeners(lh)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",r),r}}var fa={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,s=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",p="[object Boolean]",m="[object Date]",w="[object Error]",y="[object Function]",E="[object GeneratorFunction]",T="[object Map]",N="[object Number]",U="[object Null]",C="[object Object]",D="[object Promise]",b="[object Proxy]",I="[object RegExp]",O="[object Set]",h="[object String]",_="[object Symbol]",H="[object Undefined]",B="[object WeakMap]",q="[object ArrayBuffer]",X="[object DataView]",te="[object Float32Array]",x="[object Float64Array]",A="[object Int8Array]",G="[object Int16Array]",K="[object Int32Array]",W="[object Uint8Array]",z="[object Uint8ClampedArray]",J="[object Uint16Array]",Z="[object Uint32Array]",ce=/[\\^$.*+?()[\]{}|]/g,Q=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,oe={};oe[te]=oe[x]=oe[A]=oe[G]=oe[K]=oe[W]=oe[z]=oe[J]=oe[Z]=!0,oe[a]=oe[c]=oe[q]=oe[p]=oe[X]=oe[m]=oe[w]=oe[y]=oe[T]=oe[N]=oe[C]=oe[I]=oe[O]=oe[h]=oe[B]=!1;var Ce=typeof ht=="object"&&ht&&ht.Object===Object&&ht,j=typeof self=="object"&&self&&self.Object===Object&&self,F=Ce||j||Function("return this")(),R=e&&!e.nodeType&&e,f=R&&!0&&t&&!t.nodeType&&t,$=f&&f.exports===R,ee=$&&Ce.process,ne=function(){try{return ee&&ee.binding&&ee.binding("util")}catch{}}(),Ee=ne&&ne.isTypedArray;function Le(S,M){for(var Y=-1,ae=S==null?0:S.length,We=0,Ie=[];++Y<ae;){var Qe=S[Y];M(Qe,Y,S)&&(Ie[We++]=Qe)}return Ie}function Pe(S,M){for(var Y=-1,ae=M.length,We=S.length;++Y<ae;)S[We+Y]=M[Y];return S}function Ue(S,M){for(var Y=-1,ae=S==null?0:S.length;++Y<ae;)if(M(S[Y],Y,S))return!0;return!1}function Ge(S,M){for(var Y=-1,ae=Array(S);++Y<S;)ae[Y]=M(Y);return ae}function qe(S){return function(M){return S(M)}}function Te(S,M){return S.has(M)}function De(S,M){return S?.[M]}function me(S){var M=-1,Y=Array(S.size);return S.forEach(function(ae,We){Y[++M]=[We,ae]}),Y}function Se(S,M){return function(Y){return S(M(Y))}}function Oe(S){var M=-1,Y=Array(S.size);return S.forEach(function(ae){Y[++M]=ae}),Y}var ge=Array.prototype,xe=Function.prototype,g=Object.prototype,u=F["__core-js_shared__"],d=xe.toString,v=g.hasOwnProperty,P=function(){var S=/[^.]+$/.exec(u&&u.keys&&u.keys.IE_PROTO||"");return S?"Symbol(src)_1."+S:""}(),L=g.toString,k=RegExp("^"+d.call(v).replace(ce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),se=$?F.Buffer:void 0,ue=F.Symbol,Re=F.Uint8Array,Fe=g.propertyIsEnumerable,Me=ge.splice,Wt=ue?ue.toStringTag:void 0,nn=Object.getOwnPropertySymbols,Hi=se?se.isBuffer:void 0,io=Se(Object.keys,Object),rt=Fn(F,"DataView"),Je=Fn(F,"Map"),nt=Fn(F,"Promise"),it=Fn(F,"Set"),st=Fn(F,"WeakMap"),Xe=Fn(Object,"create"),gt=on(rt),mt=on(Je),wt=on(nt),yt=on(it),bt=on(st),ut=ue?ue.prototype:void 0,ot=ut?ut.valueOf:void 0;function Ve(S){var M=-1,Y=S==null?0:S.length;for(this.clear();++M<Y;){var ae=S[M];this.set(ae[0],ae[1])}}function vt(){this.__data__=Xe?Xe(null):{},this.size=0}function _t(S){var M=this.has(S)&&delete this.__data__[S];return this.size-=M?1:0,M}function d7(S){var M=this.__data__;if(Xe){var Y=M[S];return Y===n?void 0:Y}return v.call(M,S)?M[S]:void 0}function f7(S){var M=this.__data__;return Xe?M[S]!==void 0:v.call(M,S)}function p7(S,M){var Y=this.__data__;return this.size+=this.has(S)?0:1,Y[S]=Xe&&M===void 0?n:M,this}Ve.prototype.clear=vt,Ve.prototype.delete=_t,Ve.prototype.get=d7,Ve.prototype.has=f7,Ve.prototype.set=p7;function gr(S){var M=-1,Y=S==null?0:S.length;for(this.clear();++M<Y;){var ae=S[M];this.set(ae[0],ae[1])}}function g7(){this.__data__=[],this.size=0}function m7(S){var M=this.__data__,Y=oo(M,S);if(Y<0)return!1;var ae=M.length-1;return Y==ae?M.pop():Me.call(M,Y,1),--this.size,!0}function w7(S){var M=this.__data__,Y=oo(M,S);return Y<0?void 0:M[Y][1]}function y7(S){return oo(this.__data__,S)>-1}function b7(S,M){var Y=this.__data__,ae=oo(Y,S);return ae<0?(++this.size,Y.push([S,M])):Y[ae][1]=M,this}gr.prototype.clear=g7,gr.prototype.delete=m7,gr.prototype.get=w7,gr.prototype.has=y7,gr.prototype.set=b7;function sn(S){var M=-1,Y=S==null?0:S.length;for(this.clear();++M<Y;){var ae=S[M];this.set(ae[0],ae[1])}}function v7(){this.size=0,this.__data__={hash:new Ve,map:new(Je||gr),string:new Ve}}function _7(S){var M=ao(this,S).delete(S);return this.size-=M?1:0,M}function E7(S){return ao(this,S).get(S)}function x7(S){return ao(this,S).has(S)}function C7(S,M){var Y=ao(this,S),ae=Y.size;return Y.set(S,M),this.size+=Y.size==ae?0:1,this}sn.prototype.clear=v7,sn.prototype.delete=_7,sn.prototype.get=E7,sn.prototype.has=x7,sn.prototype.set=C7;function so(S){var M=-1,Y=S==null?0:S.length;for(this.__data__=new sn;++M<Y;)this.add(S[M])}function S7(S){return this.__data__.set(S,n),this}function I7(S){return this.__data__.has(S)}so.prototype.add=so.prototype.push=S7,so.prototype.has=I7;function Or(S){var M=this.__data__=new gr(S);this.size=M.size}function D7(){this.__data__=new gr,this.size=0}function O7(S){var M=this.__data__,Y=M.delete(S);return this.size=M.size,Y}function A7(S){return this.__data__.get(S)}function $7(S){return this.__data__.has(S)}function P7(S,M){var Y=this.__data__;if(Y instanceof gr){var ae=Y.__data__;if(!Je||ae.length<r-1)return ae.push([S,M]),this.size=++Y.size,this;Y=this.__data__=new sn(ae)}return Y.set(S,M),this.size=Y.size,this}Or.prototype.clear=D7,Or.prototype.delete=O7,Or.prototype.get=A7,Or.prototype.has=$7,Or.prototype.set=P7;function T7(S,M){var Y=co(S),ae=!Y&&K7(S),We=!Y&&!ae&&zc(S),Ie=!Y&&!ae&&!We&&Vd(S),Qe=Y||ae||We||Ie,Et=Qe?Ge(S.length,String):[],It=Et.length;for(var Ze in S)(M||v.call(S,Ze))&&!(Qe&&(Ze=="length"||We&&(Ze=="offset"||Ze=="parent")||Ie&&(Ze=="buffer"||Ze=="byteLength"||Ze=="byteOffset")||H7(Ze,It)))&&Et.push(Ze);return Et}function oo(S,M){for(var Y=S.length;Y--;)if(Hd(S[Y][0],M))return Y;return-1}function N7(S,M,Y){var ae=M(S);return co(S)?ae:Pe(ae,Y(S))}function zi(S){return S==null?S===void 0?H:U:Wt&&Wt in Object(S)?B7(S):V7(S)}function Fd(S){return Wi(S)&&zi(S)==a}function jd(S,M,Y,ae,We){return S===M?!0:S==null||M==null||!Wi(S)&&!Wi(M)?S!==S&&M!==M:R7(S,M,Y,ae,jd,We)}function R7(S,M,Y,ae,We,Ie){var Qe=co(S),Et=co(M),It=Qe?c:Ar(S),Ze=Et?c:Ar(M);It=It==a?C:It,Ze=Ze==a?C:Ze;var qt=It==C,er=Ze==C,At=It==Ze;if(At&&zc(S)){if(!zc(M))return!1;Qe=!0,qt=!1}if(At&&!qt)return Ie||(Ie=new Or),Qe||Vd(S)?Bd(S,M,Y,ae,We,Ie):F7(S,M,It,Y,ae,We,Ie);if(!(Y&i)){var Yt=qt&&v.call(S,"__wrapped__"),Jt=er&&v.call(M,"__wrapped__");if(Yt||Jt){var $r=Yt?S.value():S,mr=Jt?M.value():M;return Ie||(Ie=new Or),We($r,mr,Y,ae,Ie)}}return At?(Ie||(Ie=new Or),j7(S,M,Y,ae,We,Ie)):!1}function M7(S){if(!qd(S)||W7(S))return!1;var M=zd(S)?k:Q;return M.test(on(S))}function L7(S){return Wi(S)&&Wd(S.length)&&!!oe[zi(S)]}function U7(S){if(!q7(S))return io(S);var M=[];for(var Y in Object(S))v.call(S,Y)&&Y!="constructor"&&M.push(Y);return M}function Bd(S,M,Y,ae,We,Ie){var Qe=Y&i,Et=S.length,It=M.length;if(Et!=It&&!(Qe&&It>Et))return!1;var Ze=Ie.get(S);if(Ze&&Ie.get(M))return Ze==M;var qt=-1,er=!0,At=Y&s?new so:void 0;for(Ie.set(S,M),Ie.set(M,S);++qt<Et;){var Yt=S[qt],Jt=M[qt];if(ae)var $r=Qe?ae(Jt,Yt,qt,M,S,Ie):ae(Yt,Jt,qt,S,M,Ie);if($r!==void 0){if($r)continue;er=!1;break}if(At){if(!Ue(M,function(mr,an){if(!Te(At,an)&&(Yt===mr||We(Yt,mr,Y,ae,Ie)))return At.push(an)})){er=!1;break}}else if(!(Yt===Jt||We(Yt,Jt,Y,ae,Ie))){er=!1;break}}return Ie.delete(S),Ie.delete(M),er}function F7(S,M,Y,ae,We,Ie,Qe){switch(Y){case X:if(S.byteLength!=M.byteLength||S.byteOffset!=M.byteOffset)return!1;S=S.buffer,M=M.buffer;case q:return!(S.byteLength!=M.byteLength||!Ie(new Re(S),new Re(M)));case p:case m:case N:return Hd(+S,+M);case w:return S.name==M.name&&S.message==M.message;case I:case h:return S==M+"";case T:var Et=me;case O:var It=ae&i;if(Et||(Et=Oe),S.size!=M.size&&!It)return!1;var Ze=Qe.get(S);if(Ze)return Ze==M;ae|=s,Qe.set(S,M);var qt=Bd(Et(S),Et(M),ae,We,Ie,Qe);return Qe.delete(S),qt;case _:if(ot)return ot.call(S)==ot.call(M)}return!1}function j7(S,M,Y,ae,We,Ie){var Qe=Y&i,Et=kd(S),It=Et.length,Ze=kd(M),qt=Ze.length;if(It!=qt&&!Qe)return!1;for(var er=It;er--;){var At=Et[er];if(!(Qe?At in M:v.call(M,At)))return!1}var Yt=Ie.get(S);if(Yt&&Ie.get(M))return Yt==M;var Jt=!0;Ie.set(S,M),Ie.set(M,S);for(var $r=Qe;++er<It;){At=Et[er];var mr=S[At],an=M[At];if(ae)var Kd=Qe?ae(an,mr,At,M,S,Ie):ae(mr,an,At,S,M,Ie);if(!(Kd===void 0?mr===an||We(mr,an,Y,ae,Ie):Kd)){Jt=!1;break}$r||($r=At=="constructor")}if(Jt&&!$r){var lo=S.constructor,uo=M.constructor;lo!=uo&&"constructor"in S&&"constructor"in M&&!(typeof lo=="function"&&lo instanceof lo&&typeof uo=="function"&&uo instanceof uo)&&(Jt=!1)}return Ie.delete(S),Ie.delete(M),Jt}function kd(S){return N7(S,Y7,k7)}function ao(S,M){var Y=S.__data__;return z7(M)?Y[typeof M=="string"?"string":"hash"]:Y.map}function Fn(S,M){var Y=De(S,M);return M7(Y)?Y:void 0}function B7(S){var M=v.call(S,Wt),Y=S[Wt];try{S[Wt]=void 0;var ae=!0}catch{}var We=L.call(S);return ae&&(M?S[Wt]=Y:delete S[Wt]),We}var k7=nn?function(S){return S==null?[]:(S=Object(S),Le(nn(S),function(M){return Fe.call(S,M)}))}:J7,Ar=zi;(rt&&Ar(new rt(new ArrayBuffer(1)))!=X||Je&&Ar(new Je)!=T||nt&&Ar(nt.resolve())!=D||it&&Ar(new it)!=O||st&&Ar(new st)!=B)&&(Ar=function(S){var M=zi(S),Y=M==C?S.constructor:void 0,ae=Y?on(Y):"";if(ae)switch(ae){case gt:return X;case mt:return T;case wt:return D;case yt:return O;case bt:return B}return M});function H7(S,M){return M=M??o,!!M&&(typeof S=="number"||pe.test(S))&&S>-1&&S%1==0&&S<M}function z7(S){var M=typeof S;return M=="string"||M=="number"||M=="symbol"||M=="boolean"?S!=="__proto__":S===null}function W7(S){return!!P&&P in S}function q7(S){var M=S&&S.constructor,Y=typeof M=="function"&&M.prototype||g;return S===Y}function V7(S){return L.call(S)}function on(S){if(S!=null){try{return d.call(S)}catch{}try{return S+""}catch{}}return""}function Hd(S,M){return S===M||S!==S&&M!==M}var K7=Fd(function(){return arguments}())?Fd:function(S){return Wi(S)&&v.call(S,"callee")&&!Fe.call(S,"callee")},co=Array.isArray;function G7(S){return S!=null&&Wd(S.length)&&!zd(S)}var zc=Hi||X7;function Z7(S,M){return jd(S,M)}function zd(S){if(!qd(S))return!1;var M=zi(S);return M==y||M==E||M==l||M==b}function Wd(S){return typeof S=="number"&&S>-1&&S%1==0&&S<=o}function qd(S){var M=typeof S;return S!=null&&(M=="object"||M=="function")}function Wi(S){return S!=null&&typeof S=="object"}var Vd=Ee?qe(Ee):L7;function Y7(S){return G7(S)?T7(S):U7(S)}function J7(){return[]}function X7(){return!1}t.exports=Z7})(fa,fa.exports);var vw=fa.exports,_w=Object.defineProperty,uh=Object.getOwnPropertySymbols,Ew=Object.prototype.hasOwnProperty,xw=Object.prototype.propertyIsEnumerable,hh=(t,e,r)=>e in t?_w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tt=(t,e)=>{for(var r in e||(e={}))Ew.call(e,r)&&hh(t,r,e[r]);if(uh)for(var r of uh(e))xw.call(e,r)&&hh(t,r,e[r]);return t};function Cw(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var T=0,N=0,U=0,C=E.length;U!==C&&E[U]===0;)U++,T++;for(var D=(C-U)*p+1>>>0,b=new Uint8Array(D);U!==C;){for(var I=E[U],O=0,h=D-1;(I!==0||O<N)&&h!==-1;h--,O++)I+=256*b[h]>>>0,b[h]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");N=O,U++}for(var _=D-N;_!==D&&b[_]===0;)_++;for(var H=c.repeat(T);_<D;++_)H+=t.charAt(b[_]);return H}function w(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var T=0;if(E[T]!==" "){for(var N=0,U=0;E[T]===c;)N++,T++;for(var C=(E.length-T)*l+1>>>0,D=new Uint8Array(C);E[T];){var b=r[E.charCodeAt(T)];if(b===255)return;for(var I=0,O=C-1;(b!==0||I<U)&&O!==-1;O--,I++)b+=a*D[O]>>>0,D[O]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");U=I,T++}if(E[T]!==" "){for(var h=C-U;h!==C&&D[h]===0;)h++;for(var _=new Uint8Array(N+(C-h)),H=N;h!==C;)_[H++]=D[h++];return _}}}function y(E){var T=w(E);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:w,decode:y}}var Sw=Cw,Iw=Sw;const dh=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Dw=t=>new TextEncoder().encode(t),Ow=t=>new TextDecoder().decode(t);class Aw{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class $w{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return fh(this,e)}}class Pw{constructor(e){this.decoders=e}or(e){return fh(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const fh=(t,e)=>new Pw(Tt(Tt({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class Tw{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Aw(e,r,n),this.decoder=new $w(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ds=({name:t,prefix:e,encode:r,decode:n})=>new Tw(t,e,r,n),hi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Iw(r,e);return ds({prefix:t,name:e,encode:n,decode:s=>dh(i(s))})},Nw=(t,e,r,n)=>{const i={};for(let p=0;p<e.length;++p)i[e[p]]=p;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let p=0;p<s;++p){const m=i[t[p]];if(m===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|m,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Rw=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},St=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ds({prefix:e,name:t,encode(i){return Rw(i,n,r)},decode(i){return Nw(i,n,r,t)}}),Mw=ds({prefix:"\0",name:"identity",encode:t=>Ow(t),decode:t=>Dw(t)});var Lw=Object.freeze({__proto__:null,identity:Mw});const Uw=St({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Fw=Object.freeze({__proto__:null,base2:Uw});const jw=St({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Bw=Object.freeze({__proto__:null,base8:jw});const kw=hi({prefix:"9",name:"base10",alphabet:"0123456789"});var Hw=Object.freeze({__proto__:null,base10:kw});const zw=St({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ww=St({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qw=Object.freeze({__proto__:null,base16:zw,base16upper:Ww});const Vw=St({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Kw=St({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gw=St({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zw=St({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Yw=St({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jw=St({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xw=St({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qw=St({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),e5=St({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var t5=Object.freeze({__proto__:null,base32:Vw,base32upper:Kw,base32pad:Gw,base32padupper:Zw,base32hex:Yw,base32hexupper:Jw,base32hexpad:Xw,base32hexpadupper:Qw,base32z:e5});const r5=hi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),n5=hi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var i5=Object.freeze({__proto__:null,base36:r5,base36upper:n5});const s5=hi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),o5=hi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var a5=Object.freeze({__proto__:null,base58btc:s5,base58flickr:o5});const c5=St({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),l5=St({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),u5=St({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),h5=St({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var d5=Object.freeze({__proto__:null,base64:c5,base64pad:l5,base64url:u5,base64urlpad:h5});const ph=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),f5=ph.reduce((t,e,r)=>(t[r]=e,t),[]),p5=ph.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function g5(t){return t.reduce((e,r)=>(e+=f5[r],e),"")}function m5(t){const e=[];for(const r of t){const n=p5[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const w5=ds({prefix:"\u{1F680}",name:"base256emoji",encode:g5,decode:m5});var y5=Object.freeze({__proto__:null,base256emoji:w5}),b5=mh,gh=128,v5=127,_5=~v5,E5=Math.pow(2,31);function mh(t,e,r){e=e||[],r=r||0;for(var n=r;t>=E5;)e[r++]=t&255|gh,t/=128;for(;t&_5;)e[r++]=t&255|gh,t>>>=7;return e[r]=t|0,mh.bytes=r-n+1,e}var x5=pa,C5=128,wh=127;function pa(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw pa.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&wh)<<i:(o&wh)*Math.pow(2,i),i+=7}while(o>=C5);return pa.bytes=s-n,r}var S5=Math.pow(2,7),I5=Math.pow(2,14),D5=Math.pow(2,21),O5=Math.pow(2,28),A5=Math.pow(2,35),$5=Math.pow(2,42),P5=Math.pow(2,49),T5=Math.pow(2,56),N5=Math.pow(2,63),R5=function(t){return t<S5?1:t<I5?2:t<D5?3:t<O5?4:t<A5?5:t<$5?6:t<P5?7:t<T5?8:t<N5?9:10},M5={encode:b5,decode:x5,encodingLength:R5},yh=M5;const bh=(t,e,r=0)=>(yh.encode(t,e,r),e),vh=t=>yh.encodingLength(t),ga=(t,e)=>{const r=e.byteLength,n=vh(t),i=n+vh(r),s=new Uint8Array(i+r);return bh(t,s,0),bh(r,s,n),s.set(e,i),new L5(t,r,e,s)};class L5{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const _h=({name:t,code:e,encode:r})=>new U5(t,e,r);class U5{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ga(this.code,r):r.then(n=>ga(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Eh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),F5=_h({name:"sha2-256",code:18,encode:Eh("SHA-256")}),j5=_h({name:"sha2-512",code:19,encode:Eh("SHA-512")});var B5=Object.freeze({__proto__:null,sha256:F5,sha512:j5});const xh=0,k5="identity",Ch=dh;var H5=Object.freeze({__proto__:null,identity:{code:xh,name:k5,encode:Ch,digest:t=>ga(xh,Ch(t))}});new TextEncoder,new TextDecoder;const Sh=Tt(Tt(Tt(Tt(Tt(Tt(Tt(Tt(Tt(Tt({},Lw),Fw),Bw),Hw),qw),t5),i5),a5),d5),y5);Tt(Tt({},B5),H5);function z5(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Ih(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Dh=Ih("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ma=Ih("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=z5(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),W5=Tt({utf8:Dh,"utf-8":Dh,hex:Sh.base16,latin1:ma,ascii:ma,binary:ma},Sh);function q5(t,e="utf8"){const r=W5[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}const Oh="wc",V5=2,wa="core",vr=`${Oh}@${2}:${wa}:`,K5={name:wa,logger:"error"},G5={database:":memory:"},Z5="crypto",Ah="client_ed25519_seed",Y5=fe.ONE_DAY,J5="keychain",X5="0.3",Q5="messages",ey="0.3",ty=fe.SIX_HOURS,ry="publisher",$h="irn",ny="error",Ph="wss://relay.walletconnect.com",iy="relayer",ft={message:"relayer_message",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},sy="_subscription",fs={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Th=fe.ONE_SECOND,oy="2.4.9",ay="0.3",ir={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},cy="subscription",ly="0.3",uy=fe.FIVE_SECONDS*1e3,hy="pairing",dy="0.3",di={wc_pairingDelete:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:0},res:{ttl:fe.ONE_DAY,prompt:!1,tag:0}}},sr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},fy="history",py="0.3",gy="expirer",Vt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},my="0.3";class wy{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=J5,this.version=X5,this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=ie("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=Be.generateChildLogger(r,this.name)}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,uu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?hu(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class yy{constructor(e,r,n){this.core=e,this.logger=r,this.name=Z5,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Yu(i);return Zu(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=yg();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Yu(s),a=Fo();return await $m(a,i,Y5,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=bg(a,s);return this.setSymKey(c,o)},this.setSymKey=async(i,s)=>{this.isInitialized();const o=s||vg(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();const a=iu(o),c=ai(s);if(su(a)){const w=a.senderPublicKey,y=a.receiverPublicKey;i=await this.generateSharedKey(w,y)}const l=this.getSymKey(i),{type:p,senderPublicKey:m}=a;return Eg({type:p,symKey:l,message:c,senderPublicKey:m})},this.decode=async(i,s,o)=>{this.isInitialized();const a=Sg(s,o);if(su(a)){const p=a.receiverPublicKey,m=a.senderPublicKey;i=await this.generateSharedKey(p,m)}const c=this.getSymKey(i),l=xg({symKey:c,encoded:s});return ia(l)},this.core=e,this.logger=Be.generateChildLogger(r,this.name),this.keychain=n||new wy(this.core,this.logger)}get context(){return Be.getLoggerContext(this.logger)}getPayloadType(e){const r=jo(e);return qn(r.type)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ah)}catch{e=Fo(),await this.keychain.set(Ah,e)}return q5(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class by extends lm{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=Q5,this.version=ey,this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const s=rs(i);let o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const s=this.get(n),o=rs(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=Be.generateChildLogger(e,this.name),this.core=r}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,uu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?hu(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class vy extends um{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new xt.exports.EventEmitter,this.name=ry,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(n,i,s)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});try{const o=s?.ttl||ty,a=ko(s),c=s?.prompt||!1,l=s?.tag||0,p={topic:n,message:i,opts:{ttl:o,relay:a,prompt:c,tag:l}},m=rs(i);this.queue.set(m,p);try{await await Bo(this.rpcPublish(n,i,o,a,c,l),this.publishTimeout),this.relayer.events.emit(ft.publish,p)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(ft.connection_stalled);return}this.onPublish(m,p),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}})}catch(o){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(o),o}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=Be.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return Be.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o){var a,c,l,p;const m={method:ns(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o}};return $t((a=m.params)==null?void 0:a.prompt)&&((c=m.params)==null||delete c.prompt),$t((l=m.params)==null?void 0:l.tag)&&((p=m.params)==null||delete p.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m}),this.relayer.provider.request(m)}onPublish(e,r){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(ri.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()})}}class _y{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var Ey=Object.defineProperty,xy=Object.defineProperties,Cy=Object.getOwnPropertyDescriptors,Nh=Object.getOwnPropertySymbols,Sy=Object.prototype.hasOwnProperty,Iy=Object.prototype.propertyIsEnumerable,Rh=(t,e,r)=>e in t?Ey(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fi=(t,e)=>{for(var r in e||(e={}))Sy.call(e,r)&&Rh(t,r,e[r]);if(Nh)for(var r of Nh(e))Iy.call(e,r)&&Rh(t,r,e[r]);return t},ya=(t,e)=>xy(t,Cy(e));class Dy extends fm{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new _y,this.events=new xt.exports.EventEmitter,this.name=cy,this.version=ly,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=vr,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=ko(i),o={topic:n,relay:s};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s);return this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,s)=>{const o=new fe.Watch;o.start(this.pendingSubscriptionWatchLabel);const a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),i(!0)),o.elapsed(this.pendingSubscriptionWatchLabel)>=uy&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),s(!1))},this.pollingInterval)}),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Be.generateChildLogger(r,this.name),this.clientId=""}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=ko(n);await this.rpcUnsubscribe(e,r,i);const s=tt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:ns(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Bo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(ft.connection_stalled)}return rs(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:ns(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await Bo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(ft.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:ns(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.provider.request(i)}onSubscribe(e,r){this.setSubscription(e,ya(fi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,fi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,fi({},r)),this.topicMap.set(r.topic,e),this.events.emit(ir.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(ir.deleted,ya(fi({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ir.sync)}async reset(){if(!this.cached.length)return;const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}this.events.emit(ir.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);this.onBatchSubscribe(r.map((n,i)=>ya(fi({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(ri.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(ft.connect,async()=>{await this.onConnect()}),this.relayer.on(ft.disconnect,()=>{this.onDisconnect()}),this.events.on(ir.created,async e=>{const r=ir.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(ir.deleted,async e=>{const r=ir.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var Oy=Object.defineProperty,Mh=Object.getOwnPropertySymbols,Ay=Object.prototype.hasOwnProperty,$y=Object.prototype.propertyIsEnumerable,Lh=(t,e,r)=>e in t?Oy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Py=(t,e)=>{for(var r in e||(e={}))Ay.call(e,r)&&Lh(t,r,e[r]);if(Mh)for(var r of Mh(e))$y.call(e,r)&&Lh(t,r,e[r]);return t};class Ty extends hm{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new xt.exports.EventEmitter,this.name=iy,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Be.generateChildLogger(e.logger,this.name):Gn(Be.getDefaultLoggerOptions({level:e.logger||ny})),this.messages=new by(this.logger,e.core),this.subscriber=new Dy(this,this.logger),this.publisher=new vy(this,this.logger),this.relayUrl=e?.relayUrl||Ph,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),this.provider=await this.createProvider(),await Promise.all([this.messages.init(),this.transportOpen(),this.subscriber.init()]),this.registerEventListeners(),this.initialized=!0}get context(){return Be.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){this.isInitialized();let n="";return await Promise.all([new Promise(i=>{this.subscriber.once(ir.created,s=>{s.topic===e&&i()})}),new Promise(async i=>{n=await this.subscriber.subscribe(e,r),i()})]),n}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(ft.transport_closed))}async transportOpen(e){if(!this.reconnecting){this.relayUrl=e||this.relayUrl,this.transportExplicitlyClosed=!1,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(ir.resubscribed,()=>{r()})}),await Promise.race([new Promise(async r=>{await this.provider.connect(),this.removeListener(ft.transport_closed,this.rejectTransportOpen),r()}),new Promise(r=>this.once(ft.transport_closed,this.rejectTransportOpen))])])}catch(r){const n=r;if(!/socket hang up/i.test(n.message))throw r;this.logger.error(r),this.events.emit(ft.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(await this.transportClose(),await new Promise(r=>setTimeout(r,Th)),await this.transportOpen(e))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);return new ui(new bw(jg({sdkVersion:oy,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e})))}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;return await this.subscriber.isSubscribed(r)?this.messages.has(r,n):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),ha(e)){if(!e.method.endsWith(sy))return;const r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Py({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(ft.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=ua(e.id,!0);await this.provider.connection.send(r)}registerEventListeners(){this.provider.on(fs.payload,e=>this.onProviderPayload(e)),this.provider.on(fs.connect,()=>{this.events.emit(ft.connect)}),this.provider.on(fs.disconnect,()=>{this.events.emit(ft.disconnect),this.attemptToReconnect()}),this.provider.on(fs.error,e=>this.events.emit(ft.error,e)),this.events.on(ft.connection_stalled,async()=>{await this.restartTransport()})}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.transportOpen()},fe.toMiliseconds(Th))}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ny=Object.defineProperty,Uh=Object.getOwnPropertySymbols,Ry=Object.prototype.hasOwnProperty,My=Object.prototype.propertyIsEnumerable,Fh=(t,e,r)=>e in t?Ny(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jh=(t,e)=>{for(var r in e||(e={}))Ry.call(e,r)&&Fh(t,r,e[r]);if(Uh)for(var r of Uh(e))My.call(e,r)&&Fh(t,r,e[r]);return t};class ps extends dm{constructor(e,r,n,i=vr,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=ay,this.cached=[],this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{o3(o)?this.map.set(o.id,o):a3(o)?this.map.set(o.topic,o):this.getKey&&o!==null&&!$t(o)&&this.map.set(this.getKey(o),o)}),this.cached=[],this.initialized=!0)},this.set=async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>vw(a[c],o[c]))):this.values),this.update=async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=jh(jh({},this.getData(o)),a);this.map.set(o,c),await this.persist()},this.delete=async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),await this.persist())},this.logger=Be.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Ly{constructor(e,r){this.core=e,this.logger=r,this.name=hy,this.version=dy,this.events=new xt.exports,this.initialized=!1,this.storagePrefix=vr,this.ignoredPayloadTypes=[Mr],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();const n=Fo(),i=await this.core.crypto.setSymKey(n),s=rr(fe.FIVE_MINUTES),o={protocol:$h},a={topic:i,expiry:s,relay:o,active:!1},c=Yg({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:o});return await this.pairings.set(i,a),await this.core.relayer.subscribe(i),this.core.expirer.set(i,s),{topic:i,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:s,relay:o}=Gg(n.uri);if(this.pairings.keys.includes(i))throw new Error(`Pairing already exists: ${i}`);if(this.core.crypto.hasKeys(i))throw new Error(`Keychain already exists: ${i}`);const a=rr(fe.FIVE_MINUTES),c={topic:i,relay:o,expiry:a,active:!1};return await this.pairings.set(i,c),await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),this.core.expirer.set(i,a),n.activatePairing&&await this.activate({topic:i}),c},this.activate=async({topic:n})=>{this.isInitialized();const i=rr(fe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ur();this.events.once(et("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",tt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{const o=us(i,s),a=await this.core.crypto.encode(n,o),c=di[i].req;return this.core.history.set(n,o),await this.core.relayer.publish(n,a,c),o.id},this.sendResult=async(n,i,s)=>{const o=ua(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=di[c.request.method].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{const o=hs(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=di[c.request.method]?di[c.request.method].res:di.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,tt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>yr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:s}=n,o=s.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit("pairing_ping",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{const{id:s}=i;setTimeout(()=>{fr(i)?this.events.emit(et("pairing_ping",s),{}):Qt(i)&&this.events.emit(et("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit("pairing_delete",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=tt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(tt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!Ft(n)){const{message:i}=ie("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!s3(n.uri)){const{message:i}=ie("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!Ft(n)){const{message:s}=ie("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Ft(n)){const{message:s}=ie("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!dt(n,!1)){const{message:i}=ie("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(yr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=ie("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=Be.generateChildLogger(r,this.name),this.pairings=new ps(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Be.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ft.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);ha(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):da(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(Vt.expired,async e=>{const{topic:r}=fu(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class Uy extends cm{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new xt.exports.EventEmitter,this.name=fy,this.version=py,this.cached=[],this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s};this.records.set(o.id,o),this.events.emit(sr.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Qt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(sr.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(sr.deleted,s)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Be.generateChildLogger(r,this.name)}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:us(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(sr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(sr.created,e=>{const r=sr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(sr.updated,e=>{const r=sr.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(sr.deleted,e=>{const r=sr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Fy extends pm{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new xt.exports.EventEmitter,this.name=gy,this.version=my,this.cached=[],this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Vt.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Vt.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Be.generateChildLogger(r,this.name)}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Bg(e);if(typeof e=="number")return kg(e);const{message:r}=ie("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Vt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;fe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Vt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ri.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Vt.created,e=>{const r=Vt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Vt.expired,e=>{const r=Vt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Vt.deleted,e=>{const r=Vt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jy=Object.defineProperty,Bh=Object.getOwnPropertySymbols,By=Object.prototype.hasOwnProperty,ky=Object.prototype.propertyIsEnumerable,kh=(t,e,r)=>e in t?jy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hh=(t,e)=>{for(var r in e||(e={}))By.call(e,r)&&kh(t,r,e[r]);if(Bh)for(var r of Bh(e))ky.call(e,r)&&kh(t,r,e[r]);return t};class ba extends am{constructor(e){super(e),this.protocol=Oh,this.version=V5,this.name=wa,this.events=new xt.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ph;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gn(Be.getDefaultLoggerOptions({level:e?.logger||K5.logger}));this.logger=Be.generateChildLogger(r,this.name),this.heartbeat=new ri.HeartBeat,this.crypto=new yy(this,this.logger,e?.keychain),this.history=new Uy(this,this.logger),this.expirer=new Fy(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new f2(Hh(Hh({},G5),e?.storageOptions)),this.relayer=new Ty({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ly(this,this.logger)}static async init(e){const r=new ba(e);return await r.initialize(),r}get context(){return Be.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const Hy=ba,zh="wc",Wh=2,qh="client",va=`${zh}@${Wh}:${qh}:`,_a={name:qh,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},zy="proposal",Vh="Proposal expired",Wy="session",gs=fe.SEVEN_DAYS,qy="engine",pi={wc_sessionPropose:{req:{ttl:fe.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1104},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1106},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:fe.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:fe.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1112},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1115}}},Ea={min:fe.FIVE_MINUTES,max:fe.SEVEN_DAYS},Vy="request";var Ky=Object.defineProperty,Gy=Object.defineProperties,Zy=Object.getOwnPropertyDescriptors,Kh=Object.getOwnPropertySymbols,Yy=Object.prototype.hasOwnProperty,Jy=Object.prototype.propertyIsEnumerable,Gh=(t,e,r)=>e in t?Ky(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kt=(t,e)=>{for(var r in e||(e={}))Yy.call(e,r)&&Gh(t,r,e[r]);if(Kh)for(var r of Kh(e))Jy.call(e,r)&&Gh(t,r,e[r]);return t},xa=(t,e)=>Gy(t,Zy(e));class Xy extends mm{constructor(e){super(e),this.name=qy,this.events=new xt.exports,this.initialized=!1,this.ignoredPayloadTypes=[Mr],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(pi)}),this.initialized=!0)},this.connect=async r=>{this.isInitialized();const n=xa(Kt({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:c}=n;let l=i,p,m=!1;if(l&&(m=this.client.core.pairing.pairings.get(l).active),!l||!m){const{topic:D,uri:b}=await this.client.core.pairing.create();l=D,p=b}const w=await this.client.core.crypto.generateKeyPair(),y=Kt({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:$h}],proposer:{publicKey:w,metadata:this.client.metadata}},a&&{sessionProperties:a}),{reject:E,resolve:T,done:N}=Ur(fe.FIVE_MINUTES,Vh);if(this.events.once(et("session_connect"),async({error:D,session:b})=>{if(D)E(D);else if(b){b.self.publicKey=w;const I=xa(Kt({},b),{requiredNamespaces:b.requiredNamespaces,optionalNamespaces:b.optionalNamespaces});await this.client.session.set(b.topic,I),await this.setExpiry(b.topic,b.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:b.peer.metadata}),T(I)}}),!l){const{message:D}=ie("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const U=await this.sendRequest(l,"wc_sessionPropose",y),C=rr(fe.FIVE_MINUTES);return await this.setProposal(U,Kt({id:U,expiry:C},y)),{uri:p,approval:N}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{this.isInitialized(),await this.isValidApprove(r);const{id:n,relayProtocol:i,namespaces:s,sessionProperties:o}=r,a=this.client.proposal.get(n);let{pairingTopic:c,proposer:l,requiredNamespaces:p,optionalNamespaces:m}=a;Kn(p)||(p=e3(s,"approve()"));const w=await this.client.core.crypto.generateKeyPair(),y=l.publicKey,E=await this.client.core.crypto.generateSharedKey(w,y);c&&n&&(await this.client.core.pairing.updateMetadata({topic:c,metadata:l.metadata}),await this.sendResult(n,c,{relay:{protocol:i??"irn"},responderPublicKey:w}),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}));const T=Kt({relay:{protocol:i??"irn"},namespaces:s,requiredNamespaces:p,optionalNamespaces:m,controller:{publicKey:w,metadata:this.client.metadata},expiry:rr(gs)},o&&{sessionProperties:o});await this.client.core.relayer.subscribe(E);const N=await this.sendRequest(E,"wc_sessionSettle",T),{done:U,resolve:C,reject:D}=Ur();this.events.once(et("session_approve",N),({error:I})=>{I?D(I):C(this.client.session.get(E))});const b=xa(Kt({},T),{topic:E,acknowledged:!1,self:T.controller,peer:{publicKey:l.publicKey,metadata:l.metadata},controller:w});return await this.client.session.set(E,b),await this.setExpiry(E,rr(gs)),{topic:E,acknowledged:U}},this.reject=async r=>{this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:s}=this.client.proposal.get(n);s&&(await this.sendError(n,s,i),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,s=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:o,resolve:a,reject:c}=Ur();return this.events.once(et("session_update",s),({error:l})=>{l?c(l):a()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:o}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:s,resolve:o,reject:a}=Ur();return this.events.once(et("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,rr(gs)),{acknowledged:s}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:s,expiry:o}=r,a=await this.sendRequest(s,"wc_sessionRequest",{request:i,chainId:n},o),{done:c,resolve:l,reject:p}=Ur(o);return this.events.once(et("session_request",a),({error:m,result:w})=>{m?p(m):l(w)}),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n}),await c()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i;fr(i)?await this.sendResult(s,n,i.result):Qt(i)&&await this.sendError(s,n,i.error),this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:s,resolve:o,reject:a}=Ur();this.events.once(et("session_ping",i),({error:c})=>{c?a(c):o()}),await s()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:s})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest(n,"wc_sessionDelete",tt("USER_DISCONNECTED")),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>n3(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await Promise.all([this.client.session.delete(r,tt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(r),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,tt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=pi.wc_sessionRequest.req.ttl,{id:i,topic:s,params:o}=r;await this.client.pendingRequest.set(i,{id:i,topic:s,params:o}),n&&this.client.core.expirer.set(i,rr(n))},this.sendRequest=async(r,n,i,s)=>{const o=us(n,i),a=await this.client.core.crypto.encode(r,o),c=pi[n].req;return s&&(c.ttl=s),this.client.core.history.set(r,o),this.client.core.relayer.publish(r,a,c),o.id},this.sendResult=async(r,n,i)=>{const s=ua(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=pi[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.sendError=async(r,n,i)=>{const s=hs(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=pi[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{yr(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{yr(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=r=>{const{topic:n,payload:i}=r,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidConnect(Kt({},n.params));const o=rr(fe.FIVE_MINUTES),a=Kt({id:s,pairingTopic:r,expiry:o},i);await this.setProposal(s,a),this.client.events.emit("session_proposal",{id:s,params:a})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(fr(n)){const{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});const a=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const c=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const l=await this.client.core.crypto.generateSharedKey(a,c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const p=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:r})}else Qt(n)&&(await this.client.proposal.delete(i,tt("USER_DISCONNECTED")),this.events.emit(et("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,requiredNamespaces:p,optionalNamespaces:m,sessionProperties:w}=n.params,y=Kt({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,requiredNamespaces:p,optionalNamespaces:m,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},w&&{sessionProperties:w});await this.sendResult(n.id,r,!0),this.events.emit(et("session_connect"),{session:y})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;fr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(et("session_approve",i),{})):Qt(n)&&(await this.client.session.delete(r,tt("USER_DISCONNECTED")),this.events.emit(et("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidUpdate(Kt({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(s,r,!0),this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;fr(n)?this.events.emit(et("session_update",i),{}):Qt(n)&&this.events.emit(et("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,rr(gs)),await this.sendResult(i,r,!0),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;fr(n)?this.events.emit(et("session_extend",i),{}):Qt(n)&&this.events.emit(et("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{fr(n)?this.events.emit(et("session_ping",i),{}):Qt(n)&&this.events.emit(et("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),this.client.core.relayer.once(ft.publish,async()=>{await this.deleteSession(r)}),await this.sendResult(i,r,!0),this.client.events.emit("session_delete",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidRequest(Kt({topic:r},s)),await this.setPendingSessionRequest({id:i,topic:r,params:s}),this.client.events.emit("session_request",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;fr(n)?this.events.emit(et("session_request",i),{result:n.result}):Qt(n)&&this.events.emit(et("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidEmit(Kt({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.isValidConnect=async r=>{if(!Ft(r)){const{message:c}=ie("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(c)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if($t(n)||await this.isValidPairingTopic(n),!g3(a,!0)){const{message:c}=ie("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!$t(i)&&Kn(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!$t(s)&&Kn(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),$t(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=p3(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!Ft(r))throw new Error(ie("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;await this.isValidProposalId(n);const a=this.client.proposal.get(n),c=is(i,"approve()");if(c)throw new Error(c.message);const l=vu(a.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!dt(s,!0)){const{message:p}=ie("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(p)}$t(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!Ft(r)){const{message:s}=ie("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!w3(i)){const{message:s}=ie("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!Ft(r)){const{message:l}=ie("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!yu(n)){const{message:l}=ie("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=c3(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=is(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(yr(o)){const{message:l}=ie("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!Ft(r)){const{message:c}=ie("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=is(i,"update()");if(o)throw new Error(o.message);const a=vu(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!Ft(r)){const{message:i}=ie("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!Ft(r)){const{message:c}=ie("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!bu(a,s)){const{message:c}=ie("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!y3(i)){const{message:c}=ie("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!_3(a,s,i.method)){const{message:c}=ie("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!S3(o,Ea)){const{message:c}=ie("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ea.min} and ${Ea.max}`);throw new Error(c)}},this.isValidRespond=async r=>{if(!Ft(r)){const{message:s}=ie("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(s)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!b3(i)){const{message:s}=ie("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidPing=async r=>{if(!Ft(r)){const{message:i}=ie("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!Ft(r)){const{message:a}=ie("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!bu(o,s)){const{message:a}=ie("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!v3(i)){const{message:a}=ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!E3(o,s,i.name)){const{message:a}=ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!Ft(r)){const{message:i}=ie("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!dt(i,!1)){const{message:s}=ie("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})}}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(ft.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);ha(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):da(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(Vt.expired,async e=>{const{topic:r,id:n}=fu(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,ie("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}isValidPairingTopic(e){if(!dt(e,!1)){const{message:r}=ie("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(yr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=ie("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!dt(e,!1)){const{message:r}=ie("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=ie("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(yr(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=ie("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(dt(e,!1)){const{message:r}=ie("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=ie("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!m3(e)){const{message:r}=ie("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=ie("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(yr(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=ie("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class Qy extends ps{constructor(e,r){super(e,r,zy,va),this.core=e,this.logger=r}}class eb extends ps{constructor(e,r){super(e,r,Wy,va),this.core=e,this.logger=r}}class tb extends ps{constructor(e,r){super(e,r,Vy,va),this.core=e,this.logger=r}}class Ca extends gm{constructor(e){super(e),this.protocol=zh,this.version=Wh,this.name=_a.name,this.events=new xt.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||_a.name,this.metadata=e?.metadata||Mg();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gn(Be.getDefaultLoggerOptions({level:e?.logger||_a.logger}));this.core=e?.core||new Hy(e),this.logger=Be.generateChildLogger(r,this.name),this.session=new eb(this.core,this.logger),this.proposal=new Qy(this.core,this.logger),this.pendingRequest=new tb(this.core,this.logger),this.engine=new Xy(this)}static async init(e){const r=new Ca(e);return await r.initialize(),r}get context(){return Be.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Sa={exports:{}};(function(t,e){var r=typeof self<"u"?self:ht,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function c(x){return x&&DataView.prototype.isPrototypeOf(x)}if(a.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],p=ArrayBuffer.isView||function(x){return x&&l.indexOf(Object.prototype.toString.call(x))>-1};function m(x){if(typeof x!="string"&&(x=String(x)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(x))throw new TypeError("Invalid character in header field name");return x.toLowerCase()}function w(x){return typeof x!="string"&&(x=String(x)),x}function y(x){var A={next:function(){var G=x.shift();return{done:G===void 0,value:G}}};return a.iterable&&(A[Symbol.iterator]=function(){return A}),A}function E(x){this.map={},x instanceof E?x.forEach(function(A,G){this.append(G,A)},this):Array.isArray(x)?x.forEach(function(A){this.append(A[0],A[1])},this):x&&Object.getOwnPropertyNames(x).forEach(function(A){this.append(A,x[A])},this)}E.prototype.append=function(x,A){x=m(x),A=w(A);var G=this.map[x];this.map[x]=G?G+", "+A:A},E.prototype.delete=function(x){delete this.map[m(x)]},E.prototype.get=function(x){return x=m(x),this.has(x)?this.map[x]:null},E.prototype.has=function(x){return this.map.hasOwnProperty(m(x))},E.prototype.set=function(x,A){this.map[m(x)]=w(A)},E.prototype.forEach=function(x,A){for(var G in this.map)this.map.hasOwnProperty(G)&&x.call(A,this.map[G],G,this)},E.prototype.keys=function(){var x=[];return this.forEach(function(A,G){x.push(G)}),y(x)},E.prototype.values=function(){var x=[];return this.forEach(function(A){x.push(A)}),y(x)},E.prototype.entries=function(){var x=[];return this.forEach(function(A,G){x.push([G,A])}),y(x)},a.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function T(x){if(x.bodyUsed)return Promise.reject(new TypeError("Already read"));x.bodyUsed=!0}function N(x){return new Promise(function(A,G){x.onload=function(){A(x.result)},x.onerror=function(){G(x.error)}})}function U(x){var A=new FileReader,G=N(A);return A.readAsArrayBuffer(x),G}function C(x){var A=new FileReader,G=N(A);return A.readAsText(x),G}function D(x){for(var A=new Uint8Array(x),G=new Array(A.length),K=0;K<A.length;K++)G[K]=String.fromCharCode(A[K]);return G.join("")}function b(x){if(x.slice)return x.slice(0);var A=new Uint8Array(x.byteLength);return A.set(new Uint8Array(x)),A.buffer}function I(){return this.bodyUsed=!1,this._initBody=function(x){this._bodyInit=x,x?typeof x=="string"?this._bodyText=x:a.blob&&Blob.prototype.isPrototypeOf(x)?this._bodyBlob=x:a.formData&&FormData.prototype.isPrototypeOf(x)?this._bodyFormData=x:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(x)?this._bodyText=x.toString():a.arrayBuffer&&a.blob&&c(x)?(this._bodyArrayBuffer=b(x.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(x)||p(x))?this._bodyArrayBuffer=b(x):this._bodyText=x=Object.prototype.toString.call(x):this._bodyText="",this.headers.get("content-type")||(typeof x=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(x)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var x=T(this);if(x)return x;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?T(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(U)}),this.text=function(){var x=T(this);if(x)return x;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(H)}),this.json=function(){return this.text().then(JSON.parse)},this}var O=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function h(x){var A=x.toUpperCase();return O.indexOf(A)>-1?A:x}function _(x,A){A=A||{};var G=A.body;if(x instanceof _){if(x.bodyUsed)throw new TypeError("Already read");this.url=x.url,this.credentials=x.credentials,A.headers||(this.headers=new E(x.headers)),this.method=x.method,this.mode=x.mode,this.signal=x.signal,!G&&x._bodyInit!=null&&(G=x._bodyInit,x.bodyUsed=!0)}else this.url=String(x);if(this.credentials=A.credentials||this.credentials||"same-origin",(A.headers||!this.headers)&&(this.headers=new E(A.headers)),this.method=h(A.method||this.method||"GET"),this.mode=A.mode||this.mode||null,this.signal=A.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&G)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(G)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function H(x){var A=new FormData;return x.trim().split("&").forEach(function(G){if(G){var K=G.split("="),W=K.shift().replace(/\+/g," "),z=K.join("=").replace(/\+/g," ");A.append(decodeURIComponent(W),decodeURIComponent(z))}}),A}function B(x){var A=new E,G=x.replace(/\r?\n[\t ]+/g," ");return G.split(/\r?\n/).forEach(function(K){var W=K.split(":"),z=W.shift().trim();if(z){var J=W.join(":").trim();A.append(z,J)}}),A}I.call(_.prototype);function q(x,A){A||(A={}),this.type="default",this.status=A.status===void 0?200:A.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in A?A.statusText:"OK",this.headers=new E(A.headers),this.url=A.url||"",this._initBody(x)}I.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},q.error=function(){var x=new q(null,{status:0,statusText:""});return x.type="error",x};var X=[301,302,303,307,308];q.redirect=function(x,A){if(X.indexOf(A)===-1)throw new RangeError("Invalid status code");return new q(null,{status:A,headers:{location:x}})},o.DOMException=s.DOMException;try{new o.DOMException}catch{o.DOMException=function(A,G){this.message=A,this.name=G;var K=Error(A);this.stack=K.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function te(x,A){return new Promise(function(G,K){var W=new _(x,A);if(W.signal&&W.signal.aborted)return K(new o.DOMException("Aborted","AbortError"));var z=new XMLHttpRequest;function J(){z.abort()}z.onload=function(){var Z={status:z.status,statusText:z.statusText,headers:B(z.getAllResponseHeaders()||"")};Z.url="responseURL"in z?z.responseURL:Z.headers.get("X-Request-URL");var ce="response"in z?z.response:z.responseText;G(new q(ce,Z))},z.onerror=function(){K(new TypeError("Network request failed"))},z.ontimeout=function(){K(new TypeError("Network request failed"))},z.onabort=function(){K(new o.DOMException("Aborted","AbortError"))},z.open(W.method,W.url,!0),W.credentials==="include"?z.withCredentials=!0:W.credentials==="omit"&&(z.withCredentials=!1),"responseType"in z&&a.blob&&(z.responseType="blob"),W.headers.forEach(function(Z,ce){z.setRequestHeader(ce,Z)}),W.signal&&(W.signal.addEventListener("abort",J),z.onreadystatechange=function(){z.readyState===4&&W.signal.removeEventListener("abort",J)}),z.send(typeof W._bodyInit>"u"?null:W._bodyInit)})}return te.polyfill=!0,s.fetch||(s.fetch=te,s.Headers=E,s.Request=_,s.Response=q),o.Headers=E,o.Request=_,o.Response=q,o.fetch=te,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(Sa,Sa.exports);var Zh=Gd(Sa.exports);const Yh={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},Jh=10;class ms{constructor(e){if(this.url=e,this.events=new xt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!oh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=ai(e),s=await(await Zh(this.url,Object.assign(Object.assign({},Yh),{body:n}))).json();this.onPayload({data:s})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!oh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{const r=ai({id:1,jsonrpc:"2.0",method:"test",params:[]});await Zh(e,Object.assign(Object.assign({},Yh),{body:r})),this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ia(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=hs(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return eh(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Jh&&this.events.setMaxListeners(Jh)}}const Xh="error",rb="wss://relay.walletconnect.com",nb="wc",ib="universal_provider",Qh=`${nb}@${2}:${ib}:`,sb="https://rpc.walletconnect.com/v1",gi={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function mn(t,e,r){let n;const i=Ia(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${sb}?chainId=eip155:${i}&projectId=${r}`),n}function Ia(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function ob(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function ab(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}const ws=(t,e)=>{const r=n=>{n.request!==e.request||n.topic!==e.topic||(t.events.removeListener("session_request_sent",r),cb())};t.on("session_request_sent",r)};function cb(){if(typeof window<"u")try{const t=window.localStorage.getItem("WALLETCONNECT_DEEPLINK_CHOICE");if(t){const e=JSON.parse(t);window.open(e.href,"_self","noreferrer noopener")}}catch(t){console.error(t)}}class lb{constructor(e){this.name="eip155",this.namespace=e.namespace,this.client=e.client,this.events=e.events,this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),await this.client.request(e)):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){const n=Ia(e);if(!this.httpProviders[n]){const i=r||mn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||mn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new ui(new ms(n))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=Ia(r);e[n]=this.createHttpProvider(n)}),e}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;ob(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class ub{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||mn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||mn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new ui(new ms(n))}}class hb{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||mn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||mn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new ui(new ms(n))}}class db{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new ui(new ms(n))}}var fb=Object.defineProperty,pb=Object.defineProperties,gb=Object.getOwnPropertyDescriptors,e0=Object.getOwnPropertySymbols,mb=Object.prototype.hasOwnProperty,wb=Object.prototype.propertyIsEnumerable,t0=(t,e,r)=>e in t?fb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ys=(t,e)=>{for(var r in e||(e={}))mb.call(e,r)&&t0(t,r,e[r]);if(e0)for(var r of e0(e))wb.call(e,r)&&t0(t,r,e[r]);return t},Da=(t,e)=>pb(t,gb(e));class Oa{constructor(e){this.events=new xt.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gn(Be.getDefaultLoggerOptions({level:e?.logger||Xh}))}static async init(e){const r=new Oa(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ys({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:tt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(s=>{this.session=s}).catch(s=>{if(s.message!==Vh)throw s;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(br(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await Ca.init({logger:this.providerOpts.logger||Xh,relayUrl:this.providerOpts.relayUrl||rb,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");Object.keys(this.namespaces).forEach(e=>{var r,n,i;const s=((r=this.session)==null?void 0:r.namespaces[e].accounts)||[],o=ab(s),a=Da(ys({},Object.assign(this.namespaces[e],(i=(n=this.optionalNamespaces)==null?void 0:n[e])!=null?i:{})),{accounts:s,chains:o});switch(e){case"eip155":this.rpcProviders[e]=new lb({client:this.client,namespace:a,events:this.events});break;case"solana":this.rpcProviders[e]=new ub({client:this.client,namespace:a,events:this.events});break;case"cosmos":this.rpcProviders[e]=new hb({client:this.client,namespace:a,events:this.events});break;case"polkadot":break;case"cip34":this.rpcProviders[e]=new db({client:this.client,namespace:a,events:this.events});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,s=(n=this.client)==null?void 0:n.session.get(e);this.session=Da(ys({},s),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Da(ys({},tt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(gi.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Object.keys(this.namespaces)[0],s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){const[n,i]=this.validateChain(e);r||this.getProvider(n).setDefaultChain(i),this.namespaces[n].defaultChain=i,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${Qh}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${Qh}/${e}`)}}const yb=Oa,bb="wc",vb="ethereum_provider",_b=`${bb}@${2}:${vb}:`,Eb="https://rpc.walletconnect.com/v1/",bs=["eth_sendTransaction","personal_sign"],xb=["eth_accounts","eth_requestAccounts","eth_call","eth_getBalance","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],vs=["chainChanged","accountsChanged"],Cb=["message","disconnect","connect"];var Sb=Object.defineProperty,Ib=Object.defineProperties,Db=Object.getOwnPropertyDescriptors,r0=Object.getOwnPropertySymbols,Ob=Object.prototype.hasOwnProperty,Ab=Object.prototype.propertyIsEnumerable,n0=(t,e,r)=>e in t?Sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,i0=(t,e)=>{for(var r in e||(e={}))Ob.call(e,r)&&n0(t,r,e[r]);if(r0)for(var r of r0(e))Ab.call(e,r)&&n0(t,r,e[r]);return t},s0=(t,e)=>Ib(t,Db(e));function Aa(t){return Number(t[0].split(":")[1])}function $a(t){return`0x${t.toString(16)}`}function $b(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!br(e))throw new Error("Invalid chains");const c=e,l=n||bs,p=s||vs,m={[Aa(c)]:a[Aa(c)]},w={chains:c,methods:l,events:p,rpcMap:m},y=s?.filter(U=>!vs.includes(U)),E=n?.filter(U=>!bs.includes(U));if(!r&&!o&&!i&&!(y!=null&&y.length)&&!(E!=null&&E.length))return{required:w};const T=y?.length&&E?.length||!r,N={chains:[...new Set(T?c.concat(r||[]):r)],methods:[...new Set(l.concat(i||[]))],events:[...new Set(p.concat(o||[]))],rpcMap:a};return{required:w,optional:N}}class _s{constructor(){this.events=new xt.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=_b,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new _s;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=$b(this.rpc);try{const i=await new Promise(async(o,a)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(s0(i0({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(l=>{o(l)}).catch(l=>{a(new Error(l.message))})});if(!i)return;this.setChainIds(this.rpc.chains);const s=mg(i.namespaces,[this.namespace]);this.setAccounts(s),this.events.emit("connect",{chainId:$a(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",$a(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",s0(i0({},tt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",$a(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||bs,events:e?.events||vs,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:(n=e?.showQrModal)!=null?n:!0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=Aa(this.rpc.chains),this.signer=await yb.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){const{Web3Modal:r}=await Promise.resolve().then(function(){return Qb});this.modal=new r({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains})}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&br(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&br(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${Eb}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const Pb=_s,Tb=Symbol(),o0=Object.getPrototypeOf,Pa=new WeakMap,Nb=t=>t&&(Pa.has(t)?Pa.get(t):o0(t)===Object.prototype||o0(t)===Array.prototype),Rb=t=>Nb(t)&&t[Tb]||null,a0=(t,e=!0)=>{Pa.set(t,e)},Ta=t=>typeof t=="object"&&t!==null,kr=new WeakMap,Es=new WeakSet,Mb=(t=Object.is,e=(l,p)=>new Proxy(l,p),r=l=>Ta(l)&&!Es.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),n=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,s=(l,p,m=n)=>{const w=i.get(l);if(w?.[0]===p)return w[1];const y=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return a0(y,!0),i.set(l,[p,y]),Reflect.ownKeys(l).forEach(E=>{const T=Reflect.get(l,E);Es.has(T)?(a0(T,!1),y[E]=T):T instanceof Promise?Object.defineProperty(y,E,{get(){return m(T)}}):kr.has(T)?y[E]=Ub(T,m):y[E]=T}),Object.freeze(y)},o=new WeakMap,a=[1,1],c=l=>{if(!Ta(l))throw new Error("object required");const p=o.get(l);if(p)return p;let m=a[0];const w=new Set,y=(H,B=++a[0])=>{m!==B&&(m=B,w.forEach(q=>q(H,B)))};let E=a[1];const T=(H=++a[1])=>(E!==H&&!w.size&&(E=H,U.forEach(([B])=>{const q=B[1](H);q>m&&(m=q)})),m),N=H=>(B,q)=>{const X=[...B];X[1]=[H,...X[1]],y(X,q)},U=new Map,C=(H,B)=>{if(void 0!=="production"&&U.has(H))throw new Error("prop listener already exists");if(w.size){const q=B[3](N(H));U.set(H,[B,q])}else U.set(H,[B])},D=H=>{var B;const q=U.get(H);q&&(U.delete(H),(B=q[1])==null||B.call(q))},b=H=>(w.add(H),w.size===1&&U.forEach(([q,X],te)=>{if(void 0!=="production"&&X)throw new Error("remove already exists");const x=q[3](N(te));U.set(te,[q,x])}),()=>{w.delete(H),w.size===0&&U.forEach(([q,X],te)=>{X&&(X(),U.set(te,[q]))})}),I=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),h=e(I,{deleteProperty(H,B){const q=Reflect.get(H,B);D(B);const X=Reflect.deleteProperty(H,B);return X&&y(["delete",[B],q]),X},set(H,B,q,X){var te;const x=Reflect.has(H,B),A=Reflect.get(H,B,X);if(x&&t(A,q))return!0;D(B),Ta(q)&&(q=Rb(q)||q);let G=q;if(!((te=Object.getOwnPropertyDescriptor(H,B))!=null&&te.set))if(q instanceof Promise)q.then(K=>{q.status="fulfilled",q.value=K,y(["resolve",[B],K])}).catch(K=>{q.status="rejected",q.reason=K,y(["reject",[B],K])});else{!kr.has(q)&&r(q)&&(G=or(q));const K=!Es.has(G)&&kr.get(G);K&&C(B,K)}return Reflect.set(H,B,G,X),y(["set",[B],q,A]),!0}});o.set(l,h);const _=[I,T,s,b];return kr.set(h,_),Reflect.ownKeys(l).forEach(H=>{const B=Object.getOwnPropertyDescriptor(l,H);B.get||B.set?Object.defineProperty(I,H,B):h[H]=l[H]}),h})=>[c,kr,Es,t,e,r,n,i,s,o,a],[Lb]=Mb();function or(t={}){return Lb(t)}function Hr(t,e,r){const n=kr.get(t);void 0!=="production"&&!n&&console.warn("Please use proxy object");let i;const s=[],o=n[3];let a=!1;const l=o(p=>{if(s.push(p),r){e(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Ub(t,e){const r=kr.get(t);void 0!=="production"&&!r&&console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}var c0={},xs={};xs.byteLength=Bb,xs.toByteArray=Hb,xs.fromByteArray=qb;for(var ar=[],Gt=[],Fb=typeof Uint8Array<"u"?Uint8Array:Array,Na="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wn=0,jb=Na.length;wn<jb;++wn)ar[wn]=Na[wn],Gt[Na.charCodeAt(wn)]=wn;Gt["-".charCodeAt(0)]=62,Gt["_".charCodeAt(0)]=63;function l0(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Bb(t){var e=l0(t),r=e[0],n=e[1];return(r+n)*3/4-n}function kb(t,e,r){return(e+r)*3/4-r}function Hb(t){var e,r=l0(t),n=r[0],i=r[1],s=new Fb(kb(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=Gt[t.charCodeAt(c)]<<18|Gt[t.charCodeAt(c+1)]<<12|Gt[t.charCodeAt(c+2)]<<6|Gt[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Gt[t.charCodeAt(c)]<<2|Gt[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Gt[t.charCodeAt(c)]<<10|Gt[t.charCodeAt(c+1)]<<4|Gt[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function zb(t){return ar[t>>18&63]+ar[t>>12&63]+ar[t>>6&63]+ar[t&63]}function Wb(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(zb(n));return i.join("")}function qb(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(Wb(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(ar[e>>2]+ar[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(ar[e>>10]+ar[e>>4&63]+ar[e<<2&63]+"=")),i.join("")}var Ra={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Ra.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,l=c>>1,p=-7,m=r?i-1:0,w=r?-1:1,y=t[e+m];for(m+=w,s=y&(1<<-p)-1,y>>=-p,p+=a;p>0;s=s*256+t[e+m],m+=w,p-=8);for(o=s&(1<<-p)-1,s>>=-p,p+=n;p>0;o=o*256+t[e+m],m+=w,p-=8);if(s===0)s=1-l;else{if(s===c)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-l}return(y?-1:1)*o*Math.pow(2,s-n)},Ra.write=function(t,e,r,n,i,s){var o,a,c,l=s*8-i-1,p=(1<<l)-1,m=p>>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:s-1,E=n?1:-1,T=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+m>=1?e+=w/c:e+=w*Math.pow(2,1-m),e*c>=2&&(o++,c/=2),o+m>=p?(a=0,o=p):o+m>=1?(a=(e*c-1)*Math.pow(2,i),o=o+m):(a=e*Math.pow(2,m-1)*Math.pow(2,i),o=0));i>=8;t[r+y]=a&255,y+=E,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;t[r+y]=o&255,y+=E,o/=256,l-=8);t[r+y-E]|=T*128};/*!
|
|
72
|
+
***************************************************************************** */var aa=function(t,e){return aa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},aa(t,e)};function Fm(t,e){aa(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ca=function(){return ca=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},ca.apply(this,arguments)};function jm(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Bm(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function km(t,e){return function(r,n){e(r,n,t)}}function Hm(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function zm(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(m){o(m)}}function c(p){try{l(n.throw(p))}catch(m){o(m)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function Wm(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(p){return c([l,p])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(p){l=[6,p],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function qm(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Vm(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function la(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function rh(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function Km(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(rh(arguments[e]));return t}function Gm(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function li(t){return this instanceof li?(this.v=t,this):new li(t)}function Zm(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(w){n[w]&&(i[w]=function(y){return new Promise(function(E,T){s.push([w,y,E,T])>1||a(w,y)})})}function a(w,y){try{c(n[w](y))}catch(E){m(s[0][3],E)}}function c(w){w.value instanceof li?Promise.resolve(w.value.v).then(l,p):m(s[0][2],w)}function l(w){a("next",w)}function p(w){a("throw",w)}function m(w,y){w(y),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Ym(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:li(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function Jm(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof la=="function"?la(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Xm(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Qm(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function ew(t){return t&&t.__esModule?t:{default:t}}function tw(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function rw(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var nw=Object.freeze({__proto__:null,__extends:Fm,get __assign(){return ca},__rest:jm,__decorate:Bm,__param:km,__metadata:Hm,__awaiter:zm,__generator:Wm,__createBinding:qm,__exportStar:Vm,__values:la,__read:rh,__spread:Km,__spreadArrays:Gm,__await:li,__asyncGenerator:Zm,__asyncDelegator:Ym,__asyncValues:Jm,__makeTemplateObject:Xm,__importStar:Qm,__importDefault:ew,__classPrivateFieldGet:tw,__classPrivateFieldSet:rw}),iw=Pr(nw),hr={},nh;function sw(){if(nh)return hr;nh=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.isBrowserCryptoAvailable=hr.getSubtleCrypto=hr.getBrowerCrypto=void 0;function t(){return ht?.crypto||ht?.msCrypto||{}}hr.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}hr.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return hr.isBrowserCryptoAvailable=r,hr}var dr={},ih;function ow(){if(ih)return dr;ih=1,Object.defineProperty(dr,"__esModule",{value:!0}),dr.isBrowser=dr.isNode=dr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}dr.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}dr.isNode=e;function r(){return!t()&&!e()}return dr.isBrowser=r,dr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=iw;e.__exportStar(sw(),t),e.__exportStar(ow(),t)})(th);function aw(){const t=Date.now()*Math.pow(10,3),e=Math.floor(Math.random()*Math.pow(10,3));return t+e}function us(t,e,r){return{id:r||aw(),jsonrpc:"2.0",method:t,params:e}}function ua(t,e){return{id:t,jsonrpc:"2.0",result:e}}function hs(t,e,r){return{id:t,jsonrpc:"2.0",error:cw(e,r)}}function cw(t,e){return typeof t>"u"?Qu(Ju):(typeof t=="string"&&(t=Object.assign(Object.assign({},Qu(oa)),{message:t})),typeof e<"u"&&(t.data=e),Lm(t.code)&&(t=Um(t.code)),t)}class lw{}class uw extends lw{constructor(){super()}}class hw extends uw{constructor(e){super()}}const dw="^https?:",fw="^wss?:";function pw(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function sh(t,e){const r=pw(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function oh(t){return sh(t,dw)}function ah(t){return sh(t,fw)}function gw(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function ch(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function ha(t){return ch(t)&&"method"in t}function da(t){return ch(t)&&(fr(t)||Qt(t))}function fr(t){return"result"in t}function Qt(t){return"error"in t}class ui extends hw{constructor(e){super(e),this.events=new xt.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(us(e.method,e.params||[]),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Qt(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),da(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.hasRegisteredEventListeners=!0)}}const lh=10,mw=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),ww=()=>typeof window<"u",yw=mw();class bw{constructor(e){if(this.url=e,this.events=new xt.exports.EventEmitter,this.registering=!1,!ah(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ai(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!ah(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=th.isReactNative()?void 0:{rejectUnauthorized:!gw(e)},s=new yw(e,[],i);ww()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ia(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=hs(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return eh(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>lh&&this.events.setMaxListeners(lh)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",r),r}}var fa={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,s=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",p="[object Boolean]",m="[object Date]",w="[object Error]",y="[object Function]",E="[object GeneratorFunction]",T="[object Map]",N="[object Number]",U="[object Null]",C="[object Object]",D="[object Promise]",b="[object Proxy]",I="[object RegExp]",O="[object Set]",h="[object String]",_="[object Symbol]",H="[object Undefined]",B="[object WeakMap]",q="[object ArrayBuffer]",X="[object DataView]",te="[object Float32Array]",x="[object Float64Array]",A="[object Int8Array]",G="[object Int16Array]",K="[object Int32Array]",W="[object Uint8Array]",z="[object Uint8ClampedArray]",J="[object Uint16Array]",Z="[object Uint32Array]",ce=/[\\^$.*+?()[\]{}|]/g,Q=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,oe={};oe[te]=oe[x]=oe[A]=oe[G]=oe[K]=oe[W]=oe[z]=oe[J]=oe[Z]=!0,oe[a]=oe[c]=oe[q]=oe[p]=oe[X]=oe[m]=oe[w]=oe[y]=oe[T]=oe[N]=oe[C]=oe[I]=oe[O]=oe[h]=oe[B]=!1;var Ce=typeof ht=="object"&&ht&&ht.Object===Object&&ht,j=typeof self=="object"&&self&&self.Object===Object&&self,F=Ce||j||Function("return this")(),R=e&&!e.nodeType&&e,f=R&&!0&&t&&!t.nodeType&&t,$=f&&f.exports===R,ee=$&&Ce.process,ne=function(){try{return ee&&ee.binding&&ee.binding("util")}catch{}}(),Ee=ne&&ne.isTypedArray;function Le(S,M){for(var Y=-1,ae=S==null?0:S.length,We=0,Ie=[];++Y<ae;){var Qe=S[Y];M(Qe,Y,S)&&(Ie[We++]=Qe)}return Ie}function Pe(S,M){for(var Y=-1,ae=M.length,We=S.length;++Y<ae;)S[We+Y]=M[Y];return S}function Ue(S,M){for(var Y=-1,ae=S==null?0:S.length;++Y<ae;)if(M(S[Y],Y,S))return!0;return!1}function Ge(S,M){for(var Y=-1,ae=Array(S);++Y<S;)ae[Y]=M(Y);return ae}function qe(S){return function(M){return S(M)}}function Te(S,M){return S.has(M)}function De(S,M){return S?.[M]}function me(S){var M=-1,Y=Array(S.size);return S.forEach(function(ae,We){Y[++M]=[We,ae]}),Y}function Se(S,M){return function(Y){return S(M(Y))}}function Oe(S){var M=-1,Y=Array(S.size);return S.forEach(function(ae){Y[++M]=ae}),Y}var ge=Array.prototype,xe=Function.prototype,g=Object.prototype,u=F["__core-js_shared__"],d=xe.toString,v=g.hasOwnProperty,P=function(){var S=/[^.]+$/.exec(u&&u.keys&&u.keys.IE_PROTO||"");return S?"Symbol(src)_1."+S:""}(),L=g.toString,k=RegExp("^"+d.call(v).replace(ce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),se=$?F.Buffer:void 0,ue=F.Symbol,Re=F.Uint8Array,Fe=g.propertyIsEnumerable,Me=ge.splice,Wt=ue?ue.toStringTag:void 0,nn=Object.getOwnPropertySymbols,Hi=se?se.isBuffer:void 0,io=Se(Object.keys,Object),rt=Fn(F,"DataView"),Je=Fn(F,"Map"),nt=Fn(F,"Promise"),it=Fn(F,"Set"),st=Fn(F,"WeakMap"),Xe=Fn(Object,"create"),gt=on(rt),mt=on(Je),wt=on(nt),yt=on(it),bt=on(st),ut=ue?ue.prototype:void 0,ot=ut?ut.valueOf:void 0;function Ve(S){var M=-1,Y=S==null?0:S.length;for(this.clear();++M<Y;){var ae=S[M];this.set(ae[0],ae[1])}}function vt(){this.__data__=Xe?Xe(null):{},this.size=0}function _t(S){var M=this.has(S)&&delete this.__data__[S];return this.size-=M?1:0,M}function d7(S){var M=this.__data__;if(Xe){var Y=M[S];return Y===n?void 0:Y}return v.call(M,S)?M[S]:void 0}function f7(S){var M=this.__data__;return Xe?M[S]!==void 0:v.call(M,S)}function p7(S,M){var Y=this.__data__;return this.size+=this.has(S)?0:1,Y[S]=Xe&&M===void 0?n:M,this}Ve.prototype.clear=vt,Ve.prototype.delete=_t,Ve.prototype.get=d7,Ve.prototype.has=f7,Ve.prototype.set=p7;function gr(S){var M=-1,Y=S==null?0:S.length;for(this.clear();++M<Y;){var ae=S[M];this.set(ae[0],ae[1])}}function g7(){this.__data__=[],this.size=0}function m7(S){var M=this.__data__,Y=oo(M,S);if(Y<0)return!1;var ae=M.length-1;return Y==ae?M.pop():Me.call(M,Y,1),--this.size,!0}function w7(S){var M=this.__data__,Y=oo(M,S);return Y<0?void 0:M[Y][1]}function y7(S){return oo(this.__data__,S)>-1}function b7(S,M){var Y=this.__data__,ae=oo(Y,S);return ae<0?(++this.size,Y.push([S,M])):Y[ae][1]=M,this}gr.prototype.clear=g7,gr.prototype.delete=m7,gr.prototype.get=w7,gr.prototype.has=y7,gr.prototype.set=b7;function sn(S){var M=-1,Y=S==null?0:S.length;for(this.clear();++M<Y;){var ae=S[M];this.set(ae[0],ae[1])}}function v7(){this.size=0,this.__data__={hash:new Ve,map:new(Je||gr),string:new Ve}}function _7(S){var M=ao(this,S).delete(S);return this.size-=M?1:0,M}function E7(S){return ao(this,S).get(S)}function x7(S){return ao(this,S).has(S)}function C7(S,M){var Y=ao(this,S),ae=Y.size;return Y.set(S,M),this.size+=Y.size==ae?0:1,this}sn.prototype.clear=v7,sn.prototype.delete=_7,sn.prototype.get=E7,sn.prototype.has=x7,sn.prototype.set=C7;function so(S){var M=-1,Y=S==null?0:S.length;for(this.__data__=new sn;++M<Y;)this.add(S[M])}function S7(S){return this.__data__.set(S,n),this}function I7(S){return this.__data__.has(S)}so.prototype.add=so.prototype.push=S7,so.prototype.has=I7;function Or(S){var M=this.__data__=new gr(S);this.size=M.size}function D7(){this.__data__=new gr,this.size=0}function O7(S){var M=this.__data__,Y=M.delete(S);return this.size=M.size,Y}function A7(S){return this.__data__.get(S)}function $7(S){return this.__data__.has(S)}function P7(S,M){var Y=this.__data__;if(Y instanceof gr){var ae=Y.__data__;if(!Je||ae.length<r-1)return ae.push([S,M]),this.size=++Y.size,this;Y=this.__data__=new sn(ae)}return Y.set(S,M),this.size=Y.size,this}Or.prototype.clear=D7,Or.prototype.delete=O7,Or.prototype.get=A7,Or.prototype.has=$7,Or.prototype.set=P7;function T7(S,M){var Y=co(S),ae=!Y&&K7(S),We=!Y&&!ae&&zc(S),Ie=!Y&&!ae&&!We&&Vd(S),Qe=Y||ae||We||Ie,Et=Qe?Ge(S.length,String):[],It=Et.length;for(var Ze in S)(M||v.call(S,Ze))&&!(Qe&&(Ze=="length"||We&&(Ze=="offset"||Ze=="parent")||Ie&&(Ze=="buffer"||Ze=="byteLength"||Ze=="byteOffset")||H7(Ze,It)))&&Et.push(Ze);return Et}function oo(S,M){for(var Y=S.length;Y--;)if(Hd(S[Y][0],M))return Y;return-1}function N7(S,M,Y){var ae=M(S);return co(S)?ae:Pe(ae,Y(S))}function zi(S){return S==null?S===void 0?H:U:Wt&&Wt in Object(S)?B7(S):V7(S)}function Fd(S){return Wi(S)&&zi(S)==a}function jd(S,M,Y,ae,We){return S===M?!0:S==null||M==null||!Wi(S)&&!Wi(M)?S!==S&&M!==M:R7(S,M,Y,ae,jd,We)}function R7(S,M,Y,ae,We,Ie){var Qe=co(S),Et=co(M),It=Qe?c:Ar(S),Ze=Et?c:Ar(M);It=It==a?C:It,Ze=Ze==a?C:Ze;var qt=It==C,er=Ze==C,At=It==Ze;if(At&&zc(S)){if(!zc(M))return!1;Qe=!0,qt=!1}if(At&&!qt)return Ie||(Ie=new Or),Qe||Vd(S)?Bd(S,M,Y,ae,We,Ie):F7(S,M,It,Y,ae,We,Ie);if(!(Y&i)){var Yt=qt&&v.call(S,"__wrapped__"),Jt=er&&v.call(M,"__wrapped__");if(Yt||Jt){var $r=Yt?S.value():S,mr=Jt?M.value():M;return Ie||(Ie=new Or),We($r,mr,Y,ae,Ie)}}return At?(Ie||(Ie=new Or),j7(S,M,Y,ae,We,Ie)):!1}function M7(S){if(!qd(S)||W7(S))return!1;var M=zd(S)?k:Q;return M.test(on(S))}function L7(S){return Wi(S)&&Wd(S.length)&&!!oe[zi(S)]}function U7(S){if(!q7(S))return io(S);var M=[];for(var Y in Object(S))v.call(S,Y)&&Y!="constructor"&&M.push(Y);return M}function Bd(S,M,Y,ae,We,Ie){var Qe=Y&i,Et=S.length,It=M.length;if(Et!=It&&!(Qe&&It>Et))return!1;var Ze=Ie.get(S);if(Ze&&Ie.get(M))return Ze==M;var qt=-1,er=!0,At=Y&s?new so:void 0;for(Ie.set(S,M),Ie.set(M,S);++qt<Et;){var Yt=S[qt],Jt=M[qt];if(ae)var $r=Qe?ae(Jt,Yt,qt,M,S,Ie):ae(Yt,Jt,qt,S,M,Ie);if($r!==void 0){if($r)continue;er=!1;break}if(At){if(!Ue(M,function(mr,an){if(!Te(At,an)&&(Yt===mr||We(Yt,mr,Y,ae,Ie)))return At.push(an)})){er=!1;break}}else if(!(Yt===Jt||We(Yt,Jt,Y,ae,Ie))){er=!1;break}}return Ie.delete(S),Ie.delete(M),er}function F7(S,M,Y,ae,We,Ie,Qe){switch(Y){case X:if(S.byteLength!=M.byteLength||S.byteOffset!=M.byteOffset)return!1;S=S.buffer,M=M.buffer;case q:return!(S.byteLength!=M.byteLength||!Ie(new Re(S),new Re(M)));case p:case m:case N:return Hd(+S,+M);case w:return S.name==M.name&&S.message==M.message;case I:case h:return S==M+"";case T:var Et=me;case O:var It=ae&i;if(Et||(Et=Oe),S.size!=M.size&&!It)return!1;var Ze=Qe.get(S);if(Ze)return Ze==M;ae|=s,Qe.set(S,M);var qt=Bd(Et(S),Et(M),ae,We,Ie,Qe);return Qe.delete(S),qt;case _:if(ot)return ot.call(S)==ot.call(M)}return!1}function j7(S,M,Y,ae,We,Ie){var Qe=Y&i,Et=kd(S),It=Et.length,Ze=kd(M),qt=Ze.length;if(It!=qt&&!Qe)return!1;for(var er=It;er--;){var At=Et[er];if(!(Qe?At in M:v.call(M,At)))return!1}var Yt=Ie.get(S);if(Yt&&Ie.get(M))return Yt==M;var Jt=!0;Ie.set(S,M),Ie.set(M,S);for(var $r=Qe;++er<It;){At=Et[er];var mr=S[At],an=M[At];if(ae)var Kd=Qe?ae(an,mr,At,M,S,Ie):ae(mr,an,At,S,M,Ie);if(!(Kd===void 0?mr===an||We(mr,an,Y,ae,Ie):Kd)){Jt=!1;break}$r||($r=At=="constructor")}if(Jt&&!$r){var lo=S.constructor,uo=M.constructor;lo!=uo&&"constructor"in S&&"constructor"in M&&!(typeof lo=="function"&&lo instanceof lo&&typeof uo=="function"&&uo instanceof uo)&&(Jt=!1)}return Ie.delete(S),Ie.delete(M),Jt}function kd(S){return N7(S,Y7,k7)}function ao(S,M){var Y=S.__data__;return z7(M)?Y[typeof M=="string"?"string":"hash"]:Y.map}function Fn(S,M){var Y=De(S,M);return M7(Y)?Y:void 0}function B7(S){var M=v.call(S,Wt),Y=S[Wt];try{S[Wt]=void 0;var ae=!0}catch{}var We=L.call(S);return ae&&(M?S[Wt]=Y:delete S[Wt]),We}var k7=nn?function(S){return S==null?[]:(S=Object(S),Le(nn(S),function(M){return Fe.call(S,M)}))}:J7,Ar=zi;(rt&&Ar(new rt(new ArrayBuffer(1)))!=X||Je&&Ar(new Je)!=T||nt&&Ar(nt.resolve())!=D||it&&Ar(new it)!=O||st&&Ar(new st)!=B)&&(Ar=function(S){var M=zi(S),Y=M==C?S.constructor:void 0,ae=Y?on(Y):"";if(ae)switch(ae){case gt:return X;case mt:return T;case wt:return D;case yt:return O;case bt:return B}return M});function H7(S,M){return M=M??o,!!M&&(typeof S=="number"||pe.test(S))&&S>-1&&S%1==0&&S<M}function z7(S){var M=typeof S;return M=="string"||M=="number"||M=="symbol"||M=="boolean"?S!=="__proto__":S===null}function W7(S){return!!P&&P in S}function q7(S){var M=S&&S.constructor,Y=typeof M=="function"&&M.prototype||g;return S===Y}function V7(S){return L.call(S)}function on(S){if(S!=null){try{return d.call(S)}catch{}try{return S+""}catch{}}return""}function Hd(S,M){return S===M||S!==S&&M!==M}var K7=Fd(function(){return arguments}())?Fd:function(S){return Wi(S)&&v.call(S,"callee")&&!Fe.call(S,"callee")},co=Array.isArray;function G7(S){return S!=null&&Wd(S.length)&&!zd(S)}var zc=Hi||X7;function Z7(S,M){return jd(S,M)}function zd(S){if(!qd(S))return!1;var M=zi(S);return M==y||M==E||M==l||M==b}function Wd(S){return typeof S=="number"&&S>-1&&S%1==0&&S<=o}function qd(S){var M=typeof S;return S!=null&&(M=="object"||M=="function")}function Wi(S){return S!=null&&typeof S=="object"}var Vd=Ee?qe(Ee):L7;function Y7(S){return G7(S)?T7(S):U7(S)}function J7(){return[]}function X7(){return!1}t.exports=Z7})(fa,fa.exports);var vw=fa.exports,_w=Object.defineProperty,uh=Object.getOwnPropertySymbols,Ew=Object.prototype.hasOwnProperty,xw=Object.prototype.propertyIsEnumerable,hh=(t,e,r)=>e in t?_w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tt=(t,e)=>{for(var r in e||(e={}))Ew.call(e,r)&&hh(t,r,e[r]);if(uh)for(var r of uh(e))xw.call(e,r)&&hh(t,r,e[r]);return t};function Cw(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var T=0,N=0,U=0,C=E.length;U!==C&&E[U]===0;)U++,T++;for(var D=(C-U)*p+1>>>0,b=new Uint8Array(D);U!==C;){for(var I=E[U],O=0,h=D-1;(I!==0||O<N)&&h!==-1;h--,O++)I+=256*b[h]>>>0,b[h]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");N=O,U++}for(var _=D-N;_!==D&&b[_]===0;)_++;for(var H=c.repeat(T);_<D;++_)H+=t.charAt(b[_]);return H}function w(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var T=0;if(E[T]!==" "){for(var N=0,U=0;E[T]===c;)N++,T++;for(var C=(E.length-T)*l+1>>>0,D=new Uint8Array(C);E[T];){var b=r[E.charCodeAt(T)];if(b===255)return;for(var I=0,O=C-1;(b!==0||I<U)&&O!==-1;O--,I++)b+=a*D[O]>>>0,D[O]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");U=I,T++}if(E[T]!==" "){for(var h=C-U;h!==C&&D[h]===0;)h++;for(var _=new Uint8Array(N+(C-h)),H=N;h!==C;)_[H++]=D[h++];return _}}}function y(E){var T=w(E);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:w,decode:y}}var Sw=Cw,Iw=Sw;const dh=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Dw=t=>new TextEncoder().encode(t),Ow=t=>new TextDecoder().decode(t);class Aw{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class $w{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return fh(this,e)}}class Pw{constructor(e){this.decoders=e}or(e){return fh(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const fh=(t,e)=>new Pw(Tt(Tt({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class Tw{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Aw(e,r,n),this.decoder=new $w(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ds=({name:t,prefix:e,encode:r,decode:n})=>new Tw(t,e,r,n),hi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Iw(r,e);return ds({prefix:t,name:e,encode:n,decode:s=>dh(i(s))})},Nw=(t,e,r,n)=>{const i={};for(let p=0;p<e.length;++p)i[e[p]]=p;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let p=0;p<s;++p){const m=i[t[p]];if(m===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|m,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Rw=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},St=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ds({prefix:e,name:t,encode(i){return Rw(i,n,r)},decode(i){return Nw(i,n,r,t)}}),Mw=ds({prefix:"\0",name:"identity",encode:t=>Ow(t),decode:t=>Dw(t)});var Lw=Object.freeze({__proto__:null,identity:Mw});const Uw=St({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Fw=Object.freeze({__proto__:null,base2:Uw});const jw=St({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Bw=Object.freeze({__proto__:null,base8:jw});const kw=hi({prefix:"9",name:"base10",alphabet:"0123456789"});var Hw=Object.freeze({__proto__:null,base10:kw});const zw=St({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ww=St({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qw=Object.freeze({__proto__:null,base16:zw,base16upper:Ww});const Vw=St({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Kw=St({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gw=St({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zw=St({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Yw=St({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jw=St({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xw=St({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qw=St({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),e5=St({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var t5=Object.freeze({__proto__:null,base32:Vw,base32upper:Kw,base32pad:Gw,base32padupper:Zw,base32hex:Yw,base32hexupper:Jw,base32hexpad:Xw,base32hexpadupper:Qw,base32z:e5});const r5=hi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),n5=hi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var i5=Object.freeze({__proto__:null,base36:r5,base36upper:n5});const s5=hi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),o5=hi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var a5=Object.freeze({__proto__:null,base58btc:s5,base58flickr:o5});const c5=St({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),l5=St({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),u5=St({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),h5=St({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var d5=Object.freeze({__proto__:null,base64:c5,base64pad:l5,base64url:u5,base64urlpad:h5});const ph=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),f5=ph.reduce((t,e,r)=>(t[r]=e,t),[]),p5=ph.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function g5(t){return t.reduce((e,r)=>(e+=f5[r],e),"")}function m5(t){const e=[];for(const r of t){const n=p5[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const w5=ds({prefix:"\u{1F680}",name:"base256emoji",encode:g5,decode:m5});var y5=Object.freeze({__proto__:null,base256emoji:w5}),b5=mh,gh=128,v5=127,_5=~v5,E5=Math.pow(2,31);function mh(t,e,r){e=e||[],r=r||0;for(var n=r;t>=E5;)e[r++]=t&255|gh,t/=128;for(;t&_5;)e[r++]=t&255|gh,t>>>=7;return e[r]=t|0,mh.bytes=r-n+1,e}var x5=pa,C5=128,wh=127;function pa(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw pa.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&wh)<<i:(o&wh)*Math.pow(2,i),i+=7}while(o>=C5);return pa.bytes=s-n,r}var S5=Math.pow(2,7),I5=Math.pow(2,14),D5=Math.pow(2,21),O5=Math.pow(2,28),A5=Math.pow(2,35),$5=Math.pow(2,42),P5=Math.pow(2,49),T5=Math.pow(2,56),N5=Math.pow(2,63),R5=function(t){return t<S5?1:t<I5?2:t<D5?3:t<O5?4:t<A5?5:t<$5?6:t<P5?7:t<T5?8:t<N5?9:10},M5={encode:b5,decode:x5,encodingLength:R5},yh=M5;const bh=(t,e,r=0)=>(yh.encode(t,e,r),e),vh=t=>yh.encodingLength(t),ga=(t,e)=>{const r=e.byteLength,n=vh(t),i=n+vh(r),s=new Uint8Array(i+r);return bh(t,s,0),bh(r,s,n),s.set(e,i),new L5(t,r,e,s)};class L5{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const _h=({name:t,code:e,encode:r})=>new U5(t,e,r);class U5{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ga(this.code,r):r.then(n=>ga(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Eh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),F5=_h({name:"sha2-256",code:18,encode:Eh("SHA-256")}),j5=_h({name:"sha2-512",code:19,encode:Eh("SHA-512")});var B5=Object.freeze({__proto__:null,sha256:F5,sha512:j5});const xh=0,k5="identity",Ch=dh;var H5=Object.freeze({__proto__:null,identity:{code:xh,name:k5,encode:Ch,digest:t=>ga(xh,Ch(t))}});new TextEncoder,new TextDecoder;const Sh=Tt(Tt(Tt(Tt(Tt(Tt(Tt(Tt(Tt(Tt({},Lw),Fw),Bw),Hw),qw),t5),i5),a5),d5),y5);Tt(Tt({},B5),H5);function z5(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Ih(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Dh=Ih("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ma=Ih("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=z5(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),W5=Tt({utf8:Dh,"utf-8":Dh,hex:Sh.base16,latin1:ma,ascii:ma,binary:ma},Sh);function q5(t,e="utf8"){const r=W5[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}const Oh="wc",V5=2,wa="core",vr=`${Oh}@${2}:${wa}:`,K5={name:wa,logger:"error"},G5={database:":memory:"},Z5="crypto",Ah="client_ed25519_seed",Y5=fe.ONE_DAY,J5="keychain",X5="0.3",Q5="messages",ey="0.3",ty=fe.SIX_HOURS,ry="publisher",$h="irn",ny="error",Ph="wss://relay.walletconnect.com",iy="relayer",ft={message:"relayer_message",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},sy="_subscription",fs={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Th=fe.ONE_SECOND,oy="2.4.10",ay="0.3",ir={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},cy="subscription",ly="0.3",uy=fe.FIVE_SECONDS*1e3,hy="pairing",dy="0.3",di={wc_pairingDelete:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:0},res:{ttl:fe.ONE_DAY,prompt:!1,tag:0}}},sr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},fy="history",py="0.3",gy="expirer",Vt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},my="0.3";class wy{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=J5,this.version=X5,this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=ie("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=Be.generateChildLogger(r,this.name)}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,uu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?hu(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class yy{constructor(e,r,n){this.core=e,this.logger=r,this.name=Z5,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Yu(i);return Zu(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=yg();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Yu(s),a=Fo();return await $m(a,i,Y5,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=bg(a,s);return this.setSymKey(c,o)},this.setSymKey=async(i,s)=>{this.isInitialized();const o=s||vg(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();const a=iu(o),c=ai(s);if(su(a)){const w=a.senderPublicKey,y=a.receiverPublicKey;i=await this.generateSharedKey(w,y)}const l=this.getSymKey(i),{type:p,senderPublicKey:m}=a;return Eg({type:p,symKey:l,message:c,senderPublicKey:m})},this.decode=async(i,s,o)=>{this.isInitialized();const a=Sg(s,o);if(su(a)){const p=a.receiverPublicKey,m=a.senderPublicKey;i=await this.generateSharedKey(p,m)}const c=this.getSymKey(i),l=xg({symKey:c,encoded:s});return ia(l)},this.core=e,this.logger=Be.generateChildLogger(r,this.name),this.keychain=n||new wy(this.core,this.logger)}get context(){return Be.getLoggerContext(this.logger)}getPayloadType(e){const r=jo(e);return qn(r.type)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ah)}catch{e=Fo(),await this.keychain.set(Ah,e)}return q5(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class by extends lm{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=Q5,this.version=ey,this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const s=rs(i);let o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const s=this.get(n),o=rs(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=Be.generateChildLogger(e,this.name),this.core=r}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,uu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?hu(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class vy extends um{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new xt.exports.EventEmitter,this.name=ry,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(n,i,s)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});try{const o=s?.ttl||ty,a=ko(s),c=s?.prompt||!1,l=s?.tag||0,p={topic:n,message:i,opts:{ttl:o,relay:a,prompt:c,tag:l}},m=rs(i);this.queue.set(m,p);try{await await Bo(this.rpcPublish(n,i,o,a,c,l),this.publishTimeout),this.relayer.events.emit(ft.publish,p)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(ft.connection_stalled);return}this.onPublish(m,p),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}})}catch(o){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(o),o}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=Be.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return Be.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o){var a,c,l,p;const m={method:ns(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o}};return $t((a=m.params)==null?void 0:a.prompt)&&((c=m.params)==null||delete c.prompt),$t((l=m.params)==null?void 0:l.tag)&&((p=m.params)==null||delete p.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m}),this.relayer.provider.request(m)}onPublish(e,r){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(ri.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()})}}class _y{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var Ey=Object.defineProperty,xy=Object.defineProperties,Cy=Object.getOwnPropertyDescriptors,Nh=Object.getOwnPropertySymbols,Sy=Object.prototype.hasOwnProperty,Iy=Object.prototype.propertyIsEnumerable,Rh=(t,e,r)=>e in t?Ey(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fi=(t,e)=>{for(var r in e||(e={}))Sy.call(e,r)&&Rh(t,r,e[r]);if(Nh)for(var r of Nh(e))Iy.call(e,r)&&Rh(t,r,e[r]);return t},ya=(t,e)=>xy(t,Cy(e));class Dy extends fm{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new _y,this.events=new xt.exports.EventEmitter,this.name=cy,this.version=ly,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=vr,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=ko(i),o={topic:n,relay:s};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s);return this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,s)=>{const o=new fe.Watch;o.start(this.pendingSubscriptionWatchLabel);const a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),i(!0)),o.elapsed(this.pendingSubscriptionWatchLabel)>=uy&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),s(!1))},this.pollingInterval)}),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Be.generateChildLogger(r,this.name),this.clientId=""}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=ko(n);await this.rpcUnsubscribe(e,r,i);const s=tt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:ns(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Bo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(ft.connection_stalled)}return rs(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:ns(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await Bo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(ft.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:ns(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.provider.request(i)}onSubscribe(e,r){this.setSubscription(e,ya(fi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,fi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,fi({},r)),this.topicMap.set(r.topic,e),this.events.emit(ir.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(ir.deleted,ya(fi({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ir.sync)}async reset(){if(!this.cached.length)return;const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}this.events.emit(ir.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);this.onBatchSubscribe(r.map((n,i)=>ya(fi({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(ri.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(ft.connect,async()=>{await this.onConnect()}),this.relayer.on(ft.disconnect,()=>{this.onDisconnect()}),this.events.on(ir.created,async e=>{const r=ir.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(ir.deleted,async e=>{const r=ir.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var Oy=Object.defineProperty,Mh=Object.getOwnPropertySymbols,Ay=Object.prototype.hasOwnProperty,$y=Object.prototype.propertyIsEnumerable,Lh=(t,e,r)=>e in t?Oy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Py=(t,e)=>{for(var r in e||(e={}))Ay.call(e,r)&&Lh(t,r,e[r]);if(Mh)for(var r of Mh(e))$y.call(e,r)&&Lh(t,r,e[r]);return t};class Ty extends hm{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new xt.exports.EventEmitter,this.name=iy,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Be.generateChildLogger(e.logger,this.name):Gn(Be.getDefaultLoggerOptions({level:e.logger||ny})),this.messages=new by(this.logger,e.core),this.subscriber=new Dy(this,this.logger),this.publisher=new vy(this,this.logger),this.relayUrl=e?.relayUrl||Ph,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),this.provider=await this.createProvider(),await Promise.all([this.messages.init(),this.transportOpen(),this.subscriber.init()]),this.registerEventListeners(),this.initialized=!0}get context(){return Be.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){this.isInitialized();let n="";return await Promise.all([new Promise(i=>{this.subscriber.once(ir.created,s=>{s.topic===e&&i()})}),new Promise(async i=>{n=await this.subscriber.subscribe(e,r),i()})]),n}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(ft.transport_closed))}async transportOpen(e){if(!this.reconnecting){this.relayUrl=e||this.relayUrl,this.transportExplicitlyClosed=!1,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(ir.resubscribed,()=>{r()})}),await Promise.race([new Promise(async r=>{await this.provider.connect(),this.removeListener(ft.transport_closed,this.rejectTransportOpen),r()}),new Promise(r=>this.once(ft.transport_closed,this.rejectTransportOpen))])])}catch(r){const n=r;if(!/socket hang up/i.test(n.message))throw r;this.logger.error(r),this.events.emit(ft.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(await this.transportClose(),await new Promise(r=>setTimeout(r,Th)),await this.transportOpen(e))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);return new ui(new bw(jg({sdkVersion:oy,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0})))}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;return await this.subscriber.isSubscribed(r)?this.messages.has(r,n):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),ha(e)){if(!e.method.endsWith(sy))return;const r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Py({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(ft.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=ua(e.id,!0);await this.provider.connection.send(r)}registerEventListeners(){this.provider.on(fs.payload,e=>this.onProviderPayload(e)),this.provider.on(fs.connect,()=>{this.events.emit(ft.connect)}),this.provider.on(fs.disconnect,()=>{this.events.emit(ft.disconnect),this.attemptToReconnect()}),this.provider.on(fs.error,e=>{this.logger.error(e),this.events.emit(ft.error,e)}),this.events.on(ft.connection_stalled,async()=>{await this.restartTransport()})}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.transportOpen()},fe.toMiliseconds(Th))}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ny=Object.defineProperty,Uh=Object.getOwnPropertySymbols,Ry=Object.prototype.hasOwnProperty,My=Object.prototype.propertyIsEnumerable,Fh=(t,e,r)=>e in t?Ny(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jh=(t,e)=>{for(var r in e||(e={}))Ry.call(e,r)&&Fh(t,r,e[r]);if(Uh)for(var r of Uh(e))My.call(e,r)&&Fh(t,r,e[r]);return t};class ps extends dm{constructor(e,r,n,i=vr,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=ay,this.cached=[],this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{o3(o)?this.map.set(o.id,o):a3(o)?this.map.set(o.topic,o):this.getKey&&o!==null&&!$t(o)&&this.map.set(this.getKey(o),o)}),this.cached=[],this.initialized=!0)},this.set=async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>vw(a[c],o[c]))):this.values),this.update=async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=jh(jh({},this.getData(o)),a);this.map.set(o,c),await this.persist()},this.delete=async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),await this.persist())},this.logger=Be.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Ly{constructor(e,r){this.core=e,this.logger=r,this.name=hy,this.version=dy,this.events=new xt.exports,this.initialized=!1,this.storagePrefix=vr,this.ignoredPayloadTypes=[Mr],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();const n=Fo(),i=await this.core.crypto.setSymKey(n),s=rr(fe.FIVE_MINUTES),o={protocol:$h},a={topic:i,expiry:s,relay:o,active:!1},c=Yg({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:o});return await this.pairings.set(i,a),await this.core.relayer.subscribe(i),this.core.expirer.set(i,s),{topic:i,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:s,relay:o}=Gg(n.uri);if(this.pairings.keys.includes(i))throw new Error(`Pairing already exists: ${i}`);if(this.core.crypto.hasKeys(i))throw new Error(`Keychain already exists: ${i}`);const a=rr(fe.FIVE_MINUTES),c={topic:i,relay:o,expiry:a,active:!1};return await this.pairings.set(i,c),await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),this.core.expirer.set(i,a),n.activatePairing&&await this.activate({topic:i}),c},this.activate=async({topic:n})=>{this.isInitialized();const i=rr(fe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ur();this.events.once(et("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",tt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{const o=us(i,s),a=await this.core.crypto.encode(n,o),c=di[i].req;return this.core.history.set(n,o),await this.core.relayer.publish(n,a,c),o.id},this.sendResult=async(n,i,s)=>{const o=ua(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=di[c.request.method].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{const o=hs(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=di[c.request.method]?di[c.request.method].res:di.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,tt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>yr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:s}=n,o=s.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit("pairing_ping",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{const{id:s}=i;setTimeout(()=>{fr(i)?this.events.emit(et("pairing_ping",s),{}):Qt(i)&&this.events.emit(et("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit("pairing_delete",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=tt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(tt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!Ft(n)){const{message:i}=ie("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!s3(n.uri)){const{message:i}=ie("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!Ft(n)){const{message:s}=ie("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Ft(n)){const{message:s}=ie("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!dt(n,!1)){const{message:i}=ie("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(yr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=ie("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=Be.generateChildLogger(r,this.name),this.pairings=new ps(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Be.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ft.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);ha(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):da(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(Vt.expired,async e=>{const{topic:r}=fu(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class Uy extends cm{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new xt.exports.EventEmitter,this.name=fy,this.version=py,this.cached=[],this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s};this.records.set(o.id,o),this.events.emit(sr.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Qt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(sr.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(sr.deleted,s)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Be.generateChildLogger(r,this.name)}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:us(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(sr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(sr.created,e=>{const r=sr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(sr.updated,e=>{const r=sr.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(sr.deleted,e=>{const r=sr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Fy extends pm{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new xt.exports.EventEmitter,this.name=gy,this.version=my,this.cached=[],this.initialized=!1,this.storagePrefix=vr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Vt.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Vt.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Be.generateChildLogger(r,this.name)}get context(){return Be.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Bg(e);if(typeof e=="number")return kg(e);const{message:r}=ie("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Vt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=ie("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;fe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Vt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ri.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Vt.created,e=>{const r=Vt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Vt.expired,e=>{const r=Vt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Vt.deleted,e=>{const r=Vt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jy=Object.defineProperty,Bh=Object.getOwnPropertySymbols,By=Object.prototype.hasOwnProperty,ky=Object.prototype.propertyIsEnumerable,kh=(t,e,r)=>e in t?jy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hh=(t,e)=>{for(var r in e||(e={}))By.call(e,r)&&kh(t,r,e[r]);if(Bh)for(var r of Bh(e))ky.call(e,r)&&kh(t,r,e[r]);return t};class ba extends am{constructor(e){super(e),this.protocol=Oh,this.version=V5,this.name=wa,this.events=new xt.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ph;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gn(Be.getDefaultLoggerOptions({level:e?.logger||K5.logger}));this.logger=Be.generateChildLogger(r,this.name),this.heartbeat=new ri.HeartBeat,this.crypto=new yy(this,this.logger,e?.keychain),this.history=new Uy(this,this.logger),this.expirer=new Fy(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new f2(Hh(Hh({},G5),e?.storageOptions)),this.relayer=new Ty({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ly(this,this.logger)}static async init(e){const r=new ba(e);return await r.initialize(),r}get context(){return Be.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const Hy=ba,zh="wc",Wh=2,qh="client",va=`${zh}@${Wh}:${qh}:`,_a={name:qh,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},zy="proposal",Vh="Proposal expired",Wy="session",gs=fe.SEVEN_DAYS,qy="engine",pi={wc_sessionPropose:{req:{ttl:fe.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1104},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1106},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:fe.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:fe.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:fe.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:fe.ONE_DAY,prompt:!1,tag:1112},res:{ttl:fe.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:fe.THIRTY_SECONDS,prompt:!1,tag:1115}}},Ea={min:fe.FIVE_MINUTES,max:fe.SEVEN_DAYS},Vy="request";var Ky=Object.defineProperty,Gy=Object.defineProperties,Zy=Object.getOwnPropertyDescriptors,Kh=Object.getOwnPropertySymbols,Yy=Object.prototype.hasOwnProperty,Jy=Object.prototype.propertyIsEnumerable,Gh=(t,e,r)=>e in t?Ky(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kt=(t,e)=>{for(var r in e||(e={}))Yy.call(e,r)&&Gh(t,r,e[r]);if(Kh)for(var r of Kh(e))Jy.call(e,r)&&Gh(t,r,e[r]);return t},xa=(t,e)=>Gy(t,Zy(e));class Xy extends mm{constructor(e){super(e),this.name=qy,this.events=new xt.exports,this.initialized=!1,this.ignoredPayloadTypes=[Mr],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(pi)}),this.initialized=!0)},this.connect=async r=>{this.isInitialized();const n=xa(Kt({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:c}=n;let l=i,p,m=!1;if(l&&(m=this.client.core.pairing.pairings.get(l).active),!l||!m){const{topic:D,uri:b}=await this.client.core.pairing.create();l=D,p=b}const w=await this.client.core.crypto.generateKeyPair(),y=Kt({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:$h}],proposer:{publicKey:w,metadata:this.client.metadata}},a&&{sessionProperties:a}),{reject:E,resolve:T,done:N}=Ur(fe.FIVE_MINUTES,Vh);if(this.events.once(et("session_connect"),async({error:D,session:b})=>{if(D)E(D);else if(b){b.self.publicKey=w;const I=xa(Kt({},b),{requiredNamespaces:b.requiredNamespaces,optionalNamespaces:b.optionalNamespaces});await this.client.session.set(b.topic,I),await this.setExpiry(b.topic,b.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:b.peer.metadata}),T(I)}}),!l){const{message:D}=ie("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const U=await this.sendRequest(l,"wc_sessionPropose",y),C=rr(fe.FIVE_MINUTES);return await this.setProposal(U,Kt({id:U,expiry:C},y)),{uri:p,approval:N}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{this.isInitialized(),await this.isValidApprove(r);const{id:n,relayProtocol:i,namespaces:s,sessionProperties:o}=r,a=this.client.proposal.get(n);let{pairingTopic:c,proposer:l,requiredNamespaces:p,optionalNamespaces:m}=a;Kn(p)||(p=e3(s,"approve()"));const w=await this.client.core.crypto.generateKeyPair(),y=l.publicKey,E=await this.client.core.crypto.generateSharedKey(w,y);c&&n&&(await this.client.core.pairing.updateMetadata({topic:c,metadata:l.metadata}),await this.sendResult(n,c,{relay:{protocol:i??"irn"},responderPublicKey:w}),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}));const T=Kt({relay:{protocol:i??"irn"},namespaces:s,requiredNamespaces:p,optionalNamespaces:m,controller:{publicKey:w,metadata:this.client.metadata},expiry:rr(gs)},o&&{sessionProperties:o});await this.client.core.relayer.subscribe(E);const N=await this.sendRequest(E,"wc_sessionSettle",T),{done:U,resolve:C,reject:D}=Ur();this.events.once(et("session_approve",N),({error:I})=>{I?D(I):C(this.client.session.get(E))});const b=xa(Kt({},T),{topic:E,acknowledged:!1,self:T.controller,peer:{publicKey:l.publicKey,metadata:l.metadata},controller:w});return await this.client.session.set(E,b),await this.setExpiry(E,rr(gs)),{topic:E,acknowledged:U}},this.reject=async r=>{this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:s}=this.client.proposal.get(n);s&&(await this.sendError(n,s,i),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,s=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:o,resolve:a,reject:c}=Ur();return this.events.once(et("session_update",s),({error:l})=>{l?c(l):a()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:o}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:s,resolve:o,reject:a}=Ur();return this.events.once(et("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,rr(gs)),{acknowledged:s}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:s,expiry:o}=r,a=await this.sendRequest(s,"wc_sessionRequest",{request:i,chainId:n},o),{done:c,resolve:l,reject:p}=Ur(o);return this.events.once(et("session_request",a),({error:m,result:w})=>{m?p(m):l(w)}),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n}),await c()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i;fr(i)?await this.sendResult(s,n,i.result):Qt(i)&&await this.sendError(s,n,i.error),this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:s,resolve:o,reject:a}=Ur();this.events.once(et("session_ping",i),({error:c})=>{c?a(c):o()}),await s()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:s})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest(n,"wc_sessionDelete",tt("USER_DISCONNECTED")),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>n3(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await Promise.all([this.client.session.delete(r,tt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(r),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,tt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=pi.wc_sessionRequest.req.ttl,{id:i,topic:s,params:o}=r;await this.client.pendingRequest.set(i,{id:i,topic:s,params:o}),n&&this.client.core.expirer.set(i,rr(n))},this.sendRequest=async(r,n,i,s)=>{const o=us(n,i),a=await this.client.core.crypto.encode(r,o),c=pi[n].req;return s&&(c.ttl=s),this.client.core.history.set(r,o),this.client.core.relayer.publish(r,a,c),o.id},this.sendResult=async(r,n,i)=>{const s=ua(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=pi[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.sendError=async(r,n,i)=>{const s=hs(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=pi[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{yr(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{yr(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=r=>{const{topic:n,payload:i}=r,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidConnect(Kt({},n.params));const o=rr(fe.FIVE_MINUTES),a=Kt({id:s,pairingTopic:r,expiry:o},i);await this.setProposal(s,a),this.client.events.emit("session_proposal",{id:s,params:a})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(fr(n)){const{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});const a=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const c=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const l=await this.client.core.crypto.generateSharedKey(a,c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const p=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:r})}else Qt(n)&&(await this.client.proposal.delete(i,tt("USER_DISCONNECTED")),this.events.emit(et("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,requiredNamespaces:p,optionalNamespaces:m,sessionProperties:w}=n.params,y=Kt({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,requiredNamespaces:p,optionalNamespaces:m,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},w&&{sessionProperties:w});await this.sendResult(n.id,r,!0),this.events.emit(et("session_connect"),{session:y})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;fr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(et("session_approve",i),{})):Qt(n)&&(await this.client.session.delete(r,tt("USER_DISCONNECTED")),this.events.emit(et("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidUpdate(Kt({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(s,r,!0),this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;fr(n)?this.events.emit(et("session_update",i),{}):Qt(n)&&this.events.emit(et("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,rr(gs)),await this.sendResult(i,r,!0),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;fr(n)?this.events.emit(et("session_extend",i),{}):Qt(n)&&this.events.emit(et("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{fr(n)?this.events.emit(et("session_ping",i),{}):Qt(n)&&this.events.emit(et("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),this.client.core.relayer.once(ft.publish,async()=>{await this.deleteSession(r)}),await this.sendResult(i,r,!0),this.client.events.emit("session_delete",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidRequest(Kt({topic:r},s)),await this.setPendingSessionRequest({id:i,topic:r,params:s}),this.client.events.emit("session_request",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;fr(n)?this.events.emit(et("session_request",i),{result:n.result}):Qt(n)&&this.events.emit(et("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidEmit(Kt({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.isValidConnect=async r=>{if(!Ft(r)){const{message:c}=ie("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(c)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if($t(n)||await this.isValidPairingTopic(n),!g3(a,!0)){const{message:c}=ie("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!$t(i)&&Kn(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!$t(s)&&Kn(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),$t(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=p3(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!Ft(r))throw new Error(ie("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;await this.isValidProposalId(n);const a=this.client.proposal.get(n),c=is(i,"approve()");if(c)throw new Error(c.message);const l=vu(a.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!dt(s,!0)){const{message:p}=ie("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(p)}$t(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!Ft(r)){const{message:s}=ie("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!w3(i)){const{message:s}=ie("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!Ft(r)){const{message:l}=ie("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!yu(n)){const{message:l}=ie("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=c3(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=is(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(yr(o)){const{message:l}=ie("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!Ft(r)){const{message:c}=ie("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=is(i,"update()");if(o)throw new Error(o.message);const a=vu(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!Ft(r)){const{message:i}=ie("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!Ft(r)){const{message:c}=ie("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!bu(a,s)){const{message:c}=ie("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!y3(i)){const{message:c}=ie("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!_3(a,s,i.method)){const{message:c}=ie("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!S3(o,Ea)){const{message:c}=ie("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ea.min} and ${Ea.max}`);throw new Error(c)}},this.isValidRespond=async r=>{if(!Ft(r)){const{message:s}=ie("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(s)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!b3(i)){const{message:s}=ie("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidPing=async r=>{if(!Ft(r)){const{message:i}=ie("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!Ft(r)){const{message:a}=ie("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!bu(o,s)){const{message:a}=ie("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!v3(i)){const{message:a}=ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!E3(o,s,i.name)){const{message:a}=ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!Ft(r)){const{message:i}=ie("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!dt(i,!1)){const{message:s}=ie("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})}}isInitialized(){if(!this.initialized){const{message:e}=ie("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(ft.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);ha(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):da(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(Vt.expired,async e=>{const{topic:r,id:n}=fu(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,ie("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}isValidPairingTopic(e){if(!dt(e,!1)){const{message:r}=ie("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(yr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=ie("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!dt(e,!1)){const{message:r}=ie("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=ie("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(yr(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=ie("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(dt(e,!1)){const{message:r}=ie("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=ie("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!m3(e)){const{message:r}=ie("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=ie("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(yr(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=ie("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class Qy extends ps{constructor(e,r){super(e,r,zy,va),this.core=e,this.logger=r}}class eb extends ps{constructor(e,r){super(e,r,Wy,va),this.core=e,this.logger=r}}class tb extends ps{constructor(e,r){super(e,r,Vy,va),this.core=e,this.logger=r}}class Ca extends gm{constructor(e){super(e),this.protocol=zh,this.version=Wh,this.name=_a.name,this.events=new xt.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||_a.name,this.metadata=e?.metadata||Mg();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gn(Be.getDefaultLoggerOptions({level:e?.logger||_a.logger}));this.core=e?.core||new Hy(e),this.logger=Be.generateChildLogger(r,this.name),this.session=new eb(this.core,this.logger),this.proposal=new Qy(this.core,this.logger),this.pendingRequest=new tb(this.core,this.logger),this.engine=new Xy(this)}static async init(e){const r=new Ca(e);return await r.initialize(),r}get context(){return Be.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Sa={exports:{}};(function(t,e){var r=typeof self<"u"?self:ht,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function c(x){return x&&DataView.prototype.isPrototypeOf(x)}if(a.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],p=ArrayBuffer.isView||function(x){return x&&l.indexOf(Object.prototype.toString.call(x))>-1};function m(x){if(typeof x!="string"&&(x=String(x)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(x))throw new TypeError("Invalid character in header field name");return x.toLowerCase()}function w(x){return typeof x!="string"&&(x=String(x)),x}function y(x){var A={next:function(){var G=x.shift();return{done:G===void 0,value:G}}};return a.iterable&&(A[Symbol.iterator]=function(){return A}),A}function E(x){this.map={},x instanceof E?x.forEach(function(A,G){this.append(G,A)},this):Array.isArray(x)?x.forEach(function(A){this.append(A[0],A[1])},this):x&&Object.getOwnPropertyNames(x).forEach(function(A){this.append(A,x[A])},this)}E.prototype.append=function(x,A){x=m(x),A=w(A);var G=this.map[x];this.map[x]=G?G+", "+A:A},E.prototype.delete=function(x){delete this.map[m(x)]},E.prototype.get=function(x){return x=m(x),this.has(x)?this.map[x]:null},E.prototype.has=function(x){return this.map.hasOwnProperty(m(x))},E.prototype.set=function(x,A){this.map[m(x)]=w(A)},E.prototype.forEach=function(x,A){for(var G in this.map)this.map.hasOwnProperty(G)&&x.call(A,this.map[G],G,this)},E.prototype.keys=function(){var x=[];return this.forEach(function(A,G){x.push(G)}),y(x)},E.prototype.values=function(){var x=[];return this.forEach(function(A){x.push(A)}),y(x)},E.prototype.entries=function(){var x=[];return this.forEach(function(A,G){x.push([G,A])}),y(x)},a.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function T(x){if(x.bodyUsed)return Promise.reject(new TypeError("Already read"));x.bodyUsed=!0}function N(x){return new Promise(function(A,G){x.onload=function(){A(x.result)},x.onerror=function(){G(x.error)}})}function U(x){var A=new FileReader,G=N(A);return A.readAsArrayBuffer(x),G}function C(x){var A=new FileReader,G=N(A);return A.readAsText(x),G}function D(x){for(var A=new Uint8Array(x),G=new Array(A.length),K=0;K<A.length;K++)G[K]=String.fromCharCode(A[K]);return G.join("")}function b(x){if(x.slice)return x.slice(0);var A=new Uint8Array(x.byteLength);return A.set(new Uint8Array(x)),A.buffer}function I(){return this.bodyUsed=!1,this._initBody=function(x){this._bodyInit=x,x?typeof x=="string"?this._bodyText=x:a.blob&&Blob.prototype.isPrototypeOf(x)?this._bodyBlob=x:a.formData&&FormData.prototype.isPrototypeOf(x)?this._bodyFormData=x:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(x)?this._bodyText=x.toString():a.arrayBuffer&&a.blob&&c(x)?(this._bodyArrayBuffer=b(x.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(x)||p(x))?this._bodyArrayBuffer=b(x):this._bodyText=x=Object.prototype.toString.call(x):this._bodyText="",this.headers.get("content-type")||(typeof x=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(x)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var x=T(this);if(x)return x;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?T(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(U)}),this.text=function(){var x=T(this);if(x)return x;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(H)}),this.json=function(){return this.text().then(JSON.parse)},this}var O=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function h(x){var A=x.toUpperCase();return O.indexOf(A)>-1?A:x}function _(x,A){A=A||{};var G=A.body;if(x instanceof _){if(x.bodyUsed)throw new TypeError("Already read");this.url=x.url,this.credentials=x.credentials,A.headers||(this.headers=new E(x.headers)),this.method=x.method,this.mode=x.mode,this.signal=x.signal,!G&&x._bodyInit!=null&&(G=x._bodyInit,x.bodyUsed=!0)}else this.url=String(x);if(this.credentials=A.credentials||this.credentials||"same-origin",(A.headers||!this.headers)&&(this.headers=new E(A.headers)),this.method=h(A.method||this.method||"GET"),this.mode=A.mode||this.mode||null,this.signal=A.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&G)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(G)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function H(x){var A=new FormData;return x.trim().split("&").forEach(function(G){if(G){var K=G.split("="),W=K.shift().replace(/\+/g," "),z=K.join("=").replace(/\+/g," ");A.append(decodeURIComponent(W),decodeURIComponent(z))}}),A}function B(x){var A=new E,G=x.replace(/\r?\n[\t ]+/g," ");return G.split(/\r?\n/).forEach(function(K){var W=K.split(":"),z=W.shift().trim();if(z){var J=W.join(":").trim();A.append(z,J)}}),A}I.call(_.prototype);function q(x,A){A||(A={}),this.type="default",this.status=A.status===void 0?200:A.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in A?A.statusText:"OK",this.headers=new E(A.headers),this.url=A.url||"",this._initBody(x)}I.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},q.error=function(){var x=new q(null,{status:0,statusText:""});return x.type="error",x};var X=[301,302,303,307,308];q.redirect=function(x,A){if(X.indexOf(A)===-1)throw new RangeError("Invalid status code");return new q(null,{status:A,headers:{location:x}})},o.DOMException=s.DOMException;try{new o.DOMException}catch{o.DOMException=function(A,G){this.message=A,this.name=G;var K=Error(A);this.stack=K.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function te(x,A){return new Promise(function(G,K){var W=new _(x,A);if(W.signal&&W.signal.aborted)return K(new o.DOMException("Aborted","AbortError"));var z=new XMLHttpRequest;function J(){z.abort()}z.onload=function(){var Z={status:z.status,statusText:z.statusText,headers:B(z.getAllResponseHeaders()||"")};Z.url="responseURL"in z?z.responseURL:Z.headers.get("X-Request-URL");var ce="response"in z?z.response:z.responseText;G(new q(ce,Z))},z.onerror=function(){K(new TypeError("Network request failed"))},z.ontimeout=function(){K(new TypeError("Network request failed"))},z.onabort=function(){K(new o.DOMException("Aborted","AbortError"))},z.open(W.method,W.url,!0),W.credentials==="include"?z.withCredentials=!0:W.credentials==="omit"&&(z.withCredentials=!1),"responseType"in z&&a.blob&&(z.responseType="blob"),W.headers.forEach(function(Z,ce){z.setRequestHeader(ce,Z)}),W.signal&&(W.signal.addEventListener("abort",J),z.onreadystatechange=function(){z.readyState===4&&W.signal.removeEventListener("abort",J)}),z.send(typeof W._bodyInit>"u"?null:W._bodyInit)})}return te.polyfill=!0,s.fetch||(s.fetch=te,s.Headers=E,s.Request=_,s.Response=q),o.Headers=E,o.Request=_,o.Response=q,o.fetch=te,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(Sa,Sa.exports);var Zh=Gd(Sa.exports);const Yh={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},Jh=10;class ms{constructor(e){if(this.url=e,this.events=new xt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!oh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=ai(e),s=await(await Zh(this.url,Object.assign(Object.assign({},Yh),{body:n}))).json();this.onPayload({data:s})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!oh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{const r=ai({id:1,jsonrpc:"2.0",method:"test",params:[]});await Zh(e,Object.assign(Object.assign({},Yh),{body:r})),this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ia(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=hs(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return eh(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Jh&&this.events.setMaxListeners(Jh)}}const Xh="error",rb="wss://relay.walletconnect.com",nb="wc",ib="universal_provider",Qh=`${nb}@${2}:${ib}:`,sb="https://rpc.walletconnect.com/v1",gi={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function mn(t,e,r){let n;const i=Ia(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${sb}?chainId=eip155:${i}&projectId=${r}`),n}function Ia(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function ob(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function ab(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}const ws=(t,e)=>{const r=n=>{n.request!==e.request||n.topic!==e.topic||(t.events.removeListener("session_request_sent",r),cb())};t.on("session_request_sent",r)};function cb(){if(typeof window<"u")try{const t=window.localStorage.getItem("WALLETCONNECT_DEEPLINK_CHOICE");if(t){const e=JSON.parse(t);window.open(e.href,"_self","noreferrer noopener")}}catch(t){console.error(t)}}class lb{constructor(e){this.name="eip155",this.namespace=e.namespace,this.client=e.client,this.events=e.events,this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),await this.client.request(e)):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){const n=Ia(e);if(!this.httpProviders[n]){const i=r||mn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||mn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new ui(new ms(n))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=Ia(r);e[n]=this.createHttpProvider(n)}),e}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;ob(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class ub{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||mn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||mn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new ui(new ms(n))}}class hb{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||mn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||mn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new ui(new ms(n))}}class db{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ws(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new ui(new ms(n))}}var fb=Object.defineProperty,pb=Object.defineProperties,gb=Object.getOwnPropertyDescriptors,e0=Object.getOwnPropertySymbols,mb=Object.prototype.hasOwnProperty,wb=Object.prototype.propertyIsEnumerable,t0=(t,e,r)=>e in t?fb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ys=(t,e)=>{for(var r in e||(e={}))mb.call(e,r)&&t0(t,r,e[r]);if(e0)for(var r of e0(e))wb.call(e,r)&&t0(t,r,e[r]);return t},Da=(t,e)=>pb(t,gb(e));class Oa{constructor(e){this.events=new xt.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gn(Be.getDefaultLoggerOptions({level:e?.logger||Xh}))}static async init(e){const r=new Oa(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ys({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:tt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(s=>{this.session=s}).catch(s=>{if(s.message!==Vh)throw s;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(br(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await Ca.init({logger:this.providerOpts.logger||Xh,relayUrl:this.providerOpts.relayUrl||rb,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");Object.keys(this.namespaces).forEach(e=>{var r,n,i;const s=((r=this.session)==null?void 0:r.namespaces[e].accounts)||[],o=ab(s),a=Da(ys({},Object.assign(this.namespaces[e],(i=(n=this.optionalNamespaces)==null?void 0:n[e])!=null?i:{})),{accounts:s,chains:o});switch(e){case"eip155":this.rpcProviders[e]=new lb({client:this.client,namespace:a,events:this.events});break;case"solana":this.rpcProviders[e]=new ub({client:this.client,namespace:a,events:this.events});break;case"cosmos":this.rpcProviders[e]=new hb({client:this.client,namespace:a,events:this.events});break;case"polkadot":break;case"cip34":this.rpcProviders[e]=new db({client:this.client,namespace:a,events:this.events});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,s=(n=this.client)==null?void 0:n.session.get(e);this.session=Da(ys({},s),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Da(ys({},tt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(gi.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Object.keys(this.namespaces)[0],s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){const[n,i]=this.validateChain(e);r||this.getProvider(n).setDefaultChain(i),this.namespaces[n].defaultChain=i,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${Qh}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${Qh}/${e}`)}}const yb=Oa,bb="wc",vb="ethereum_provider",_b=`${bb}@${2}:${vb}:`,Eb="https://rpc.walletconnect.com/v1/",bs=["eth_sendTransaction","personal_sign"],xb=["eth_accounts","eth_requestAccounts","eth_call","eth_getBalance","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],vs=["chainChanged","accountsChanged"],Cb=["message","disconnect","connect"];var Sb=Object.defineProperty,Ib=Object.defineProperties,Db=Object.getOwnPropertyDescriptors,r0=Object.getOwnPropertySymbols,Ob=Object.prototype.hasOwnProperty,Ab=Object.prototype.propertyIsEnumerable,n0=(t,e,r)=>e in t?Sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,i0=(t,e)=>{for(var r in e||(e={}))Ob.call(e,r)&&n0(t,r,e[r]);if(r0)for(var r of r0(e))Ab.call(e,r)&&n0(t,r,e[r]);return t},s0=(t,e)=>Ib(t,Db(e));function Aa(t){return Number(t[0].split(":")[1])}function $a(t){return`0x${t.toString(16)}`}function $b(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!br(e))throw new Error("Invalid chains");const c=e,l=n||bs,p=s||vs,m={[Aa(c)]:a[Aa(c)]},w={chains:c,methods:l,events:p,rpcMap:m},y=s?.filter(U=>!vs.includes(U)),E=n?.filter(U=>!bs.includes(U));if(!r&&!o&&!i&&!(y!=null&&y.length)&&!(E!=null&&E.length))return{required:w};const T=y?.length&&E?.length||!r,N={chains:[...new Set(T?c.concat(r||[]):r)],methods:[...new Set(l.concat(i||[]))],events:[...new Set(p.concat(o||[]))],rpcMap:a};return{required:w,optional:N}}class _s{constructor(){this.events=new xt.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=_b,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new _s;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=$b(this.rpc);try{const i=await new Promise(async(o,a)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(s0(i0({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(l=>{o(l)}).catch(l=>{a(new Error(l.message))})});if(!i)return;this.setChainIds(this.rpc.chains);const s=mg(i.namespaces,[this.namespace]);this.setAccounts(s),this.events.emit("connect",{chainId:$a(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",$a(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",s0(i0({},tt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",$a(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||bs,events:e?.events||vs,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:(n=e?.showQrModal)!=null?n:!0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=Aa(this.rpc.chains),this.signer=await yb.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){const{Web3Modal:r}=await Promise.resolve().then(function(){return Qb});this.modal=new r({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains})}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&br(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&br(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${Eb}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const Pb=_s,Tb=Symbol(),o0=Object.getPrototypeOf,Pa=new WeakMap,Nb=t=>t&&(Pa.has(t)?Pa.get(t):o0(t)===Object.prototype||o0(t)===Array.prototype),Rb=t=>Nb(t)&&t[Tb]||null,a0=(t,e=!0)=>{Pa.set(t,e)},Ta=t=>typeof t=="object"&&t!==null,kr=new WeakMap,Es=new WeakSet,Mb=(t=Object.is,e=(l,p)=>new Proxy(l,p),r=l=>Ta(l)&&!Es.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),n=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,s=(l,p,m=n)=>{const w=i.get(l);if(w?.[0]===p)return w[1];const y=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return a0(y,!0),i.set(l,[p,y]),Reflect.ownKeys(l).forEach(E=>{const T=Reflect.get(l,E);Es.has(T)?(a0(T,!1),y[E]=T):T instanceof Promise?Object.defineProperty(y,E,{get(){return m(T)}}):kr.has(T)?y[E]=Ub(T,m):y[E]=T}),Object.freeze(y)},o=new WeakMap,a=[1,1],c=l=>{if(!Ta(l))throw new Error("object required");const p=o.get(l);if(p)return p;let m=a[0];const w=new Set,y=(H,B=++a[0])=>{m!==B&&(m=B,w.forEach(q=>q(H,B)))};let E=a[1];const T=(H=++a[1])=>(E!==H&&!w.size&&(E=H,U.forEach(([B])=>{const q=B[1](H);q>m&&(m=q)})),m),N=H=>(B,q)=>{const X=[...B];X[1]=[H,...X[1]],y(X,q)},U=new Map,C=(H,B)=>{if(void 0!=="production"&&U.has(H))throw new Error("prop listener already exists");if(w.size){const q=B[3](N(H));U.set(H,[B,q])}else U.set(H,[B])},D=H=>{var B;const q=U.get(H);q&&(U.delete(H),(B=q[1])==null||B.call(q))},b=H=>(w.add(H),w.size===1&&U.forEach(([q,X],te)=>{if(void 0!=="production"&&X)throw new Error("remove already exists");const x=q[3](N(te));U.set(te,[q,x])}),()=>{w.delete(H),w.size===0&&U.forEach(([q,X],te)=>{X&&(X(),U.set(te,[q]))})}),I=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),h=e(I,{deleteProperty(H,B){const q=Reflect.get(H,B);D(B);const X=Reflect.deleteProperty(H,B);return X&&y(["delete",[B],q]),X},set(H,B,q,X){var te;const x=Reflect.has(H,B),A=Reflect.get(H,B,X);if(x&&t(A,q))return!0;D(B),Ta(q)&&(q=Rb(q)||q);let G=q;if(!((te=Object.getOwnPropertyDescriptor(H,B))!=null&&te.set))if(q instanceof Promise)q.then(K=>{q.status="fulfilled",q.value=K,y(["resolve",[B],K])}).catch(K=>{q.status="rejected",q.reason=K,y(["reject",[B],K])});else{!kr.has(q)&&r(q)&&(G=or(q));const K=!Es.has(G)&&kr.get(G);K&&C(B,K)}return Reflect.set(H,B,G,X),y(["set",[B],q,A]),!0}});o.set(l,h);const _=[I,T,s,b];return kr.set(h,_),Reflect.ownKeys(l).forEach(H=>{const B=Object.getOwnPropertyDescriptor(l,H);B.get||B.set?Object.defineProperty(I,H,B):h[H]=l[H]}),h})=>[c,kr,Es,t,e,r,n,i,s,o,a],[Lb]=Mb();function or(t={}){return Lb(t)}function Hr(t,e,r){const n=kr.get(t);void 0!=="production"&&!n&&console.warn("Please use proxy object");let i;const s=[],o=n[3];let a=!1;const l=o(p=>{if(s.push(p),r){e(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Ub(t,e){const r=kr.get(t);void 0!=="production"&&!r&&console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}var c0={},xs={};xs.byteLength=Bb,xs.toByteArray=Hb,xs.fromByteArray=qb;for(var ar=[],Gt=[],Fb=typeof Uint8Array<"u"?Uint8Array:Array,Na="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wn=0,jb=Na.length;wn<jb;++wn)ar[wn]=Na[wn],Gt[Na.charCodeAt(wn)]=wn;Gt["-".charCodeAt(0)]=62,Gt["_".charCodeAt(0)]=63;function l0(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Bb(t){var e=l0(t),r=e[0],n=e[1];return(r+n)*3/4-n}function kb(t,e,r){return(e+r)*3/4-r}function Hb(t){var e,r=l0(t),n=r[0],i=r[1],s=new Fb(kb(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=Gt[t.charCodeAt(c)]<<18|Gt[t.charCodeAt(c+1)]<<12|Gt[t.charCodeAt(c+2)]<<6|Gt[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Gt[t.charCodeAt(c)]<<2|Gt[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Gt[t.charCodeAt(c)]<<10|Gt[t.charCodeAt(c+1)]<<4|Gt[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function zb(t){return ar[t>>18&63]+ar[t>>12&63]+ar[t>>6&63]+ar[t&63]}function Wb(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(zb(n));return i.join("")}function qb(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(Wb(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(ar[e>>2]+ar[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(ar[e>>10]+ar[e>>4&63]+ar[e<<2&63]+"=")),i.join("")}var Ra={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Ra.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,l=c>>1,p=-7,m=r?i-1:0,w=r?-1:1,y=t[e+m];for(m+=w,s=y&(1<<-p)-1,y>>=-p,p+=a;p>0;s=s*256+t[e+m],m+=w,p-=8);for(o=s&(1<<-p)-1,s>>=-p,p+=n;p>0;o=o*256+t[e+m],m+=w,p-=8);if(s===0)s=1-l;else{if(s===c)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-l}return(y?-1:1)*o*Math.pow(2,s-n)},Ra.write=function(t,e,r,n,i,s){var o,a,c,l=s*8-i-1,p=(1<<l)-1,m=p>>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:s-1,E=n?1:-1,T=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+m>=1?e+=w/c:e+=w*Math.pow(2,1-m),e*c>=2&&(o++,c/=2),o+m>=p?(a=0,o=p):o+m>=1?(a=(e*c-1)*Math.pow(2,i),o=o+m):(a=e*Math.pow(2,m-1)*Math.pow(2,i),o=0));i>=8;t[r+y]=a&255,y+=E,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;t[r+y]=o&255,y+=E,o/=256,l-=8);t[r+y-E]|=T*128};/*!
|
|
73
73
|
* The buffer module from node.js, for the browser.
|
|
74
74
|
*
|
|
75
75
|
* @author Feross Aboukhadijeh <https://feross.org>
|