Socket
Socket
Sign inDemoInstall

@metamask/sdk-communication-layer

Package Overview
Dependencies
Maintainers
12
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@metamask/sdk-communication-layer - npm Package Compare versions

Comparing version 0.17.0 to 0.18.0

7

CHANGELOG.md

@@ -9,2 +9,6 @@ # Changelog

## [0.18.0]
### Added
- feat: update prod socket server url ([#774](https://github.com/MetaMask/metamask-sdk/pull/774))
## [0.17.0]

@@ -167,3 +171,4 @@ ### Added

[Unreleased]: https://github.com/MetaMask/metamask-sdk/compare/@metamask/sdk-communication-layer@0.17.0...HEAD
[Unreleased]: https://github.com/MetaMask/metamask-sdk/compare/@metamask/sdk-communication-layer@0.18.0...HEAD
[0.18.0]: https://github.com/MetaMask/metamask-sdk/compare/@metamask/sdk-communication-layer@0.17.0...@metamask/sdk-communication-layer@0.18.0
[0.17.0]: https://github.com/MetaMask/metamask-sdk/compare/@metamask/sdk-communication-layer@0.16.0...@metamask/sdk-communication-layer@0.17.0

@@ -170,0 +175,0 @@ [0.16.0]: https://github.com/MetaMask/metamask-sdk/compare/@metamask/sdk-communication-layer@0.15.0...@metamask/sdk-communication-layer@0.16.0

2

dist/browser/es/src/config.d.ts

@@ -1,2 +0,2 @@

export declare const DEFAULT_SERVER_URL = "https://metamask-sdk-socket.metafi.codefi.network/";
export declare const DEFAULT_SERVER_URL = "https://metamask-sdk.api.cx.metamask.io/";
export declare const DEFAULT_SOCKET_TRANSPORTS: string[];

@@ -3,0 +3,0 @@ export declare const MIN_IN_MS: number;

@@ -1,2 +0,2 @@

export declare const DEFAULT_SERVER_URL = "https://metamask-sdk-socket.metafi.codefi.network/";
export declare const DEFAULT_SERVER_URL = "https://metamask-sdk.api.cx.metamask.io/";
export declare const DEFAULT_SOCKET_TRANSPORTS: string[];

@@ -3,0 +3,0 @@ export declare const MIN_IN_MS: number;

@@ -1,2 +0,2 @@

export declare const DEFAULT_SERVER_URL = "https://metamask-sdk-socket.metafi.codefi.network/";
export declare const DEFAULT_SERVER_URL = "https://metamask-sdk.api.cx.metamask.io/";
export declare const DEFAULT_SOCKET_TRANSPORTS: string[];

@@ -3,0 +3,0 @@ export declare const MIN_IN_MS: number;

@@ -1,2 +0,2 @@

"use strict";var e=require("cross-fetch"),t=require("tty"),n=require("util"),o=require("os"),s=require("buffer"),i=require("eciesjs"),a=require("eventemitter2"),r=require("uuid"),c=require("socket.io-client");function l(e,t,n,o){return new(n||(n=Promise))((function(s,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function r(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,r)}c((o=o.apply(e,t||[])).next())}))}function d(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var u,h,p,m,g,y={exports:{}},E={exports:{}};function v(){if(h)return u;h=1;var e=1e3,t=60*e,n=60*t,o=24*n,s=7*o,i=365.25*o;function a(e,t,n,o){var s=t>=1.5*n;return Math.round(e/n)+" "+o+(s?"s":"")}return u=function(r,c){c=c||{};var l=typeof r;if("string"===l&&r.length>0)return function(a){if((a=String(a)).length>100)return;var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!r)return;var c=parseFloat(r[1]);switch((r[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*o;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(r);if("number"===l&&isFinite(r))return c.long?function(s){var i=Math.abs(s);if(i>=o)return a(s,i,o,"day");if(i>=n)return a(s,i,n,"hour");if(i>=t)return a(s,i,t,"minute");if(i>=e)return a(s,i,e,"second");return s+" ms"}(r):function(s){var i=Math.abs(s);if(i>=o)return Math.round(s/o)+"d";if(i>=n)return Math.round(s/n)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))}}function C(){if(m)return p;return m=1,p=function(e){function t(e){let o,s,i,a=null;function r(...e){if(!r.enabled)return;const n=r,s=Number(new Date),i=s-(o||s);n.diff=i,n.prev=o,n.curr=s,o=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((o,s)=>{if("%%"===o)return"%";a++;const i=t.formatters[s];if("function"==typeof i){const t=e[a];o=i.call(n,t),e.splice(a,1),a--}return o})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return r.namespace=e,r.useColors=t.useColors(),r.color=t.selectColor(e),r.extend=n,r.destroy=t.destroy,Object.defineProperty(r,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{a=e}}),"function"==typeof t.init&&t.init(r),r}function n(e,n){const o=t(this.namespace+(void 0===n?":":n)+e);return o.log=this.log,o}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const o=("string"==typeof e?e:"").split(/[\s,]+/),s=o.length;for(n=0;n<s;n++)o[n]&&("-"===(e=o[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,o;for(n=0,o=t.skips.length;n<o;n++)if(t.skips[n].test(e))return!1;for(n=0,o=t.names.length;n<o;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=v(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},p}var S,x,f,k,T,K={exports:{}};function I(){return x?S:(x=1,S=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",o=t.indexOf(n+e),s=t.indexOf("--");return-1!==o&&(-1===s||o<s)})}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?y.exports=(g||(g=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let o=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(o++,"%c"===e&&(s=o))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=C()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(E,E.exports)),E.exports):y.exports=(T||(T=1,function(e,s){const i=t,a=n;s.init=function(e){e.inspectOpts={};const t=Object.keys(s.inspectOpts);for(let n=0;n<t.length;n++)e.inspectOpts[t[n]]=s.inspectOpts[t[n]]},s.log=function(...e){return process.stderr.write(a.format(...e)+"\n")},s.formatArgs=function(t){const{namespace:n,useColors:o}=this;if(o){const o=this.color,s="[3"+(o<8?o:"8;5;"+o),i=` ${s};1m${n} `;t[0]=i+t[0].split("\n").join("\n"+i),t.push(s+"m+"+e.exports.humanize(this.diff)+"")}else t[0]=(s.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+n+" "+t[0]},s.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},s.load=function(){return process.env.DEBUG},s.useColors=function(){return"colors"in s.inspectOpts?Boolean(s.inspectOpts.colors):i.isatty(process.stderr.fd)},s.destroy=a.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),s.colors=[6,2,3,4,5,1];try{const e=function(){if(k)return f;k=1;const e=o,n=t,s=I(),{env:i}=process;let a;function r(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(t,n){if(0===a)return 0;if(s("color=16m")||s("color=full")||s("color=truecolor"))return 3;if(s("color=256"))return 2;if(t&&!n&&void 0===a)return 0;const o=a||0;if("dumb"===i.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in i)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||"codeship"===i.CI_NAME?1:o;if("TEAMCITY_VERSION"in i)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0;if("truecolor"===i.COLORTERM)return 3;if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(i.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)||"COLORTERM"in i?1:o}return s("no-color")||s("no-colors")||s("color=false")||s("color=never")?a=0:(s("color")||s("colors")||s("color=true")||s("color=always"))&&(a=1),"FORCE_COLOR"in i&&(a="true"===i.FORCE_COLOR?1:"false"===i.FORCE_COLOR?0:0===i.FORCE_COLOR.length?1:Math.min(parseInt(i.FORCE_COLOR,10),3)),f={supportsColor:function(e){return r(c(e,e&&e.isTTY))},stdout:r(c(!0,n.isatty(1))),stderr:r(c(!0,n.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(s.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}s.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let o=process.env[t];return o=!!/^(yes|on|true|enabled)$/i.test(o)||!/^(no|off|false|disabled)$/i.test(o)&&("null"===o?null:Number(o)),e[n]=o,e}),{}),e.exports=C()(s);const{formatters:r}=e.exports;r.o=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},r.O=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts)}}(K,K.exports)),K.exports);var _=d(y.exports);const O=_("KeyExchange:Layer"),A=_("SocketService:Layer"),N=_("Ecies:Layer"),R=_("RemoteCommunication:Layer");O.color="##95c44e",A.color="#f638d7",N.color="#465b9c",R.color="#47a2be";const b={KeyExchange:O,SocketService:A,Ecies:N,RemoteCommunication:R};let w,M=[],D=[];function $(t){return l(this,void 0,void 0,(function*(){if(!w||!t)return;!function(){const e=D;D=M,M=e}();const n=w.endsWith("/")?`${w}debug`:`${w}/debug`,o=Object.assign({},t);if(delete o.params,t.params)for(const[e,n]of Object.entries(t.params))o[e]=n;const s=JSON.stringify(o);b.RemoteCommunication(`[sendBufferedEvents] Sending ${M.length} analytics events to ${n}`);try{const t=yield e(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:s}),o=yield t.text();b.RemoteCommunication(`[sendBufferedEvents] Response: ${o}`),M.length=0}catch(e){console.warn("Error sending analytics",e)}}))}const L=(e,t)=>l(void 0,void 0,void 0,(function*(){var n;w=t,n=e,D.push(n),$(e).catch((()=>{}))}));class P{constructor(e){this.enabled=!0,(null==e?void 0:e.debug)&&_.enable("Ecies:Layer"),(null==e?void 0:e.pkey)?this.ecies=i.PrivateKey.fromHex(e.pkey):this.ecies=new i.PrivateKey,b.Ecies("[ECIES constructor()] initialized secret: ",this.ecies.toHex()),b.Ecies("[ECIES constructor()] initialized public: ",this.ecies.publicKey.toHex()),b.Ecies("[ECIES constructor()] init with",this)}generateECIES(){this.ecies=new i.PrivateKey}getPublicKey(){return this.ecies.publicKey.toHex()}encrypt(e,t){let n=e;if(this.enabled)try{b.Ecies("[ECIES: encrypt()] using otherPublicKey",t);const o=s.Buffer.from(e),a=i.encrypt(t,o);n=s.Buffer.from(a).toString("base64")}catch(n){throw b.Ecies("[ECIES: encrypt()] error encrypt:",n),b.Ecies("[ECIES: encrypt()] private: ",this.ecies.toHex()),b.Ecies("[ECIES: encrypt()] data: ",e),b.Ecies("[ECIES: encrypt()] otherkey: ",t),n}return n}decrypt(e){let t=e;if(this.enabled)try{b.Ecies("[ECIES: decrypt()] using privateKey",this.ecies.toHex());const n=s.Buffer.from(e.toString(),"base64");t=i.decrypt(this.ecies.toHex(),n).toString()}catch(t){throw b.Ecies("[ECIES: decrypt()] error decrypt",t),b.Ecies("[ECIES: decrypt()] private: ",this.ecies.toHex()),b.Ecies("[ECIES: decrypt()] encryptedData: ",e),t}return t}getKeyInfo(){return{private:this.ecies.toHex(),public:this.ecies.publicKey.toHex()}}toString(){b.Ecies("[ECIES: toString()]",this.getKeyInfo())}}var H={name:"@metamask/sdk-communication-layer",version:"0.17.0",description:"",homepage:"https://github.com/MetaMask/metamask-sdk#readme",bugs:{url:"https://github.com/MetaMask/metamask-sdk/issues"},repository:{type:"git",url:"https://github.com/MetaMask/metamask-sdk.git",directory:"packages/sdk-communication-layer"},main:"dist/node/cjs/metamask-sdk-communication-layer.js",unpkg:"dist/browser/umd/metamask-sdk-communication-layer.js",module:"dist/node/es/metamask-sdk-communication-layer.js",browser:"dist/browser/es/metamask-sdk-communication-layer.js","react-native":"dist/react-native/es/metamask-sdk-communication-layer.js",types:"dist/browser/es/src/index.d.ts",files:["/dist"],scripts:{build:"rimraf dist && rollup -c --bundleConfigAsCjs","build:tsc":"tsc","build:dev":"rimraf dist && NODE_ENV=dev rollup -c --bundleConfigAsCjs","build:post-tsc":"echo 'N/A'","build:pre-tsc":"echo 'N/A'",size:"size-limit",clean:"rimraf ./dist",lint:"yarn lint:eslint && yarn lint:misc --check","lint:changelog":"../../scripts/validate-changelog.sh @metamask/sdk-communication-layer","lint:eslint":"eslint . --cache --ext js,ts","lint:fix":"yarn lint:eslint --fix && yarn lint:misc --write","lint:misc":"prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path ../../.gitignore","prepare-manifest:preview":"../../scripts/prepare-preview-manifest.sh","publish:preview":"yarn npm publish --tag preview",prepack:"../../scripts/prepack.sh",reset:"yarn clean && rimraf ./node_modules/",test:"jest","test:coverage":"jest --coverage","test:ci":"jest --coverage --passWithNoTests --setupFilesAfterEnv ./jest-preload.js","test:dev":"jest",watch:"rollup -c --bundleConfigAsCjs -w"},dependencies:{bufferutil:"^4.0.8","date-fns":"^2.29.3",debug:"^4.3.4","utf-8-validate":"^6.0.3",uuid:"^8.3.2"},devDependencies:{"@jest/globals":"^29.3.1","@lavamoat/allow-scripts":"^2.3.1","@metamask/auto-changelog":"3.1.0","@metamask/eslint-config":"^6.0.0","@metamask/eslint-config-nodejs":"^6.0.0","@metamask/eslint-config-typescript":"^6.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.0.2","@rollup/plugin-terser":"^0.4.1","@size-limit/preset-big-lib":"^11.0.2","@types/jest":"^29.2.4","@types/node":"^20.1.3","@types/uuid":"^9.0.0","@typescript-eslint/eslint-plugin":"^4.26.0","@typescript-eslint/parser":"^4.26.0","cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eslint:"^7.30.0","eslint-config-prettier":"^8.3.0","eslint-plugin-import":"^2.23.4","eslint-plugin-jest":"^24.4.0","eslint-plugin-jsdoc":"^36.1.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.4.0",eventemitter2:"^6.4.7",jest:"^29.3.1",prettier:"^2.3.0",rimraf:"^3.0.2",rollup:"^3.21.7","rollup-plugin-jscc":"^2.0.0","rollup-plugin-natives":"^0.7.5","rollup-plugin-node-builtins":"^2.1.2","rollup-plugin-node-globals":"^1.4.0","rollup-plugin-peer-deps-external":"^2.2.4","rollup-plugin-sizes":"^1.0.6","rollup-plugin-typescript2":"^0.31.2","rollup-plugin-visualizer":"^5.9.2","size-limit":"^11.0.2","socket.io-client":"^4.5.1","stream-browserify":"^3.0.0","ts-jest":"^29.0.3","ts-node":"^10.9.1",typescript:"^4.3.2"},peerDependencies:{"cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eventemitter2:"^6.4.7","readable-stream":"^3.6.2","socket.io-client":"^4.5.1"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},lavamoat:{allowScripts:{"@lavamoat/preinstall-always-fail":!1,canvas:!0,"eciesjs>secp256k1":!1,"socket.io-client>engine.io-client>ws>bufferutil":!1,"socket.io-client>engine.io-client>ws>utf-8-validate":!1,bufferutil:!1,"utf-8-validate":!1}}};const F="https://metamask-sdk-socket.metafi.codefi.network/",U=["websocket"],Y=6048e5,j={METAMASK_GETPROVIDERSTATE:"metamask_getProviderState",ETH_REQUESTACCOUNTS:"eth_requestAccounts"};function G(e){const{context:t}=e;b.RemoteCommunication(`[RemoteCommunication: clean()] context=${t}`),e.channelConfig=void 0,e.ready=!1,e.originatorConnectStarted=!1}var z,V,W,B,q;exports.ConnectionStatus=void 0,(z=exports.ConnectionStatus||(exports.ConnectionStatus={})).DISCONNECTED="disconnected",z.WAITING="waiting",z.TIMEOUT="timeout",z.LINKED="linked",z.PAUSED="paused",z.TERMINATED="terminated",exports.EventType=void 0,(V=exports.EventType||(exports.EventType={})).KEY_INFO="key_info",V.SERVICE_STATUS="service_status",V.PROVIDER_UPDATE="provider_update",V.RPC_UPDATE="rpc_update",V.KEYS_EXCHANGED="keys_exchanged",V.JOIN_CHANNEL="join_channel",V.CHANNEL_CREATED="channel_created",V.CLIENTS_CONNECTED="clients_connected",V.CLIENTS_DISCONNECTED="clients_disconnected",V.CLIENTS_WAITING="clients_waiting",V.CLIENTS_READY="clients_ready",V.SOCKET_DISCONNECTED="socket_disconnected",V.SOCKET_RECONNECT="socket_reconnect",V.OTP="otp",V.SDK_RPC_CALL="sdk_rpc_call",V.AUTHORIZED="authorized",V.CONNECTION_STATUS="connection_status",V.MESSAGE="message",V.TERMINATE="terminate",function(e){e.KEY_EXCHANGE="key_exchange"}(W||(W={})),exports.KeyExchangeMessageType=void 0,(B=exports.KeyExchangeMessageType||(exports.KeyExchangeMessageType={})).KEY_HANDSHAKE_START="key_handshake_start",B.KEY_HANDSHAKE_CHECK="key_handshake_check",B.KEY_HANDSHAKE_SYN="key_handshake_SYN",B.KEY_HANDSHAKE_SYNACK="key_handshake_SYNACK",B.KEY_HANDSHAKE_ACK="key_handshake_ACK",B.KEY_HANDSHAKE_NONE="none";class J extends a.EventEmitter2{constructor({communicationLayer:e,otherPublicKey:t,context:n,ecies:o,logging:s}){super(),this.keysExchanged=!1,this.step=exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE,this.debug=!1,this.context=n,this.myECIES=new P(Object.assign(Object.assign({},o),{debug:null==s?void 0:s.eciesLayer})),this.communicationLayer=e,this.myPublicKey=this.myECIES.getPublicKey(),this.debug=!0===(null==s?void 0:s.keyExchangeLayer),(null==s?void 0:s.keyExchangeLayer)&&_.enable("KeyExchange:Layer"),t&&this.setOtherPublicKey(t),this.communicationLayer.on(W.KEY_EXCHANGE,this.onKeyExchangeMessage.bind(this))}onKeyExchangeMessage(e){b.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} keysExchanged=${this.keysExchanged}`,e);const{message:t}=e;this.keysExchanged&&b.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} received handshake while already exchanged. step=${this.step} otherPubKey=${this.otherPublicKey}`),this.emit(exports.EventType.KEY_INFO,t.type),t.type===exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYN?(this.checkStep([exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE,exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK]),b.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYN",t),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK,pubkey:this.myPublicKey}),this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK)):t.type===exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK?(this.checkStep([exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK,exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK,exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE]),b.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYNACK"),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK}),this.keysExchanged=!0,this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK),this.emit(exports.EventType.KEYS_EXCHANGED)):t.type===exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK&&(b.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_ACK set keysExchanged to true!"),this.checkStep([exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK,exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE]),this.keysExchanged=!0,this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK),this.emit(exports.EventType.KEYS_EXCHANGED))}resetKeys(e){this.clean(),this.myECIES=new P(e)}clean(){b.KeyExchange(`[KeyExchange: clean()] context=${this.context} reset handshake state`),this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE),this.emit(exports.EventType.KEY_INFO,this.step),this.keysExchanged=!1}start({isOriginator:e,force:t}){b.KeyExchange(`[KeyExchange: start()] context=${this.context} isOriginator=${e} step=${this.step} force=${t} keysExchanged=${this.keysExchanged}`),e?!(this.keysExchanged||this.step!==exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE&&this.step!==exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK)||t?(b.KeyExchange(`[KeyExchange: start()] context=${this.context} -- start key exchange (force=${t}) -- step=${this.step}`,this.step),this.clean(),this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK),this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYN,pubkey:this.myPublicKey})):b.KeyExchange(`[KeyExchange: start()] context=${this.context} -- key exchange already ${this.keysExchanged?"done":"in progress"} -- aborted.`,this.step):this.keysExchanged&&!0!==t?b.KeyExchange("[KeyExchange: start()] don't send KEY_HANDSHAKE_START -- exchange already done."):(this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_START}),this.clean())}setStep(e){this.step=e,this.emit(exports.EventType.KEY_INFO,e)}checkStep(e){e.length>0&&-1===e.indexOf(this.step.toString())&&console.warn(`[KeyExchange: checkStep()] Wrong Step "${this.step}" not within ${e}`)}setKeysExchanged(e){this.keysExchanged=e}areKeysExchanged(){return this.keysExchanged}getMyPublicKey(){return this.myPublicKey}getOtherPublicKey(){return this.otherPublicKey}setOtherPublicKey(e){b.KeyExchange("[KeyExchange: setOtherPubKey()]",e),this.otherPublicKey=e}encryptMessage(e){if(!this.otherPublicKey)throw new Error("encryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.encrypt(e,this.otherPublicKey)}decryptMessage(e){if(!this.otherPublicKey)throw new Error("decryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.decrypt(e)}getKeyInfo(){return{ecies:Object.assign(Object.assign({},this.myECIES.getKeyInfo()),{otherPubKey:this.otherPublicKey}),step:this.step,keysExchanged:this.areKeysExchanged()}}toString(){const e={keyInfo:this.getKeyInfo(),keysExchanged:this.keysExchanged,step:this.step};return JSON.stringify(e)}}exports.MessageType=void 0,(q=exports.MessageType||(exports.MessageType={})).TERMINATE="terminate",q.ANSWER="answer",q.OFFER="offer",q.CANDIDATE="candidate",q.JSONRPC="jsonrpc",q.WALLET_INFO="wallet_info",q.ORIGINATOR_INFO="originator_info",q.PAUSE="pause",q.OTP="otp",q.AUTHORIZED="authorized",q.PING="ping",q.READY="ready";const Z=e=>new Promise((t=>{setTimeout(t,e)})),X=(e,t,n=200)=>l(void 0,void 0,void 0,(function*(){let o;const s=Date.now();let i=!1;for(;!i;){if(i=Date.now()-s>3e5,o=t[e],void 0!==o.elapsedTime)return o;yield Z(n)}throw new Error(`RPC ${e} timed out`)})),Q=({rpcId:e,instance:t})=>l(void 0,void 0,void 0,(function*(){for(;t.state.lastRpcId===e||void 0===t.state.lastRpcId;)yield Z(200);return t.state.lastRpcId})),ee=e=>l(void 0,void 0,void 0,(function*(){var t,n,o,s,i;return b.SocketService(`[SocketService: reconnectSocket()] instance.state.socket?.connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} trying to reconnect after socketio disconnection`,e),yield Z(200),(null===(n=e.state.socket)||void 0===n?void 0:n.connected)||(e.state.resumed=!0,null===(o=e.state.socket)||void 0===o||o.connect(),e.emit(exports.EventType.SOCKET_RECONNECT),null===(s=e.state.socket)||void 0===s||s.emit(exports.EventType.JOIN_CHANNEL,e.state.channelId,`${e.state.context}connect_again`)),yield Z(100),null===(i=e.state.socket)||void 0===i?void 0:i.connected}));function te(e){return t=>{b.SocketService(`[SocketService: handleDisconnect()] on 'disconnect' manualDisconnect=${e.state.manualDisconnect}`,t),e.state.manualDisconnect||(e.emit(exports.EventType.SOCKET_DISCONNECTED),function(e){"undefined"!=typeof window&&"undefined"!=typeof document&&(b.SocketService(`[SocketService: checkFocusAndReconnect()] hasFocus=${document.hasFocus()}`,e),document.hasFocus()?ee(e).then((t=>{b.SocketService(`SocketService::checkFocus reconnectSocket success=${t}`,e)})).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)})):window.addEventListener("focus",(()=>{ee(e).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)}))}),{once:!0}))}(e))}}const ne=[{event:"clients_connected",handler:function(e,t){return n=>l(this,void 0,void 0,(function*(){var n,o,s,i,a,r,c,l;b.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected-${t}' resumed=${e.state.resumed} clientsPaused=${e.state.clientsPaused} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()} isOriginator=${e.state.isOriginator}`),e.emit(exports.EventType.CLIENTS_CONNECTED,{isOriginator:e.state.isOriginator,keysExchanged:null===(o=e.state.keyExchange)||void 0===o?void 0:o.areKeysExchanged(),context:e.state.context}),e.state.resumed?(e.state.isOriginator||(b.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} 'clients_connected' / keysExchanged=${null===(s=e.state.keyExchange)||void 0===s?void 0:s.areKeysExchanged()} -- backward compatibility`),null===(i=e.state.keyExchange)||void 0===i||i.start({isOriginator:null!==(a=e.state.isOriginator)&&void 0!==a&&a})),e.state.resumed=!1):e.state.clientsPaused?b.SocketService("[SocketService: handleClientsConnected()] 'clients_connected' skip sending originatorInfo on pause"):e.state.isOriginator||(b.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected' / keysExchanged=${null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged()} -- backward compatibility`),null===(c=e.state.keyExchange)||void 0===c||c.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l,force:!0})),e.state.clientsConnected=!0,e.state.clientsPaused=!1}))}},{event:"channel_created",handler:function(e,t){return n=>{b.SocketService(`[SocketService: handleChannelCreated()] context=${e.state.context} on 'channel_created-${t}'`,n),e.emit(exports.EventType.CHANNEL_CREATED,n)}}},{event:"clients_disconnected",handler:function(e,t){return()=>{var n;e.state.clientsConnected=!1,b.SocketService(`[SocketService: handlesClientsDisconnected()] context=${e.state.context} on 'clients_disconnected-${t}'`),e.state.isOriginator&&!e.state.clientsPaused&&(null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.emit(exports.EventType.CLIENTS_DISCONNECTED,t)}}},{event:"message",handler:function(e,t){return({id:n,message:o,error:s})=>{var i,a,r,c,l,d,u,h,p,m,g,y,E,v,C;if(b.SocketService(`[SocketService handleMessage()] context=${e.state.context} on 'message' ${t} keysExchanged=${null===(i=e.state.keyExchange)||void 0===i?void 0:i.areKeysExchanged()}`,o),s)throw b.SocketService(`\n [SocketService handleMessage()] context=${e.state.context}::on 'message' error=${s}`),new Error(s);try{!function(e,t){if(t!==e.channelId)throw e.debug&&console.error(`Wrong id ${t} - should be ${e.channelId}`),new Error("Wrong id")}(e.state,n)}catch(e){return void console.error("ignore message --- wrong id ",o)}if(e.state.isOriginator&&(null==o?void 0:o.type)===exports.KeyExchangeMessageType.KEY_HANDSHAKE_START)return b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received HANDSHAKE_START isOriginator=${e.state.isOriginator}`,o),void(null===(a=e.state.keyExchange)||void 0===a||a.start({isOriginator:null!==(r=e.state.isOriginator)&&void 0!==r&&r,force:!0}));if((null==o?void 0:o.type)===exports.MessageType.PING)return b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' ping `),void e.emit(exports.EventType.MESSAGE,{message:{type:"ping"}});if(b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' originator=${e.state.isOriginator}, type=${null==o?void 0:o.type}, keysExchanged=${null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged()}`),null===(l=null==o?void 0:o.type)||void 0===l?void 0:l.startsWith("key_handshake"))return b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' emit KEY_EXCHANGE`,o),void e.emit(W.KEY_EXCHANGE,{message:o,context:e.state.context});if(null===(d=e.state.keyExchange)||void 0===d?void 0:d.areKeysExchanged()){if(-1!==o.toString().indexOf("type"))return console.warn("[SocketService handleMessage() ::on 'message' received non encrypted unkwown message"),void e.emit(exports.EventType.MESSAGE,o)}else{let t=!1;try{null===(u=e.state.keyExchange)||void 0===u||u.decryptMessage(o),t=!0}catch(e){}if(!t)return e.state.isOriginator?null===(p=e.state.keyExchange)||void 0===p||p.start({isOriginator:null!==(m=e.state.isOriginator)&&void 0!==m&&m}):e.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_START}),void console.warn(`Message ignored because invalid key exchange status. step=${null===(g=e.state.keyExchange)||void 0===g?void 0:g.getKeyInfo().step}`,null===(y=e.state.keyExchange)||void 0===y?void 0:y.getKeyInfo(),o);console.warn("Invalid key exchange status detected --- updating it."),null===(h=e.state.keyExchange)||void 0===h||h.setKeysExchanged(!0)}const S=null===(E=e.state.keyExchange)||void 0===E?void 0:E.decryptMessage(o),x=JSON.parse(null!=S?S:"{}");if((null==x?void 0:x.type)===exports.MessageType.PAUSE?e.state.clientsPaused=!0:e.state.clientsPaused=!1,e.state.isOriginator&&x.data){const t=x.data,n=e.state.rpcMethodTracker[t.id];if(n){const o=Date.now()-n.timestamp;b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received answer for id=${t.id} method=${n.method} responseTime=${o}`,x);const s=Object.assign(Object.assign({},n),{result:t.result,error:t.error?{code:null===(v=t.error)||void 0===v?void 0:v.code,message:null===(C=t.error)||void 0===C?void 0:C.message}:void 0,elapsedTime:o});e.state.rpcMethodTracker[t.id]=s,e.emit(exports.EventType.RPC_UPDATE,s),b.SocketService("[SocketService handleMessage()] HACK (wallet <7.3) update rpcMethodTracker",s),e.emit(exports.EventType.AUTHORIZED)}}e.emit(exports.EventType.MESSAGE,{message:x})}}},{event:"clients_waiting_to_join",handler:function(e,t){return n=>{b.SocketService(`[SocketService: handleClientsWaitingToJoin()] context=${e.state.context} on 'clients_waiting_to_join-${t}'`,n),e.emit(exports.EventType.CLIENTS_WAITING,n)}}}],oe=[{event:exports.EventType.KEY_INFO,handler:function(e){return t=>{b.SocketService("[SocketService: handleKeyInfo()] on 'KEY_INFO'",t),e.emit(exports.EventType.KEY_INFO,t)}}},{event:exports.EventType.KEYS_EXCHANGED,handler:function(e){return()=>{var t,n;b.SocketService(`[SocketService: handleKeysExchanged()] on 'keys_exchanged' keyschanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.emit(exports.EventType.KEYS_EXCHANGED,{keysExchanged:null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged(),isOriginator:e.state.isOriginator});const o={keyInfo:e.getKeyInfo()};e.emit(exports.EventType.SERVICE_STATUS,o)}}}];function se(e,t){b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} setting socket listeners for channel ${t}...`);const{socket:n}=e.state,{keyExchange:o}=e.state;e.state.setupChannelListeners&&console.warn(`[SocketService: setupChannelListener()] context=${e.state.context} socket listeners already set up for channel ${t}`),n&&e.state.isOriginator&&(e.state.debug&&(null==n||n.io.on("error",(t=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=error`,t)})),null==n||n.io.on("reconnect",(t=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect`,t)})),null==n||n.io.on("reconnect_error",(t=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_error`,t)})),null==n||n.io.on("reconnect_failed",(()=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_failed`)})),null==n||n.io.on("ping",(()=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=ping`)}))),null==n||n.on("disconnect",(t=>(b.SocketService(`[SocketService: setupChannelListener()] on 'disconnect' -- MetaMaskSDK socket disconnected '${t}' begin recovery...`),te(e)(t))))),ne.forEach((({event:o,handler:s})=>{const i=`${o}-${t}`;null==n||n.on(i,s(e,t))})),oe.forEach((({event:t,handler:n})=>{null==o||o.on(t,n(e))})),e.state.setupChannelListeners=!0}var ie;exports.TrackingEvents=void 0,(ie=exports.TrackingEvents||(exports.TrackingEvents={})).REQUEST="sdk_connect_request_started",ie.REQUEST_MOBILE="sdk_connect_request_started_mobile",ie.RECONNECT="sdk_reconnect_request_started",ie.CONNECTED="sdk_connection_established",ie.CONNECTED_MOBILE="sdk_connection_established_mobile",ie.AUTHORIZED="sdk_connection_authorized",ie.REJECTED="sdk_connection_rejected",ie.TERMINATED="sdk_connection_terminated",ie.DISCONNECTED="sdk_disconnected",ie.SDK_USE_EXTENSION="sdk_use_extension",ie.SDK_RPC_REQUEST="sdk_rpc_request",ie.SDK_EXTENSION_UTILIZED="sdk_extension_utilized",ie.SDK_USE_INAPP_BROWSER="sdk_use_inapp_browser";const ae="SDK_CONNECTION_ISSUE";var re;!function(e){e.RPC_CHECK="rpcCheck",e.SKIPPED_RPC="skippedRpc"}(re||(re={}));const ce=["eth_sendTransaction","eth_signTypedData","eth_signTransaction","wallet_requestPermissions","wallet_switchEthereumChain","eth_signTypedData_v3","eth_signTypedData_v4","metamask_connectSign","metamask_connectWith","metamask_batch"].map((e=>e.toLowerCase()));function le(e,t){var n,o,s,i;if(!e.state.channelId)throw new Error("Create a channel first");b.SocketService(`[SocketService: handleSendMessage()] context=${e.state.context} areKeysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`,t);(null===(o=null==t?void 0:t.type)||void 0===o?void 0:o.startsWith("key_handshake"))?function(e,t){var n;b.SocketService(`[SocketService: handleKeyHandshake()] context=${e.state.context}`,t),null===(n=e.state.socket)||void 0===n||n.emit(exports.EventType.MESSAGE,{id:e.state.channelId,context:e.state.context,message:t})}(e,t):(!function(e,t){var n;if(!(null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()))throw b.SocketService(`[SocketService: validateKeyExchange()] context=${e.state.context} ERROR keys not exchanged`,t),new Error("Keys not exchanged BBB")}(e,t),function(e,t){var n;const o=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"",s=null==t?void 0:t.id;e.state.isOriginator&&s&&(e.state.rpcMethodTracker[s]={id:s,timestamp:Date.now(),method:o},e.emit(exports.EventType.RPC_UPDATE,e.state.rpcMethodTracker[s]))}(e,t),function(e,t){var n,o;const s=null===(n=e.state.keyExchange)||void 0===n?void 0:n.encryptMessage(JSON.stringify(t)),i={id:e.state.channelId,context:e.state.context,message:s,plaintext:e.state.hasPlaintext?JSON.stringify(t):void 0};b.SocketService(`[SocketService: encryptAndSendMessage()] context=${e.state.context}`,i),t.type===exports.MessageType.TERMINATE&&(e.state.manualDisconnect=!0),null===(o=e.state.socket)||void 0===o||o.emit(exports.EventType.MESSAGE,i)}(e,t),e.remote.state.analytics&&t.method&&ce.includes(t.method.toLowerCase())&&L({id:null!==(s=e.remote.state.channelId)&&void 0!==s?s:"",event:exports.TrackingEvents.SDK_RPC_REQUEST,sdkVersion:e.remote.state.sdkVersion,commLayerVersion:H.version,walletVersion:null===(i=e.remote.state.walletInfo)||void 0===i?void 0:i.version,params:{method:t.method,from:"mobile"}},e.remote.state.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),function(e,t){var n;return l(this,void 0,void 0,(function*(){const o=null==t?void 0:t.id,s=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"";if(e.state.isOriginator&&o)try{const n=X(o,e.state.rpcMethodTracker,200).then((e=>({type:re.RPC_CHECK,result:e}))),i=(()=>l(this,void 0,void 0,(function*(){const t=yield Q({instance:e,rpcId:o}),n=yield X(t,e.state.rpcMethodTracker,200);return{type:re.SKIPPED_RPC,result:n}})))(),a=yield Promise.race([n,i]);if(a.type===re.RPC_CHECK){const e=a.result;b.SocketService(`[SocketService:handleRpcReplies()] id=${t.id} ${s} ( ${e.elapsedTime} ms)`,e.result)}else{if(a.type!==re.SKIPPED_RPC)throw new Error(`Error handling RPC replies for ${o}`);{const{result:t}=a;console.warn(`[SocketService handleRpcReplies()] RPC METHOD HAS BEEN SKIPPED rpcid=${o} method=${s}`,t);const n=Object.assign(Object.assign({},e.state.rpcMethodTracker[o]),{error:new Error(ae)});e.emit(exports.EventType.RPC_UPDATE,n);const i={data:Object.assign(Object.assign({},n),{jsonrpc:"2.0"}),name:"metamask-provider"};e.emit(exports.EventType.MESSAGE,{message:i})}}}catch(e){throw console.warn(`[SocketService handleRpcReplies()] Error rpcId=${t.id} ${s}`,e),e}}))}(e,t).catch((e=>{console.warn("Error handleRpcReplies",e)})))}class de extends a.EventEmitter2{constructor({otherPublicKey:e,reconnect:t,communicationLayerPreference:n,transports:o,communicationServerUrl:s,context:i,ecies:a,remote:r,logging:l}){super(),this.state={clientsConnected:!1,clientsPaused:!1,manualDisconnect:!1,lastRpcId:void 0,rpcMethodTracker:{},hasPlaintext:!1,communicationServerUrl:""},this.state.resumed=t,this.state.context=i,this.state.communicationLayerPreference=n,this.state.debug=!0===(null==l?void 0:l.serviceLayer),this.remote=r,!0===(null==l?void 0:l.serviceLayer)&&_.enable("SocketService:Layer"),this.state.communicationServerUrl=s,this.state.hasPlaintext=this.state.communicationServerUrl!==F&&!0===(null==l?void 0:l.plaintext);const d={autoConnect:!1,transports:U,withCredentials:!0};o&&(d.transports=o),b.SocketService(`[SocketService: constructor()] Socket IO url: ${this.state.communicationServerUrl}`),this.state.socket=c.io(s,d);const u={communicationLayer:this,otherPublicKey:e,sendPublicKey:!1,context:this.state.context,ecies:a,logging:l};this.state.keyExchange=new J(u)}resetKeys(){return e=this,b.SocketService("[SocketService: resetKeys()] Resetting keys."),void(null===(t=e.state.keyExchange)||void 0===t||t.resetKeys());var e,t}createChannel(){return function(e){var t,n,o,s;b.SocketService(`[SocketService: createChannel()] context=${e.state.context}`),(null===(t=e.state.socket)||void 0===t?void 0:t.connected)||null===(n=e.state.socket)||void 0===n||n.connect(),e.state.manualDisconnect=!1,e.state.isOriginator=!0;const i=r.v4();return e.state.channelId=i,se(e,i),null===(o=e.state.socket)||void 0===o||o.emit(exports.EventType.JOIN_CHANNEL,i,`${e.state.context}createChannel`),{channelId:i,pubKey:(null===(s=e.state.keyExchange)||void 0===s?void 0:s.getMyPublicKey())||""}}(this)}connectToChannel({channelId:e,isOriginator:t=!1,withKeyExchange:n=!1}){return function({options:e,instance:t}){var n,o,s,i;const{channelId:a,withKeyExchange:r,isOriginator:c}=e;if(b.SocketService(`[SocketService: connectToChannel()] context=${t.state.context} channelId=${a} isOriginator=${c}`,null===(n=t.state.keyExchange)||void 0===n?void 0:n.toString()),null===(o=t.state.socket)||void 0===o?void 0:o.connected)throw new Error("socket already connected");t.state.manualDisconnect=!1,null===(s=t.state.socket)||void 0===s||s.connect(),t.state.withKeyExchange=r,t.state.isOriginator=c,t.state.channelId=a,se(t,a),null===(i=t.state.socket)||void 0===i||i.emit(exports.EventType.JOIN_CHANNEL,a,`${t.state.context}_connectToChannel`)}({options:{channelId:e,isOriginator:t,withKeyExchange:n},instance:this})}getKeyInfo(){return this.state.keyExchange.getKeyInfo()}keyCheck(){var e,t;null===(t=(e=this).state.socket)||void 0===t||t.emit(exports.EventType.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_CHECK,pubkey:e.getKeyInfo().ecies.otherPubKey}})}getKeyExchange(){return this.state.keyExchange}sendMessage(e){return le(this,e)}ping(){return e=this,b.SocketService(`[SocketService: ping()] context=${e.state.context} originator=${e.state.isOriginator} keysExchanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.state.isOriginator&&((null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged())?(console.warn(`[SocketService:ping()] context=${e.state.context} sending READY message`),e.sendMessage({type:exports.MessageType.READY})):(console.warn(`[SocketService: ping()] context=${e.state.context} starting key exchange`),null===(o=e.state.keyExchange)||void 0===o||o.start({isOriginator:null!==(s=e.state.isOriginator)&&void 0!==s&&s}))),void(null===(i=e.state.socket)||void 0===i||i.emit(exports.EventType.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:exports.MessageType.PING}}));var e,t,n,o,s,i}pause(){return e=this,b.SocketService(`[SocketService: pause()] context=${e.state.context}`),e.state.manualDisconnect=!0,(null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged())&&e.sendMessage({type:exports.MessageType.PAUSE}),void(null===(n=e.state.socket)||void 0===n||n.disconnect());var e,t,n}isConnected(){var e;return null===(e=this.state.socket)||void 0===e?void 0:e.connected}resume(){return e=this,b.SocketService(`[SocketService: resume()] context=${e.state.context} connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} manualDisconnect=${e.state.manualDisconnect} resumed=${e.state.resumed} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`),(null===(o=e.state.socket)||void 0===o?void 0:o.connected)?b.SocketService("[SocketService: resume()] already connected."):(null===(s=e.state.socket)||void 0===s||s.connect(),b.SocketService(`[SocketService: resume()] after connecting socket --\x3e connected=${null===(i=e.state.socket)||void 0===i?void 0:i.connected}`),null===(a=e.state.socket)||void 0===a||a.emit(exports.EventType.JOIN_CHANNEL,e.state.channelId,`${e.state.context}_resume`)),(null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged())?e.state.isOriginator||e.sendMessage({type:exports.MessageType.READY}):e.state.isOriginator||null===(c=e.state.keyExchange)||void 0===c||c.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l}),e.state.manualDisconnect=!1,void(e.state.resumed=!0);var e,t,n,o,s,i,a,r,c,l}getRPCMethodTracker(){return this.state.rpcMethodTracker}disconnect(e){return function(e,t){var n,o;b.SocketService(`[SocketService: disconnect()] context=${e.state.context}`,t),(null==t?void 0:t.terminate)&&(e.state.channelId=t.channelId,null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.state.rpcMethodTracker={},e.state.manualDisconnect=!0,null===(o=e.state.socket)||void 0===o||o.disconnect()}(this,e)}}var ue,he;function pe(e){return()=>l(this,void 0,void 0,(function*(){var t,n,o;const{state:s}=e;if(s.authorized)return;yield(()=>l(this,void 0,void 0,(function*(){for(;!s.walletInfo;)yield Z(500)})))();const i="7.3".localeCompare((null===(t=s.walletInfo)||void 0===t?void 0:t.version)||"");if(b.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' version=${null===(n=s.walletInfo)||void 0===n?void 0:n.version} compareValue=${i}`),1!==i)return;const a=s.platformType===exports.PlatformType.MobileWeb||s.platformType===exports.PlatformType.ReactNative||s.platformType===exports.PlatformType.MetaMaskMobileWebview;b.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' platform=${s.platformType} secure=${a} channel=${s.channelId} walletVersion=${null===(o=s.walletInfo)||void 0===o?void 0:o.version}`),a&&(s.authorized=!0,e.emit(exports.EventType.AUTHORIZED))}))}function me(e){return t=>{const{state:n}=e;b.RemoteCommunication(`[RemoteCommunication: handleChannelCreatedEvent()] context=${n.context} on 'channel_created' channelId=${t}`),e.emit(exports.EventType.CHANNEL_CREATED,t)}}function ge(e,t){return()=>{var n,o,s,i;const{state:a}=e;if(b.RemoteCommunication(`[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=${a.channelId} keysExchanged=${null===(o=null===(n=a.communicationLayer)||void 0===n?void 0:n.getKeyInfo())||void 0===o?void 0:o.keysExchanged}`),a.analytics){const e=a.isOriginator?exports.TrackingEvents.REQUEST:exports.TrackingEvents.REQUEST_MOBILE;L(Object.assign(Object.assign({id:null!==(s=a.channelId)&&void 0!==s?s:"",event:a.reconnection?exports.TrackingEvents.RECONNECT:e},a.originatorInfo),{commLayer:t,sdkVersion:a.sdkVersion,walletVersion:null===(i=a.walletInfo)||void 0===i?void 0:i.version,commLayerVersion:H.version}),a.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}a.clientsConnected=!0,a.originatorInfoSent=!1,e.emit(exports.EventType.CLIENTS_CONNECTED)}}function ye(e,t){return n=>{var o;const{state:s}=e;b.RemoteCommunication(`[RemoteCommunication: handleClientsDisconnectedEvent()] context=${s.context} on 'clients_disconnected' channelId=${n}`),s.clientsConnected=!1,e.emit(exports.EventType.CLIENTS_DISCONNECTED,s.channelId),e.setConnectionStatus(exports.ConnectionStatus.DISCONNECTED),s.ready=!1,s.authorized=!1,s.analytics&&s.channelId&&L({id:s.channelId,event:exports.TrackingEvents.DISCONNECTED,sdkVersion:s.sdkVersion,commLayer:t,commLayerVersion:H.version,walletVersion:null===(o=s.walletInfo)||void 0===o?void 0:o.version},s.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}}function Ee(e){return t=>{var n;const{state:o}=e;if(b.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] context=${o.context} on 'clients_waiting' numberUsers=${t} ready=${o.ready} autoStarted=${o.originatorConnectStarted}`),e.setConnectionStatus(exports.ConnectionStatus.WAITING),e.emit(exports.EventType.CLIENTS_WAITING,t),o.originatorConnectStarted){b.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] on 'clients_waiting' watch autoStarted=${o.originatorConnectStarted} timeout`,o.autoConnectOptions);const t=(null===(n=o.autoConnectOptions)||void 0===n?void 0:n.timeout)||3e3,s=setTimeout((()=>{b.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] setTimeout(${t}) terminate channelConfig`,o.autoConnectOptions),o.originatorConnectStarted=!1,o.ready||e.setConnectionStatus(exports.ConnectionStatus.TIMEOUT),clearTimeout(s)}),t)}}}function ve(e,t){return n=>{var o,s,i,a,r;const{state:c}=e;b.RemoteCommunication(`[RemoteCommunication: handleKeysExchangedEvent()] context=${c.context} on commLayer.'keys_exchanged' channel=${c.channelId}`,n),(null===(s=null===(o=c.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===s?void 0:s.keysExchanged)&&e.setConnectionStatus(exports.ConnectionStatus.LINKED),function(e,t){var n,o,s,i;const{state:a}=e;b.RemoteCommunication(`[RemoteCommunication: setLastActiveDate()] channel=${a.channelId}`,t);const r={channelId:null!==(n=a.channelId)&&void 0!==n?n:"",validUntil:null!==(s=null===(o=a.channelConfig)||void 0===o?void 0:o.validUntil)&&void 0!==s?s:0,lastActive:t.getTime()};null===(i=a.storageManager)||void 0===i||i.persistChannelConfig(r)}(e,new Date),c.analytics&&c.channelId&&L({id:c.channelId,event:n.isOriginator?exports.TrackingEvents.CONNECTED:exports.TrackingEvents.CONNECTED_MOBILE,sdkVersion:c.sdkVersion,commLayer:t,commLayerVersion:H.version,walletVersion:null===(i=c.walletInfo)||void 0===i?void 0:i.version},c.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),c.isOriginator=n.isOriginator,n.isOriginator||(null===(a=c.communicationLayer)||void 0===a||a.sendMessage({type:exports.MessageType.READY}),c.ready=!0,c.paused=!1),n.isOriginator&&!c.originatorInfoSent&&(null===(r=c.communicationLayer)||void 0===r||r.sendMessage({type:exports.MessageType.ORIGINATOR_INFO,originatorInfo:c.originatorInfo,originator:c.originatorInfo}),c.originatorInfoSent=!0)}}function Ce(e,t){const{state:n}=t;if(b.RemoteCommunication(`[RemoteCommunication: onCommunicationLayerMessage()] context=${n.context} on 'message' typeof=${typeof e}`,e),t.state.ready=!0,n.isOriginator||e.type!==exports.MessageType.ORIGINATOR_INFO)if(n.isOriginator&&e.type===exports.MessageType.WALLET_INFO)!function(e,t){const{state:n}=e;n.walletInfo=t.walletInfo,n.paused=!1}(t,e);else{if(e.type===exports.MessageType.TERMINATE)!function(e){const{state:t}=e;t.isOriginator&&(Te({options:{terminate:!0,sendMessage:!1},instance:e}),console.debug(),e.emit(exports.EventType.TERMINATE))}(t);else if(e.type===exports.MessageType.PAUSE)!function(e){const{state:t}=e;t.paused=!0,e.setConnectionStatus(exports.ConnectionStatus.PAUSED)}(t);else if(e.type===exports.MessageType.READY&&n.isOriginator)!function(e){const{state:t}=e;e.setConnectionStatus(exports.ConnectionStatus.LINKED);const n=t.paused;t.paused=!1,e.emit(exports.EventType.CLIENTS_READY,{isOriginator:t.isOriginator,walletInfo:t.walletInfo}),n&&(t.authorized=!0,e.emit(exports.EventType.AUTHORIZED))}(t);else{if(e.type===exports.MessageType.OTP&&n.isOriginator)return void function(e,t){var n;const{state:o}=e;e.emit(exports.EventType.OTP,t.otpAnswer),1==="6.6".localeCompare((null===(n=o.walletInfo)||void 0===n?void 0:n.version)||"")&&(console.warn("RemoteCommunication::on 'otp' -- backward compatibility <6.6 -- triger eth_requestAccounts"),e.emit(exports.EventType.SDK_RPC_CALL,{method:j.ETH_REQUESTACCOUNTS,params:[]}))}(t,e);e.type===exports.MessageType.AUTHORIZED&&n.isOriginator&&function(e){const{state:t}=e;t.authorized=!0,e.emit(exports.EventType.AUTHORIZED)}(t)}t.emit(exports.EventType.MESSAGE,e)}else!function(e,t){var n;const{state:o}=e;null===(n=o.communicationLayer)||void 0===n||n.sendMessage({type:exports.MessageType.WALLET_INFO,walletInfo:o.walletInfo}),o.originatorInfo=t.originatorInfo||t.originator,e.emit(exports.EventType.CLIENTS_READY,{isOriginator:o.isOriginator,originatorInfo:o.originatorInfo}),o.paused=!1}(t,e)}function Se(e,t){var n,o;return l(this,void 0,void 0,(function*(){const{state:s}=e;b.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${s.context} paused=${s.paused} ready=${s.ready} authorized=${s.authorized} socket=${null===(n=s.communicationLayer)||void 0===n?void 0:n.isConnected()} clientsConnected=${s.clientsConnected} status=${s._connectionStatus}`,t),!s.paused&&s.ready&&(null===(o=s.communicationLayer)||void 0===o?void 0:o.isConnected())&&s.clientsConnected||(b.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${s.context} SKIP message waiting for MM mobile readiness.`),yield new Promise((t=>{e.once(exports.EventType.CLIENTS_READY,t)})),b.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${s.context} AFTER SKIP / READY -- sending pending message`));try{yield function(e,t){return l(this,void 0,void 0,(function*(){return new Promise((n=>{var o,s,i,a;const{state:r}=e;if(b.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${r.context} ready=${r.ready} authorized=${r.authorized} method=${t.method}`),1==="7.3".localeCompare((null===(o=r.walletInfo)||void 0===o?void 0:o.version)||""))return b.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] compatibility hack wallet version > ${null===(s=r.walletInfo)||void 0===s?void 0:s.version}`),null===(i=r.communicationLayer)||void 0===i||i.sendMessage(t),void n();!r.isOriginator||r.authorized?(null===(a=r.communicationLayer)||void 0===a||a.sendMessage(t),n()):e.once(exports.EventType.AUTHORIZED,(()=>{var e;b.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${r.context} AFTER SKIP / AUTHORIZED -- sending pending message`),null===(e=r.communicationLayer)||void 0===e||e.sendMessage(t),n()}))}))}))}(e,t)}catch(e){throw console.error(`[RemoteCommunication: sendMessage()] context=${s.context} ERROR`,e),e}}))}function xe(e){return t=>{let n=t;t.message&&(n=n.message),Ce(n,e)}}function fe(e){return()=>{const{state:t}=e;b.RemoteCommunication("[RemoteCommunication: handleSocketReconnectEvent()] on 'socket_reconnect' -- reset key exchange status / set ready to false"),t.ready=!1,t.authorized=!1,G(t),e.emitServiceStatusEvent()}}function ke(e){return()=>{const{state:t}=e;b.RemoteCommunication("[RemoteCommunication: handleSocketDisconnectedEvent()] on 'socket_Disconnected' set ready to false"),t.ready=!1}}function Te({options:e,instance:t}){var n,o,s,i,a,c;const{state:l}=t;b.RemoteCommunication(`[RemoteCommunication: disconnect()] channel=${l.channelId}`,e),l.ready=!1,l.paused=!1,(null==e?void 0:e.terminate)?(null===(n=l.storageManager)||void 0===n||n.terminate(null!==(o=l.channelId)&&void 0!==o?o:""),(null===(s=l.communicationLayer)||void 0===s?void 0:s.getKeyInfo().keysExchanged)&&(null==e?void 0:e.sendMessage)&&(null===(i=l.communicationLayer)||void 0===i||i.sendMessage({type:exports.MessageType.TERMINATE})),l.channelId=r.v4(),e.channelId=l.channelId,l.channelConfig=void 0,l.originatorConnectStarted=!1,null===(a=l.communicationLayer)||void 0===a||a.disconnect(e),t.setConnectionStatus(exports.ConnectionStatus.TERMINATED)):(null===(c=l.communicationLayer)||void 0===c||c.disconnect(e),t.setConnectionStatus(exports.ConnectionStatus.DISCONNECTED))}exports.CommunicationLayerPreference=void 0,(exports.CommunicationLayerPreference||(exports.CommunicationLayerPreference={})).SOCKET="socket",exports.PlatformType=void 0,(ue=exports.PlatformType||(exports.PlatformType={})).NonBrowser="nodejs",ue.MetaMaskMobileWebview="in-app-browser",ue.DesktopWeb="web-desktop",ue.MobileWeb="web-mobile",ue.ReactNative="react-native";class Ke extends a.EventEmitter2{constructor({platformType:e,communicationLayerPreference:t,otherPublicKey:n,reconnect:o,walletInfo:s,dappMetadata:i,transports:a,context:r,ecies:c,analytics:l=!1,storage:d,sdkVersion:u,communicationServerUrl:h=F,logging:p,autoConnect:m={timeout:3e3}}){super(),this.state={ready:!1,authorized:!1,isOriginator:!1,paused:!1,platformType:"metamask-mobile",analytics:!1,reconnection:!1,originatorInfoSent:!1,communicationServerUrl:F,context:"",clientsConnected:!1,sessionDuration:Y,originatorConnectStarted:!1,debug:!1,_connectionStatus:exports.ConnectionStatus.DISCONNECTED},this.state.otherPublicKey=n,this.state.dappMetadata=i,this.state.walletInfo=s,this.state.transports=a,this.state.platformType=e,this.state.analytics=l,this.state.isOriginator=!n,this.state.communicationServerUrl=h,this.state.context=r,this.state.sdkVersion=u,this.setMaxListeners(50),this.setConnectionStatus(exports.ConnectionStatus.DISCONNECTED),(null==d?void 0:d.duration)&&(this.state.sessionDuration=Y),this.state.storageOptions=d,this.state.autoConnectOptions=m,this.state.debug=!0===(null==p?void 0:p.remoteLayer),!0===(null==p?void 0:p.remoteLayer)&&_.enable("RemoteCommunication:Layer"),this.state.logging=p,(null==d?void 0:d.storageManager)&&(this.state.storageManager=d.storageManager),this.initCommunicationLayer({communicationLayerPreference:t,otherPublicKey:n,reconnect:o,ecies:c,communicationServerUrl:h}),this.emitServiceStatusEvent()}initCommunicationLayer({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:s=F}){return function({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:s=F,instance:i}){var a,r,c,l,d;const{state:u}=i;if(e!==exports.CommunicationLayerPreference.SOCKET)throw new Error("Invalid communication protocol");u.communicationLayer=new de({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,transports:u.transports,communicationServerUrl:s,context:u.context,ecies:o,logging:u.logging,remote:i});let h="undefined"!=typeof document&&document.URL||"",p="undefined"!=typeof document&&document.title||"";(null===(a=u.dappMetadata)||void 0===a?void 0:a.url)&&(h=u.dappMetadata.url),(null===(r=u.dappMetadata)||void 0===r?void 0:r.name)&&(p=u.dappMetadata.name);const m={url:h,title:p,source:null===(c=u.dappMetadata)||void 0===c?void 0:c.source,icon:(null===(l=u.dappMetadata)||void 0===l?void 0:l.iconUrl)||(null===(d=u.dappMetadata)||void 0===d?void 0:d.base64Icon),platform:u.platformType,apiVersion:H.version};u.originatorInfo=m;const g={[exports.EventType.AUTHORIZED]:pe(i),[exports.EventType.MESSAGE]:xe(i),[exports.EventType.CLIENTS_CONNECTED]:ge(i,e),[exports.EventType.KEYS_EXCHANGED]:ve(i,e),[exports.EventType.SOCKET_DISCONNECTED]:ke(i),[exports.EventType.SOCKET_RECONNECT]:fe(i),[exports.EventType.CLIENTS_DISCONNECTED]:ye(i,e),[exports.EventType.KEY_INFO]:()=>{i.emitServiceStatusEvent()},[exports.EventType.CHANNEL_CREATED]:me(i),[exports.EventType.CLIENTS_WAITING]:Ee(i),[exports.EventType.RPC_UPDATE]:e=>{i.emit(exports.EventType.RPC_UPDATE,e)}};for(const[e,t]of Object.entries(g))try{u.communicationLayer.on(e,t)}catch(t){console.error(`Error registering handler for ${e}:`,t)}}({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:s,instance:this})}originatorSessionConnect(){return l(this,void 0,void 0,(function*(){return yield function(e){var t,n,o;return l(this,void 0,void 0,(function*(){const{state:s}=e;if(!s.storageManager)return void b.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] no storage manager defined - skip");const i=yield s.storageManager.getPersistedChannelConfig(null!==(t=s.channelId)&&void 0!==t?t:"");if(b.RemoteCommunication(`[RemoteCommunication: originatorSessionConnect()] autoStarted=${s.originatorConnectStarted} channelConfig`,i),null===(n=s.communicationLayer)||void 0===n?void 0:n.isConnected())return b.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] socket already connected - skip"),i;if(i){if(i.validUntil>Date.now())return s.channelConfig=i,s.originatorConnectStarted=!0,s.channelId=null==i?void 0:i.channelId,s.reconnection=!0,null===(o=s.communicationLayer)||void 0===o||o.connectToChannel({channelId:i.channelId,isOriginator:!0}),i;b.RemoteCommunication("[RemoteCommunication: autoConnect()] Session has expired")}s.originatorConnectStarted=!1}))}(this)}))}generateChannelIdConnect(){return l(this,void 0,void 0,(function*(){return function(e){var t,n,o,s,i;if(!e.communicationLayer)throw new Error("communication layer not initialized");if(e.ready)throw new Error("Channel already connected");if(e.channelId&&(null===(t=e.communicationLayer)||void 0===t?void 0:t.isConnected()))return console.warn("Channel already exists -- interrupt generateChannelId",e.channelConfig),e.channelConfig={channelId:e.channelId,validUntil:Date.now()+e.sessionDuration},null===(n=e.storageManager)||void 0===n||n.persistChannelConfig(e.channelConfig),{channelId:e.channelId,pubKey:null===(s=null===(o=e.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===s?void 0:s.ecies.public};b.RemoteCommunication("[RemoteCommunication: generateChannelId()]"),G(e);const a=e.communicationLayer.createChannel();b.RemoteCommunication("[RemoteCommunication: generateChannelId()] channel created",a);const r={channelId:a.channelId,validUntil:Date.now()+e.sessionDuration};return e.channelId=a.channelId,e.channelConfig=r,null===(i=e.storageManager)||void 0===i||i.persistChannelConfig(r),{channelId:e.channelId,pubKey:a.pubKey}}(this.state)}))}clean(){return G(this.state)}connectToChannel(e,t){return function({channelId:e,withKeyExchange:t,state:n}){var o,s,i;if(!r.validate(e))throw b.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} invalid channel channelId=${e}`),new Error(`Invalid channel ${e}`);if(b.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} channelId=${e}`),null===(o=n.communicationLayer)||void 0===o?void 0:o.isConnected())return void b.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} already connected - interrupt connection.`);n.channelId=e,null===(s=n.communicationLayer)||void 0===s||s.connectToChannel({channelId:e,withKeyExchange:t});const a={channelId:e,validUntil:Date.now()+n.sessionDuration};n.channelConfig=a,null===(i=n.storageManager)||void 0===i||i.persistChannelConfig(a)}({channelId:e,withKeyExchange:t,state:this.state})}sendMessage(e){return Se(this,e)}testStorage(){return l(this,void 0,void 0,(function*(){return function(e){var t,n;return l(this,void 0,void 0,(function*(){const o=yield null===(t=e.storageManager)||void 0===t?void 0:t.getPersistedChannelConfig(null!==(n=e.channelId)&&void 0!==n?n:"");b.RemoteCommunication("[RemoteCommunication: testStorage()] res",o)}))}(this.state)}))}getChannelConfig(){return this.state.channelConfig}isReady(){return this.state.ready}isConnected(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.isConnected()}isAuthorized(){return this.state.authorized}isPaused(){return this.state.paused}getCommunicationLayer(){return this.state.communicationLayer}ping(){var e;b.RemoteCommunication(`[RemoteCommunication: ping()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.ping()}keyCheck(){var e;b.RemoteCommunication(`[RemoteCommunication: keyCheck()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.keyCheck()}setConnectionStatus(e){this.state._connectionStatus!==e&&(this.state._connectionStatus=e,this.emit(exports.EventType.CONNECTION_STATUS,e),this.emitServiceStatusEvent())}emitServiceStatusEvent(){this.emit(exports.EventType.SERVICE_STATUS,this.getServiceStatus())}getConnectionStatus(){return this.state._connectionStatus}getServiceStatus(){return{originatorInfo:this.state.originatorInfo,keyInfo:this.getKeyInfo(),connectionStatus:this.state._connectionStatus,channelConfig:this.state.channelConfig,channelId:this.state.channelId}}getKeyInfo(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getKeyInfo()}resetKeys(){var e;null===(e=this.state.communicationLayer)||void 0===e||e.resetKeys()}setOtherPublicKey(e){var t;const n=null===(t=this.state.communicationLayer)||void 0===t?void 0:t.getKeyExchange();if(!n)throw new Error("KeyExchange is not initialized.");n.getOtherPublicKey()!==e&&n.setOtherPublicKey(e)}pause(){var e;b.RemoteCommunication(`[RemoteCommunication: pause()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.pause(),this.setConnectionStatus(exports.ConnectionStatus.PAUSED)}getVersion(){return H.version}resume(){return function(e){var t;const{state:n}=e;b.RemoteCommunication(`[RemoteCommunication: resume()] channel=${n.channelId}`),null===(t=n.communicationLayer)||void 0===t||t.resume(),e.setConnectionStatus(exports.ConnectionStatus.LINKED)}(this)}getChannelId(){return this.state.channelId}getRPCMethodTracker(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getRPCMethodTracker()}disconnect(e){return Te({options:e,instance:this})}}exports.AutoConnectType=void 0,(he=exports.AutoConnectType||(exports.AutoConnectType={})).RENEW="renew",he.LINK="link",exports.DEFAULT_SERVER_URL=F,exports.ECIES=P,exports.RemoteCommunication=Ke,exports.SendAnalytics=L,exports.SocketService=de;
"use strict";var e=require("cross-fetch"),t=require("tty"),n=require("util"),o=require("os"),s=require("buffer"),i=require("eciesjs"),a=require("eventemitter2"),r=require("uuid"),c=require("socket.io-client");function l(e,t,n,o){return new(n||(n=Promise))((function(s,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function r(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,r)}c((o=o.apply(e,t||[])).next())}))}function d(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var u,h,p,m,g,y={exports:{}},E={exports:{}};function v(){if(h)return u;h=1;var e=1e3,t=60*e,n=60*t,o=24*n,s=7*o,i=365.25*o;function a(e,t,n,o){var s=t>=1.5*n;return Math.round(e/n)+" "+o+(s?"s":"")}return u=function(r,c){c=c||{};var l=typeof r;if("string"===l&&r.length>0)return function(a){if((a=String(a)).length>100)return;var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!r)return;var c=parseFloat(r[1]);switch((r[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*o;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(r);if("number"===l&&isFinite(r))return c.long?function(s){var i=Math.abs(s);if(i>=o)return a(s,i,o,"day");if(i>=n)return a(s,i,n,"hour");if(i>=t)return a(s,i,t,"minute");if(i>=e)return a(s,i,e,"second");return s+" ms"}(r):function(s){var i=Math.abs(s);if(i>=o)return Math.round(s/o)+"d";if(i>=n)return Math.round(s/n)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))}}function C(){if(m)return p;return m=1,p=function(e){function t(e){let o,s,i,a=null;function r(...e){if(!r.enabled)return;const n=r,s=Number(new Date),i=s-(o||s);n.diff=i,n.prev=o,n.curr=s,o=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((o,s)=>{if("%%"===o)return"%";a++;const i=t.formatters[s];if("function"==typeof i){const t=e[a];o=i.call(n,t),e.splice(a,1),a--}return o})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return r.namespace=e,r.useColors=t.useColors(),r.color=t.selectColor(e),r.extend=n,r.destroy=t.destroy,Object.defineProperty(r,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{a=e}}),"function"==typeof t.init&&t.init(r),r}function n(e,n){const o=t(this.namespace+(void 0===n?":":n)+e);return o.log=this.log,o}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const o=("string"==typeof e?e:"").split(/[\s,]+/),s=o.length;for(n=0;n<s;n++)o[n]&&("-"===(e=o[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,o;for(n=0,o=t.skips.length;n<o;n++)if(t.skips[n].test(e))return!1;for(n=0,o=t.names.length;n<o;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=v(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},p}var S,x,f,k,T,K={exports:{}};function I(){return x?S:(x=1,S=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",o=t.indexOf(n+e),s=t.indexOf("--");return-1!==o&&(-1===s||o<s)})}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?y.exports=(g||(g=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let o=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(o++,"%c"===e&&(s=o))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=C()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(E,E.exports)),E.exports):y.exports=(T||(T=1,function(e,s){const i=t,a=n;s.init=function(e){e.inspectOpts={};const t=Object.keys(s.inspectOpts);for(let n=0;n<t.length;n++)e.inspectOpts[t[n]]=s.inspectOpts[t[n]]},s.log=function(...e){return process.stderr.write(a.format(...e)+"\n")},s.formatArgs=function(t){const{namespace:n,useColors:o}=this;if(o){const o=this.color,s="[3"+(o<8?o:"8;5;"+o),i=` ${s};1m${n} `;t[0]=i+t[0].split("\n").join("\n"+i),t.push(s+"m+"+e.exports.humanize(this.diff)+"")}else t[0]=(s.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+n+" "+t[0]},s.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},s.load=function(){return process.env.DEBUG},s.useColors=function(){return"colors"in s.inspectOpts?Boolean(s.inspectOpts.colors):i.isatty(process.stderr.fd)},s.destroy=a.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),s.colors=[6,2,3,4,5,1];try{const e=function(){if(k)return f;k=1;const e=o,n=t,s=I(),{env:i}=process;let a;function r(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(t,n){if(0===a)return 0;if(s("color=16m")||s("color=full")||s("color=truecolor"))return 3;if(s("color=256"))return 2;if(t&&!n&&void 0===a)return 0;const o=a||0;if("dumb"===i.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in i)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||"codeship"===i.CI_NAME?1:o;if("TEAMCITY_VERSION"in i)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0;if("truecolor"===i.COLORTERM)return 3;if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(i.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)||"COLORTERM"in i?1:o}return s("no-color")||s("no-colors")||s("color=false")||s("color=never")?a=0:(s("color")||s("colors")||s("color=true")||s("color=always"))&&(a=1),"FORCE_COLOR"in i&&(a="true"===i.FORCE_COLOR?1:"false"===i.FORCE_COLOR?0:0===i.FORCE_COLOR.length?1:Math.min(parseInt(i.FORCE_COLOR,10),3)),f={supportsColor:function(e){return r(c(e,e&&e.isTTY))},stdout:r(c(!0,n.isatty(1))),stderr:r(c(!0,n.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(s.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}s.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let o=process.env[t];return o=!!/^(yes|on|true|enabled)$/i.test(o)||!/^(no|off|false|disabled)$/i.test(o)&&("null"===o?null:Number(o)),e[n]=o,e}),{}),e.exports=C()(s);const{formatters:r}=e.exports;r.o=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},r.O=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts)}}(K,K.exports)),K.exports);var _=d(y.exports);const O=_("KeyExchange:Layer"),A=_("SocketService:Layer"),N=_("Ecies:Layer"),R=_("RemoteCommunication:Layer");O.color="##95c44e",A.color="#f638d7",N.color="#465b9c",R.color="#47a2be";const b={KeyExchange:O,SocketService:A,Ecies:N,RemoteCommunication:R};let w,M=[],D=[];function $(t){return l(this,void 0,void 0,(function*(){if(!w||!t)return;!function(){const e=D;D=M,M=e}();const n=w.endsWith("/")?`${w}debug`:`${w}/debug`,o=Object.assign({},t);if(delete o.params,t.params)for(const[e,n]of Object.entries(t.params))o[e]=n;const s=JSON.stringify(o);b.RemoteCommunication(`[sendBufferedEvents] Sending ${M.length} analytics events to ${n}`);try{const t=yield e(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:s}),o=yield t.text();b.RemoteCommunication(`[sendBufferedEvents] Response: ${o}`),M.length=0}catch(e){console.warn("Error sending analytics",e)}}))}const L=(e,t)=>l(void 0,void 0,void 0,(function*(){var n;w=t,n=e,D.push(n),$(e).catch((()=>{}))}));class P{constructor(e){this.enabled=!0,(null==e?void 0:e.debug)&&_.enable("Ecies:Layer"),(null==e?void 0:e.pkey)?this.ecies=i.PrivateKey.fromHex(e.pkey):this.ecies=new i.PrivateKey,b.Ecies("[ECIES constructor()] initialized secret: ",this.ecies.toHex()),b.Ecies("[ECIES constructor()] initialized public: ",this.ecies.publicKey.toHex()),b.Ecies("[ECIES constructor()] init with",this)}generateECIES(){this.ecies=new i.PrivateKey}getPublicKey(){return this.ecies.publicKey.toHex()}encrypt(e,t){let n=e;if(this.enabled)try{b.Ecies("[ECIES: encrypt()] using otherPublicKey",t);const o=s.Buffer.from(e),a=i.encrypt(t,o);n=s.Buffer.from(a).toString("base64")}catch(n){throw b.Ecies("[ECIES: encrypt()] error encrypt:",n),b.Ecies("[ECIES: encrypt()] private: ",this.ecies.toHex()),b.Ecies("[ECIES: encrypt()] data: ",e),b.Ecies("[ECIES: encrypt()] otherkey: ",t),n}return n}decrypt(e){let t=e;if(this.enabled)try{b.Ecies("[ECIES: decrypt()] using privateKey",this.ecies.toHex());const n=s.Buffer.from(e.toString(),"base64");t=i.decrypt(this.ecies.toHex(),n).toString()}catch(t){throw b.Ecies("[ECIES: decrypt()] error decrypt",t),b.Ecies("[ECIES: decrypt()] private: ",this.ecies.toHex()),b.Ecies("[ECIES: decrypt()] encryptedData: ",e),t}return t}getKeyInfo(){return{private:this.ecies.toHex(),public:this.ecies.publicKey.toHex()}}toString(){b.Ecies("[ECIES: toString()]",this.getKeyInfo())}}var H={name:"@metamask/sdk-communication-layer",version:"0.18.0",description:"",homepage:"https://github.com/MetaMask/metamask-sdk#readme",bugs:{url:"https://github.com/MetaMask/metamask-sdk/issues"},repository:{type:"git",url:"https://github.com/MetaMask/metamask-sdk.git",directory:"packages/sdk-communication-layer"},main:"dist/node/cjs/metamask-sdk-communication-layer.js",unpkg:"dist/browser/umd/metamask-sdk-communication-layer.js",module:"dist/node/es/metamask-sdk-communication-layer.js",browser:"dist/browser/es/metamask-sdk-communication-layer.js","react-native":"dist/react-native/es/metamask-sdk-communication-layer.js",types:"dist/browser/es/src/index.d.ts",files:["/dist"],scripts:{build:"rimraf dist && rollup -c --bundleConfigAsCjs","build:tsc":"tsc","build:dev":"rimraf dist && NODE_ENV=dev rollup -c --bundleConfigAsCjs","build:post-tsc":"echo 'N/A'","build:pre-tsc":"echo 'N/A'",size:"size-limit",clean:"rimraf ./dist",lint:"yarn lint:eslint && yarn lint:misc --check","lint:changelog":"../../scripts/validate-changelog.sh @metamask/sdk-communication-layer","lint:eslint":"eslint . --cache --ext js,ts","lint:fix":"yarn lint:eslint --fix && yarn lint:misc --write","lint:misc":"prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path ../../.gitignore","prepare-manifest:preview":"../../scripts/prepare-preview-manifest.sh","publish:preview":"yarn npm publish --tag preview",prepack:"../../scripts/prepack.sh",reset:"yarn clean && rimraf ./node_modules/",test:"jest","test:coverage":"jest --coverage","test:ci":"jest --coverage --passWithNoTests --setupFilesAfterEnv ./jest-preload.js","test:dev":"jest",watch:"rollup -c --bundleConfigAsCjs -w"},dependencies:{bufferutil:"^4.0.8","date-fns":"^2.29.3",debug:"^4.3.4","utf-8-validate":"^6.0.3",uuid:"^8.3.2"},devDependencies:{"@jest/globals":"^29.3.1","@lavamoat/allow-scripts":"^2.3.1","@metamask/auto-changelog":"3.1.0","@metamask/eslint-config":"^6.0.0","@metamask/eslint-config-nodejs":"^6.0.0","@metamask/eslint-config-typescript":"^6.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.0.2","@rollup/plugin-terser":"^0.4.1","@size-limit/preset-big-lib":"^11.0.2","@types/jest":"^29.2.4","@types/node":"^20.1.3","@types/uuid":"^9.0.0","@typescript-eslint/eslint-plugin":"^4.26.0","@typescript-eslint/parser":"^4.26.0","cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eslint:"^7.30.0","eslint-config-prettier":"^8.3.0","eslint-plugin-import":"^2.23.4","eslint-plugin-jest":"^24.4.0","eslint-plugin-jsdoc":"^36.1.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.4.0",eventemitter2:"^6.4.7",jest:"^29.3.1",prettier:"^2.3.0",rimraf:"^3.0.2",rollup:"^3.21.7","rollup-plugin-jscc":"^2.0.0","rollup-plugin-natives":"^0.7.5","rollup-plugin-node-builtins":"^2.1.2","rollup-plugin-node-globals":"^1.4.0","rollup-plugin-peer-deps-external":"^2.2.4","rollup-plugin-sizes":"^1.0.6","rollup-plugin-typescript2":"^0.31.2","rollup-plugin-visualizer":"^5.9.2","size-limit":"^11.0.2","socket.io-client":"^4.5.1","stream-browserify":"^3.0.0","ts-jest":"^29.0.3","ts-node":"^10.9.1",typescript:"^4.3.2"},peerDependencies:{"cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eventemitter2:"^6.4.7","readable-stream":"^3.6.2","socket.io-client":"^4.5.1"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},lavamoat:{allowScripts:{"@lavamoat/preinstall-always-fail":!1,canvas:!0,"eciesjs>secp256k1":!1,"socket.io-client>engine.io-client>ws>bufferutil":!1,"socket.io-client>engine.io-client>ws>utf-8-validate":!1,bufferutil:!1,"utf-8-validate":!1}}};const F="https://metamask-sdk.api.cx.metamask.io/",U=["websocket"],Y=6048e5,j={METAMASK_GETPROVIDERSTATE:"metamask_getProviderState",ETH_REQUESTACCOUNTS:"eth_requestAccounts"};function G(e){const{context:t}=e;b.RemoteCommunication(`[RemoteCommunication: clean()] context=${t}`),e.channelConfig=void 0,e.ready=!1,e.originatorConnectStarted=!1}var z,V,W,B,q;exports.ConnectionStatus=void 0,(z=exports.ConnectionStatus||(exports.ConnectionStatus={})).DISCONNECTED="disconnected",z.WAITING="waiting",z.TIMEOUT="timeout",z.LINKED="linked",z.PAUSED="paused",z.TERMINATED="terminated",exports.EventType=void 0,(V=exports.EventType||(exports.EventType={})).KEY_INFO="key_info",V.SERVICE_STATUS="service_status",V.PROVIDER_UPDATE="provider_update",V.RPC_UPDATE="rpc_update",V.KEYS_EXCHANGED="keys_exchanged",V.JOIN_CHANNEL="join_channel",V.CHANNEL_CREATED="channel_created",V.CLIENTS_CONNECTED="clients_connected",V.CLIENTS_DISCONNECTED="clients_disconnected",V.CLIENTS_WAITING="clients_waiting",V.CLIENTS_READY="clients_ready",V.SOCKET_DISCONNECTED="socket_disconnected",V.SOCKET_RECONNECT="socket_reconnect",V.OTP="otp",V.SDK_RPC_CALL="sdk_rpc_call",V.AUTHORIZED="authorized",V.CONNECTION_STATUS="connection_status",V.MESSAGE="message",V.TERMINATE="terminate",function(e){e.KEY_EXCHANGE="key_exchange"}(W||(W={})),exports.KeyExchangeMessageType=void 0,(B=exports.KeyExchangeMessageType||(exports.KeyExchangeMessageType={})).KEY_HANDSHAKE_START="key_handshake_start",B.KEY_HANDSHAKE_CHECK="key_handshake_check",B.KEY_HANDSHAKE_SYN="key_handshake_SYN",B.KEY_HANDSHAKE_SYNACK="key_handshake_SYNACK",B.KEY_HANDSHAKE_ACK="key_handshake_ACK",B.KEY_HANDSHAKE_NONE="none";class J extends a.EventEmitter2{constructor({communicationLayer:e,otherPublicKey:t,context:n,ecies:o,logging:s}){super(),this.keysExchanged=!1,this.step=exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE,this.debug=!1,this.context=n,this.myECIES=new P(Object.assign(Object.assign({},o),{debug:null==s?void 0:s.eciesLayer})),this.communicationLayer=e,this.myPublicKey=this.myECIES.getPublicKey(),this.debug=!0===(null==s?void 0:s.keyExchangeLayer),(null==s?void 0:s.keyExchangeLayer)&&_.enable("KeyExchange:Layer"),t&&this.setOtherPublicKey(t),this.communicationLayer.on(W.KEY_EXCHANGE,this.onKeyExchangeMessage.bind(this))}onKeyExchangeMessage(e){b.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} keysExchanged=${this.keysExchanged}`,e);const{message:t}=e;this.keysExchanged&&b.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} received handshake while already exchanged. step=${this.step} otherPubKey=${this.otherPublicKey}`),this.emit(exports.EventType.KEY_INFO,t.type),t.type===exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYN?(this.checkStep([exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE,exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK]),b.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYN",t),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK,pubkey:this.myPublicKey}),this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK)):t.type===exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK?(this.checkStep([exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK,exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK,exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE]),b.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYNACK"),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK}),this.keysExchanged=!0,this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK),this.emit(exports.EventType.KEYS_EXCHANGED)):t.type===exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK&&(b.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_ACK set keysExchanged to true!"),this.checkStep([exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK,exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE]),this.keysExchanged=!0,this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_ACK),this.emit(exports.EventType.KEYS_EXCHANGED))}resetKeys(e){this.clean(),this.myECIES=new P(e)}clean(){b.KeyExchange(`[KeyExchange: clean()] context=${this.context} reset handshake state`),this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE),this.emit(exports.EventType.KEY_INFO,this.step),this.keysExchanged=!1}start({isOriginator:e,force:t}){b.KeyExchange(`[KeyExchange: start()] context=${this.context} isOriginator=${e} step=${this.step} force=${t} keysExchanged=${this.keysExchanged}`),e?!(this.keysExchanged||this.step!==exports.KeyExchangeMessageType.KEY_HANDSHAKE_NONE&&this.step!==exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK)||t?(b.KeyExchange(`[KeyExchange: start()] context=${this.context} -- start key exchange (force=${t}) -- step=${this.step}`,this.step),this.clean(),this.setStep(exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYNACK),this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_SYN,pubkey:this.myPublicKey})):b.KeyExchange(`[KeyExchange: start()] context=${this.context} -- key exchange already ${this.keysExchanged?"done":"in progress"} -- aborted.`,this.step):this.keysExchanged&&!0!==t?b.KeyExchange("[KeyExchange: start()] don't send KEY_HANDSHAKE_START -- exchange already done."):(this.communicationLayer.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_START}),this.clean())}setStep(e){this.step=e,this.emit(exports.EventType.KEY_INFO,e)}checkStep(e){e.length>0&&-1===e.indexOf(this.step.toString())&&console.warn(`[KeyExchange: checkStep()] Wrong Step "${this.step}" not within ${e}`)}setKeysExchanged(e){this.keysExchanged=e}areKeysExchanged(){return this.keysExchanged}getMyPublicKey(){return this.myPublicKey}getOtherPublicKey(){return this.otherPublicKey}setOtherPublicKey(e){b.KeyExchange("[KeyExchange: setOtherPubKey()]",e),this.otherPublicKey=e}encryptMessage(e){if(!this.otherPublicKey)throw new Error("encryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.encrypt(e,this.otherPublicKey)}decryptMessage(e){if(!this.otherPublicKey)throw new Error("decryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.decrypt(e)}getKeyInfo(){return{ecies:Object.assign(Object.assign({},this.myECIES.getKeyInfo()),{otherPubKey:this.otherPublicKey}),step:this.step,keysExchanged:this.areKeysExchanged()}}toString(){const e={keyInfo:this.getKeyInfo(),keysExchanged:this.keysExchanged,step:this.step};return JSON.stringify(e)}}exports.MessageType=void 0,(q=exports.MessageType||(exports.MessageType={})).TERMINATE="terminate",q.ANSWER="answer",q.OFFER="offer",q.CANDIDATE="candidate",q.JSONRPC="jsonrpc",q.WALLET_INFO="wallet_info",q.ORIGINATOR_INFO="originator_info",q.PAUSE="pause",q.OTP="otp",q.AUTHORIZED="authorized",q.PING="ping",q.READY="ready";const Z=e=>new Promise((t=>{setTimeout(t,e)})),X=(e,t,n=200)=>l(void 0,void 0,void 0,(function*(){let o;const s=Date.now();let i=!1;for(;!i;){if(i=Date.now()-s>3e5,o=t[e],void 0!==o.elapsedTime)return o;yield Z(n)}throw new Error(`RPC ${e} timed out`)})),Q=({rpcId:e,instance:t})=>l(void 0,void 0,void 0,(function*(){for(;t.state.lastRpcId===e||void 0===t.state.lastRpcId;)yield Z(200);return t.state.lastRpcId})),ee=e=>l(void 0,void 0,void 0,(function*(){var t,n,o,s,i;return b.SocketService(`[SocketService: reconnectSocket()] instance.state.socket?.connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} trying to reconnect after socketio disconnection`,e),yield Z(200),(null===(n=e.state.socket)||void 0===n?void 0:n.connected)||(e.state.resumed=!0,null===(o=e.state.socket)||void 0===o||o.connect(),e.emit(exports.EventType.SOCKET_RECONNECT),null===(s=e.state.socket)||void 0===s||s.emit(exports.EventType.JOIN_CHANNEL,e.state.channelId,`${e.state.context}connect_again`)),yield Z(100),null===(i=e.state.socket)||void 0===i?void 0:i.connected}));function te(e){return t=>{b.SocketService(`[SocketService: handleDisconnect()] on 'disconnect' manualDisconnect=${e.state.manualDisconnect}`,t),e.state.manualDisconnect||(e.emit(exports.EventType.SOCKET_DISCONNECTED),function(e){"undefined"!=typeof window&&"undefined"!=typeof document&&(b.SocketService(`[SocketService: checkFocusAndReconnect()] hasFocus=${document.hasFocus()}`,e),document.hasFocus()?ee(e).then((t=>{b.SocketService(`SocketService::checkFocus reconnectSocket success=${t}`,e)})).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)})):window.addEventListener("focus",(()=>{ee(e).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)}))}),{once:!0}))}(e))}}const ne=[{event:"clients_connected",handler:function(e,t){return n=>l(this,void 0,void 0,(function*(){var n,o,s,i,a,r,c,l;b.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected-${t}' resumed=${e.state.resumed} clientsPaused=${e.state.clientsPaused} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()} isOriginator=${e.state.isOriginator}`),e.emit(exports.EventType.CLIENTS_CONNECTED,{isOriginator:e.state.isOriginator,keysExchanged:null===(o=e.state.keyExchange)||void 0===o?void 0:o.areKeysExchanged(),context:e.state.context}),e.state.resumed?(e.state.isOriginator||(b.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} 'clients_connected' / keysExchanged=${null===(s=e.state.keyExchange)||void 0===s?void 0:s.areKeysExchanged()} -- backward compatibility`),null===(i=e.state.keyExchange)||void 0===i||i.start({isOriginator:null!==(a=e.state.isOriginator)&&void 0!==a&&a})),e.state.resumed=!1):e.state.clientsPaused?b.SocketService("[SocketService: handleClientsConnected()] 'clients_connected' skip sending originatorInfo on pause"):e.state.isOriginator||(b.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected' / keysExchanged=${null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged()} -- backward compatibility`),null===(c=e.state.keyExchange)||void 0===c||c.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l,force:!0})),e.state.clientsConnected=!0,e.state.clientsPaused=!1}))}},{event:"channel_created",handler:function(e,t){return n=>{b.SocketService(`[SocketService: handleChannelCreated()] context=${e.state.context} on 'channel_created-${t}'`,n),e.emit(exports.EventType.CHANNEL_CREATED,n)}}},{event:"clients_disconnected",handler:function(e,t){return()=>{var n;e.state.clientsConnected=!1,b.SocketService(`[SocketService: handlesClientsDisconnected()] context=${e.state.context} on 'clients_disconnected-${t}'`),e.state.isOriginator&&!e.state.clientsPaused&&(null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.emit(exports.EventType.CLIENTS_DISCONNECTED,t)}}},{event:"message",handler:function(e,t){return({id:n,message:o,error:s})=>{var i,a,r,c,l,d,u,h,p,m,g,y,E,v,C;if(b.SocketService(`[SocketService handleMessage()] context=${e.state.context} on 'message' ${t} keysExchanged=${null===(i=e.state.keyExchange)||void 0===i?void 0:i.areKeysExchanged()}`,o),s)throw b.SocketService(`\n [SocketService handleMessage()] context=${e.state.context}::on 'message' error=${s}`),new Error(s);try{!function(e,t){if(t!==e.channelId)throw e.debug&&console.error(`Wrong id ${t} - should be ${e.channelId}`),new Error("Wrong id")}(e.state,n)}catch(e){return void console.error("ignore message --- wrong id ",o)}if(e.state.isOriginator&&(null==o?void 0:o.type)===exports.KeyExchangeMessageType.KEY_HANDSHAKE_START)return b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received HANDSHAKE_START isOriginator=${e.state.isOriginator}`,o),void(null===(a=e.state.keyExchange)||void 0===a||a.start({isOriginator:null!==(r=e.state.isOriginator)&&void 0!==r&&r,force:!0}));if((null==o?void 0:o.type)===exports.MessageType.PING)return b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' ping `),void e.emit(exports.EventType.MESSAGE,{message:{type:"ping"}});if(b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' originator=${e.state.isOriginator}, type=${null==o?void 0:o.type}, keysExchanged=${null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged()}`),null===(l=null==o?void 0:o.type)||void 0===l?void 0:l.startsWith("key_handshake"))return b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' emit KEY_EXCHANGE`,o),void e.emit(W.KEY_EXCHANGE,{message:o,context:e.state.context});if(null===(d=e.state.keyExchange)||void 0===d?void 0:d.areKeysExchanged()){if(-1!==o.toString().indexOf("type"))return console.warn("[SocketService handleMessage() ::on 'message' received non encrypted unkwown message"),void e.emit(exports.EventType.MESSAGE,o)}else{let t=!1;try{null===(u=e.state.keyExchange)||void 0===u||u.decryptMessage(o),t=!0}catch(e){}if(!t)return e.state.isOriginator?null===(p=e.state.keyExchange)||void 0===p||p.start({isOriginator:null!==(m=e.state.isOriginator)&&void 0!==m&&m}):e.sendMessage({type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_START}),void console.warn(`Message ignored because invalid key exchange status. step=${null===(g=e.state.keyExchange)||void 0===g?void 0:g.getKeyInfo().step}`,null===(y=e.state.keyExchange)||void 0===y?void 0:y.getKeyInfo(),o);console.warn("Invalid key exchange status detected --- updating it."),null===(h=e.state.keyExchange)||void 0===h||h.setKeysExchanged(!0)}const S=null===(E=e.state.keyExchange)||void 0===E?void 0:E.decryptMessage(o),x=JSON.parse(null!=S?S:"{}");if((null==x?void 0:x.type)===exports.MessageType.PAUSE?e.state.clientsPaused=!0:e.state.clientsPaused=!1,e.state.isOriginator&&x.data){const t=x.data,n=e.state.rpcMethodTracker[t.id];if(n){const o=Date.now()-n.timestamp;b.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received answer for id=${t.id} method=${n.method} responseTime=${o}`,x);const s=Object.assign(Object.assign({},n),{result:t.result,error:t.error?{code:null===(v=t.error)||void 0===v?void 0:v.code,message:null===(C=t.error)||void 0===C?void 0:C.message}:void 0,elapsedTime:o});e.state.rpcMethodTracker[t.id]=s,e.emit(exports.EventType.RPC_UPDATE,s),b.SocketService("[SocketService handleMessage()] HACK (wallet <7.3) update rpcMethodTracker",s),e.emit(exports.EventType.AUTHORIZED)}}e.emit(exports.EventType.MESSAGE,{message:x})}}},{event:"clients_waiting_to_join",handler:function(e,t){return n=>{b.SocketService(`[SocketService: handleClientsWaitingToJoin()] context=${e.state.context} on 'clients_waiting_to_join-${t}'`,n),e.emit(exports.EventType.CLIENTS_WAITING,n)}}}],oe=[{event:exports.EventType.KEY_INFO,handler:function(e){return t=>{b.SocketService("[SocketService: handleKeyInfo()] on 'KEY_INFO'",t),e.emit(exports.EventType.KEY_INFO,t)}}},{event:exports.EventType.KEYS_EXCHANGED,handler:function(e){return()=>{var t,n;b.SocketService(`[SocketService: handleKeysExchanged()] on 'keys_exchanged' keyschanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.emit(exports.EventType.KEYS_EXCHANGED,{keysExchanged:null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged(),isOriginator:e.state.isOriginator});const o={keyInfo:e.getKeyInfo()};e.emit(exports.EventType.SERVICE_STATUS,o)}}}];function se(e,t){b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} setting socket listeners for channel ${t}...`);const{socket:n}=e.state,{keyExchange:o}=e.state;e.state.setupChannelListeners&&console.warn(`[SocketService: setupChannelListener()] context=${e.state.context} socket listeners already set up for channel ${t}`),n&&e.state.isOriginator&&(e.state.debug&&(null==n||n.io.on("error",(t=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=error`,t)})),null==n||n.io.on("reconnect",(t=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect`,t)})),null==n||n.io.on("reconnect_error",(t=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_error`,t)})),null==n||n.io.on("reconnect_failed",(()=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_failed`)})),null==n||n.io.on("ping",(()=>{b.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=ping`)}))),null==n||n.on("disconnect",(t=>(b.SocketService(`[SocketService: setupChannelListener()] on 'disconnect' -- MetaMaskSDK socket disconnected '${t}' begin recovery...`),te(e)(t))))),ne.forEach((({event:o,handler:s})=>{const i=`${o}-${t}`;null==n||n.on(i,s(e,t))})),oe.forEach((({event:t,handler:n})=>{null==o||o.on(t,n(e))})),e.state.setupChannelListeners=!0}var ie;exports.TrackingEvents=void 0,(ie=exports.TrackingEvents||(exports.TrackingEvents={})).REQUEST="sdk_connect_request_started",ie.REQUEST_MOBILE="sdk_connect_request_started_mobile",ie.RECONNECT="sdk_reconnect_request_started",ie.CONNECTED="sdk_connection_established",ie.CONNECTED_MOBILE="sdk_connection_established_mobile",ie.AUTHORIZED="sdk_connection_authorized",ie.REJECTED="sdk_connection_rejected",ie.TERMINATED="sdk_connection_terminated",ie.DISCONNECTED="sdk_disconnected",ie.SDK_USE_EXTENSION="sdk_use_extension",ie.SDK_RPC_REQUEST="sdk_rpc_request",ie.SDK_EXTENSION_UTILIZED="sdk_extension_utilized",ie.SDK_USE_INAPP_BROWSER="sdk_use_inapp_browser";const ae="SDK_CONNECTION_ISSUE";var re;!function(e){e.RPC_CHECK="rpcCheck",e.SKIPPED_RPC="skippedRpc"}(re||(re={}));const ce=["eth_sendTransaction","eth_signTypedData","eth_signTransaction","wallet_requestPermissions","wallet_switchEthereumChain","eth_signTypedData_v3","eth_signTypedData_v4","metamask_connectSign","metamask_connectWith","metamask_batch"].map((e=>e.toLowerCase()));function le(e,t){var n,o,s,i;if(!e.state.channelId)throw new Error("Create a channel first");b.SocketService(`[SocketService: handleSendMessage()] context=${e.state.context} areKeysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`,t);(null===(o=null==t?void 0:t.type)||void 0===o?void 0:o.startsWith("key_handshake"))?function(e,t){var n;b.SocketService(`[SocketService: handleKeyHandshake()] context=${e.state.context}`,t),null===(n=e.state.socket)||void 0===n||n.emit(exports.EventType.MESSAGE,{id:e.state.channelId,context:e.state.context,message:t})}(e,t):(!function(e,t){var n;if(!(null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()))throw b.SocketService(`[SocketService: validateKeyExchange()] context=${e.state.context} ERROR keys not exchanged`,t),new Error("Keys not exchanged BBB")}(e,t),function(e,t){var n;const o=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"",s=null==t?void 0:t.id;e.state.isOriginator&&s&&(e.state.rpcMethodTracker[s]={id:s,timestamp:Date.now(),method:o},e.emit(exports.EventType.RPC_UPDATE,e.state.rpcMethodTracker[s]))}(e,t),function(e,t){var n,o;const s=null===(n=e.state.keyExchange)||void 0===n?void 0:n.encryptMessage(JSON.stringify(t)),i={id:e.state.channelId,context:e.state.context,message:s,plaintext:e.state.hasPlaintext?JSON.stringify(t):void 0};b.SocketService(`[SocketService: encryptAndSendMessage()] context=${e.state.context}`,i),t.type===exports.MessageType.TERMINATE&&(e.state.manualDisconnect=!0),null===(o=e.state.socket)||void 0===o||o.emit(exports.EventType.MESSAGE,i)}(e,t),e.remote.state.analytics&&t.method&&ce.includes(t.method.toLowerCase())&&L({id:null!==(s=e.remote.state.channelId)&&void 0!==s?s:"",event:exports.TrackingEvents.SDK_RPC_REQUEST,sdkVersion:e.remote.state.sdkVersion,commLayerVersion:H.version,walletVersion:null===(i=e.remote.state.walletInfo)||void 0===i?void 0:i.version,params:{method:t.method,from:"mobile"}},e.remote.state.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),function(e,t){var n;return l(this,void 0,void 0,(function*(){const o=null==t?void 0:t.id,s=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"";if(e.state.isOriginator&&o)try{const n=X(o,e.state.rpcMethodTracker,200).then((e=>({type:re.RPC_CHECK,result:e}))),i=(()=>l(this,void 0,void 0,(function*(){const t=yield Q({instance:e,rpcId:o}),n=yield X(t,e.state.rpcMethodTracker,200);return{type:re.SKIPPED_RPC,result:n}})))(),a=yield Promise.race([n,i]);if(a.type===re.RPC_CHECK){const e=a.result;b.SocketService(`[SocketService:handleRpcReplies()] id=${t.id} ${s} ( ${e.elapsedTime} ms)`,e.result)}else{if(a.type!==re.SKIPPED_RPC)throw new Error(`Error handling RPC replies for ${o}`);{const{result:t}=a;console.warn(`[SocketService handleRpcReplies()] RPC METHOD HAS BEEN SKIPPED rpcid=${o} method=${s}`,t);const n=Object.assign(Object.assign({},e.state.rpcMethodTracker[o]),{error:new Error(ae)});e.emit(exports.EventType.RPC_UPDATE,n);const i={data:Object.assign(Object.assign({},n),{jsonrpc:"2.0"}),name:"metamask-provider"};e.emit(exports.EventType.MESSAGE,{message:i})}}}catch(e){throw console.warn(`[SocketService handleRpcReplies()] Error rpcId=${t.id} ${s}`,e),e}}))}(e,t).catch((e=>{console.warn("Error handleRpcReplies",e)})))}class de extends a.EventEmitter2{constructor({otherPublicKey:e,reconnect:t,communicationLayerPreference:n,transports:o,communicationServerUrl:s,context:i,ecies:a,remote:r,logging:l}){super(),this.state={clientsConnected:!1,clientsPaused:!1,manualDisconnect:!1,lastRpcId:void 0,rpcMethodTracker:{},hasPlaintext:!1,communicationServerUrl:""},this.state.resumed=t,this.state.context=i,this.state.communicationLayerPreference=n,this.state.debug=!0===(null==l?void 0:l.serviceLayer),this.remote=r,!0===(null==l?void 0:l.serviceLayer)&&_.enable("SocketService:Layer"),this.state.communicationServerUrl=s,this.state.hasPlaintext=this.state.communicationServerUrl!==F&&!0===(null==l?void 0:l.plaintext);const d={autoConnect:!1,transports:U,withCredentials:!0};o&&(d.transports=o),b.SocketService(`[SocketService: constructor()] Socket IO url: ${this.state.communicationServerUrl}`),this.state.socket=c.io(s,d);const u={communicationLayer:this,otherPublicKey:e,sendPublicKey:!1,context:this.state.context,ecies:a,logging:l};this.state.keyExchange=new J(u)}resetKeys(){return e=this,b.SocketService("[SocketService: resetKeys()] Resetting keys."),void(null===(t=e.state.keyExchange)||void 0===t||t.resetKeys());var e,t}createChannel(){return function(e){var t,n,o,s;b.SocketService(`[SocketService: createChannel()] context=${e.state.context}`),(null===(t=e.state.socket)||void 0===t?void 0:t.connected)||null===(n=e.state.socket)||void 0===n||n.connect(),e.state.manualDisconnect=!1,e.state.isOriginator=!0;const i=r.v4();return e.state.channelId=i,se(e,i),null===(o=e.state.socket)||void 0===o||o.emit(exports.EventType.JOIN_CHANNEL,i,`${e.state.context}createChannel`),{channelId:i,pubKey:(null===(s=e.state.keyExchange)||void 0===s?void 0:s.getMyPublicKey())||""}}(this)}connectToChannel({channelId:e,isOriginator:t=!1,withKeyExchange:n=!1}){return function({options:e,instance:t}){var n,o,s,i;const{channelId:a,withKeyExchange:r,isOriginator:c}=e;if(b.SocketService(`[SocketService: connectToChannel()] context=${t.state.context} channelId=${a} isOriginator=${c}`,null===(n=t.state.keyExchange)||void 0===n?void 0:n.toString()),null===(o=t.state.socket)||void 0===o?void 0:o.connected)throw new Error("socket already connected");t.state.manualDisconnect=!1,null===(s=t.state.socket)||void 0===s||s.connect(),t.state.withKeyExchange=r,t.state.isOriginator=c,t.state.channelId=a,se(t,a),null===(i=t.state.socket)||void 0===i||i.emit(exports.EventType.JOIN_CHANNEL,a,`${t.state.context}_connectToChannel`)}({options:{channelId:e,isOriginator:t,withKeyExchange:n},instance:this})}getKeyInfo(){return this.state.keyExchange.getKeyInfo()}keyCheck(){var e,t;null===(t=(e=this).state.socket)||void 0===t||t.emit(exports.EventType.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:exports.KeyExchangeMessageType.KEY_HANDSHAKE_CHECK,pubkey:e.getKeyInfo().ecies.otherPubKey}})}getKeyExchange(){return this.state.keyExchange}sendMessage(e){return le(this,e)}ping(){return e=this,b.SocketService(`[SocketService: ping()] context=${e.state.context} originator=${e.state.isOriginator} keysExchanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.state.isOriginator&&((null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged())?(console.warn(`[SocketService:ping()] context=${e.state.context} sending READY message`),e.sendMessage({type:exports.MessageType.READY})):(console.warn(`[SocketService: ping()] context=${e.state.context} starting key exchange`),null===(o=e.state.keyExchange)||void 0===o||o.start({isOriginator:null!==(s=e.state.isOriginator)&&void 0!==s&&s}))),void(null===(i=e.state.socket)||void 0===i||i.emit(exports.EventType.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:exports.MessageType.PING}}));var e,t,n,o,s,i}pause(){return e=this,b.SocketService(`[SocketService: pause()] context=${e.state.context}`),e.state.manualDisconnect=!0,(null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged())&&e.sendMessage({type:exports.MessageType.PAUSE}),void(null===(n=e.state.socket)||void 0===n||n.disconnect());var e,t,n}isConnected(){var e;return null===(e=this.state.socket)||void 0===e?void 0:e.connected}resume(){return e=this,b.SocketService(`[SocketService: resume()] context=${e.state.context} connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} manualDisconnect=${e.state.manualDisconnect} resumed=${e.state.resumed} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`),(null===(o=e.state.socket)||void 0===o?void 0:o.connected)?b.SocketService("[SocketService: resume()] already connected."):(null===(s=e.state.socket)||void 0===s||s.connect(),b.SocketService(`[SocketService: resume()] after connecting socket --\x3e connected=${null===(i=e.state.socket)||void 0===i?void 0:i.connected}`),null===(a=e.state.socket)||void 0===a||a.emit(exports.EventType.JOIN_CHANNEL,e.state.channelId,`${e.state.context}_resume`)),(null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged())?e.state.isOriginator||e.sendMessage({type:exports.MessageType.READY}):e.state.isOriginator||null===(c=e.state.keyExchange)||void 0===c||c.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l}),e.state.manualDisconnect=!1,void(e.state.resumed=!0);var e,t,n,o,s,i,a,r,c,l}getRPCMethodTracker(){return this.state.rpcMethodTracker}disconnect(e){return function(e,t){var n,o;b.SocketService(`[SocketService: disconnect()] context=${e.state.context}`,t),(null==t?void 0:t.terminate)&&(e.state.channelId=t.channelId,null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.state.rpcMethodTracker={},e.state.manualDisconnect=!0,null===(o=e.state.socket)||void 0===o||o.disconnect()}(this,e)}}var ue,he;function pe(e){return()=>l(this,void 0,void 0,(function*(){var t,n,o;const{state:s}=e;if(s.authorized)return;yield(()=>l(this,void 0,void 0,(function*(){for(;!s.walletInfo;)yield Z(500)})))();const i="7.3".localeCompare((null===(t=s.walletInfo)||void 0===t?void 0:t.version)||"");if(b.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' version=${null===(n=s.walletInfo)||void 0===n?void 0:n.version} compareValue=${i}`),1!==i)return;const a=s.platformType===exports.PlatformType.MobileWeb||s.platformType===exports.PlatformType.ReactNative||s.platformType===exports.PlatformType.MetaMaskMobileWebview;b.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' platform=${s.platformType} secure=${a} channel=${s.channelId} walletVersion=${null===(o=s.walletInfo)||void 0===o?void 0:o.version}`),a&&(s.authorized=!0,e.emit(exports.EventType.AUTHORIZED))}))}function me(e){return t=>{const{state:n}=e;b.RemoteCommunication(`[RemoteCommunication: handleChannelCreatedEvent()] context=${n.context} on 'channel_created' channelId=${t}`),e.emit(exports.EventType.CHANNEL_CREATED,t)}}function ge(e,t){return()=>{var n,o,s,i;const{state:a}=e;if(b.RemoteCommunication(`[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=${a.channelId} keysExchanged=${null===(o=null===(n=a.communicationLayer)||void 0===n?void 0:n.getKeyInfo())||void 0===o?void 0:o.keysExchanged}`),a.analytics){const e=a.isOriginator?exports.TrackingEvents.REQUEST:exports.TrackingEvents.REQUEST_MOBILE;L(Object.assign(Object.assign({id:null!==(s=a.channelId)&&void 0!==s?s:"",event:a.reconnection?exports.TrackingEvents.RECONNECT:e},a.originatorInfo),{commLayer:t,sdkVersion:a.sdkVersion,walletVersion:null===(i=a.walletInfo)||void 0===i?void 0:i.version,commLayerVersion:H.version}),a.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}a.clientsConnected=!0,a.originatorInfoSent=!1,e.emit(exports.EventType.CLIENTS_CONNECTED)}}function ye(e,t){return n=>{var o;const{state:s}=e;b.RemoteCommunication(`[RemoteCommunication: handleClientsDisconnectedEvent()] context=${s.context} on 'clients_disconnected' channelId=${n}`),s.clientsConnected=!1,e.emit(exports.EventType.CLIENTS_DISCONNECTED,s.channelId),e.setConnectionStatus(exports.ConnectionStatus.DISCONNECTED),s.ready=!1,s.authorized=!1,s.analytics&&s.channelId&&L({id:s.channelId,event:exports.TrackingEvents.DISCONNECTED,sdkVersion:s.sdkVersion,commLayer:t,commLayerVersion:H.version,walletVersion:null===(o=s.walletInfo)||void 0===o?void 0:o.version},s.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}}function Ee(e){return t=>{var n;const{state:o}=e;if(b.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] context=${o.context} on 'clients_waiting' numberUsers=${t} ready=${o.ready} autoStarted=${o.originatorConnectStarted}`),e.setConnectionStatus(exports.ConnectionStatus.WAITING),e.emit(exports.EventType.CLIENTS_WAITING,t),o.originatorConnectStarted){b.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] on 'clients_waiting' watch autoStarted=${o.originatorConnectStarted} timeout`,o.autoConnectOptions);const t=(null===(n=o.autoConnectOptions)||void 0===n?void 0:n.timeout)||3e3,s=setTimeout((()=>{b.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] setTimeout(${t}) terminate channelConfig`,o.autoConnectOptions),o.originatorConnectStarted=!1,o.ready||e.setConnectionStatus(exports.ConnectionStatus.TIMEOUT),clearTimeout(s)}),t)}}}function ve(e,t){return n=>{var o,s,i,a,r;const{state:c}=e;b.RemoteCommunication(`[RemoteCommunication: handleKeysExchangedEvent()] context=${c.context} on commLayer.'keys_exchanged' channel=${c.channelId}`,n),(null===(s=null===(o=c.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===s?void 0:s.keysExchanged)&&e.setConnectionStatus(exports.ConnectionStatus.LINKED),function(e,t){var n,o,s,i;const{state:a}=e;b.RemoteCommunication(`[RemoteCommunication: setLastActiveDate()] channel=${a.channelId}`,t);const r={channelId:null!==(n=a.channelId)&&void 0!==n?n:"",validUntil:null!==(s=null===(o=a.channelConfig)||void 0===o?void 0:o.validUntil)&&void 0!==s?s:0,lastActive:t.getTime()};null===(i=a.storageManager)||void 0===i||i.persistChannelConfig(r)}(e,new Date),c.analytics&&c.channelId&&L({id:c.channelId,event:n.isOriginator?exports.TrackingEvents.CONNECTED:exports.TrackingEvents.CONNECTED_MOBILE,sdkVersion:c.sdkVersion,commLayer:t,commLayerVersion:H.version,walletVersion:null===(i=c.walletInfo)||void 0===i?void 0:i.version},c.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),c.isOriginator=n.isOriginator,n.isOriginator||(null===(a=c.communicationLayer)||void 0===a||a.sendMessage({type:exports.MessageType.READY}),c.ready=!0,c.paused=!1),n.isOriginator&&!c.originatorInfoSent&&(null===(r=c.communicationLayer)||void 0===r||r.sendMessage({type:exports.MessageType.ORIGINATOR_INFO,originatorInfo:c.originatorInfo,originator:c.originatorInfo}),c.originatorInfoSent=!0)}}function Ce(e,t){const{state:n}=t;if(b.RemoteCommunication(`[RemoteCommunication: onCommunicationLayerMessage()] context=${n.context} on 'message' typeof=${typeof e}`,e),t.state.ready=!0,n.isOriginator||e.type!==exports.MessageType.ORIGINATOR_INFO)if(n.isOriginator&&e.type===exports.MessageType.WALLET_INFO)!function(e,t){const{state:n}=e;n.walletInfo=t.walletInfo,n.paused=!1}(t,e);else{if(e.type===exports.MessageType.TERMINATE)!function(e){const{state:t}=e;t.isOriginator&&(Te({options:{terminate:!0,sendMessage:!1},instance:e}),console.debug(),e.emit(exports.EventType.TERMINATE))}(t);else if(e.type===exports.MessageType.PAUSE)!function(e){const{state:t}=e;t.paused=!0,e.setConnectionStatus(exports.ConnectionStatus.PAUSED)}(t);else if(e.type===exports.MessageType.READY&&n.isOriginator)!function(e){const{state:t}=e;e.setConnectionStatus(exports.ConnectionStatus.LINKED);const n=t.paused;t.paused=!1,e.emit(exports.EventType.CLIENTS_READY,{isOriginator:t.isOriginator,walletInfo:t.walletInfo}),n&&(t.authorized=!0,e.emit(exports.EventType.AUTHORIZED))}(t);else{if(e.type===exports.MessageType.OTP&&n.isOriginator)return void function(e,t){var n;const{state:o}=e;e.emit(exports.EventType.OTP,t.otpAnswer),1==="6.6".localeCompare((null===(n=o.walletInfo)||void 0===n?void 0:n.version)||"")&&(console.warn("RemoteCommunication::on 'otp' -- backward compatibility <6.6 -- triger eth_requestAccounts"),e.emit(exports.EventType.SDK_RPC_CALL,{method:j.ETH_REQUESTACCOUNTS,params:[]}))}(t,e);e.type===exports.MessageType.AUTHORIZED&&n.isOriginator&&function(e){const{state:t}=e;t.authorized=!0,e.emit(exports.EventType.AUTHORIZED)}(t)}t.emit(exports.EventType.MESSAGE,e)}else!function(e,t){var n;const{state:o}=e;null===(n=o.communicationLayer)||void 0===n||n.sendMessage({type:exports.MessageType.WALLET_INFO,walletInfo:o.walletInfo}),o.originatorInfo=t.originatorInfo||t.originator,e.emit(exports.EventType.CLIENTS_READY,{isOriginator:o.isOriginator,originatorInfo:o.originatorInfo}),o.paused=!1}(t,e)}function Se(e,t){var n,o;return l(this,void 0,void 0,(function*(){const{state:s}=e;b.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${s.context} paused=${s.paused} ready=${s.ready} authorized=${s.authorized} socket=${null===(n=s.communicationLayer)||void 0===n?void 0:n.isConnected()} clientsConnected=${s.clientsConnected} status=${s._connectionStatus}`,t),!s.paused&&s.ready&&(null===(o=s.communicationLayer)||void 0===o?void 0:o.isConnected())&&s.clientsConnected||(b.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${s.context} SKIP message waiting for MM mobile readiness.`),yield new Promise((t=>{e.once(exports.EventType.CLIENTS_READY,t)})),b.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${s.context} AFTER SKIP / READY -- sending pending message`));try{yield function(e,t){return l(this,void 0,void 0,(function*(){return new Promise((n=>{var o,s,i,a;const{state:r}=e;if(b.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${r.context} ready=${r.ready} authorized=${r.authorized} method=${t.method}`),1==="7.3".localeCompare((null===(o=r.walletInfo)||void 0===o?void 0:o.version)||""))return b.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] compatibility hack wallet version > ${null===(s=r.walletInfo)||void 0===s?void 0:s.version}`),null===(i=r.communicationLayer)||void 0===i||i.sendMessage(t),void n();!r.isOriginator||r.authorized?(null===(a=r.communicationLayer)||void 0===a||a.sendMessage(t),n()):e.once(exports.EventType.AUTHORIZED,(()=>{var e;b.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${r.context} AFTER SKIP / AUTHORIZED -- sending pending message`),null===(e=r.communicationLayer)||void 0===e||e.sendMessage(t),n()}))}))}))}(e,t)}catch(e){throw console.error(`[RemoteCommunication: sendMessage()] context=${s.context} ERROR`,e),e}}))}function xe(e){return t=>{let n=t;t.message&&(n=n.message),Ce(n,e)}}function fe(e){return()=>{const{state:t}=e;b.RemoteCommunication("[RemoteCommunication: handleSocketReconnectEvent()] on 'socket_reconnect' -- reset key exchange status / set ready to false"),t.ready=!1,t.authorized=!1,G(t),e.emitServiceStatusEvent()}}function ke(e){return()=>{const{state:t}=e;b.RemoteCommunication("[RemoteCommunication: handleSocketDisconnectedEvent()] on 'socket_Disconnected' set ready to false"),t.ready=!1}}function Te({options:e,instance:t}){var n,o,s,i,a,c;const{state:l}=t;b.RemoteCommunication(`[RemoteCommunication: disconnect()] channel=${l.channelId}`,e),l.ready=!1,l.paused=!1,(null==e?void 0:e.terminate)?(null===(n=l.storageManager)||void 0===n||n.terminate(null!==(o=l.channelId)&&void 0!==o?o:""),(null===(s=l.communicationLayer)||void 0===s?void 0:s.getKeyInfo().keysExchanged)&&(null==e?void 0:e.sendMessage)&&(null===(i=l.communicationLayer)||void 0===i||i.sendMessage({type:exports.MessageType.TERMINATE})),l.channelId=r.v4(),e.channelId=l.channelId,l.channelConfig=void 0,l.originatorConnectStarted=!1,null===(a=l.communicationLayer)||void 0===a||a.disconnect(e),t.setConnectionStatus(exports.ConnectionStatus.TERMINATED)):(null===(c=l.communicationLayer)||void 0===c||c.disconnect(e),t.setConnectionStatus(exports.ConnectionStatus.DISCONNECTED))}exports.CommunicationLayerPreference=void 0,(exports.CommunicationLayerPreference||(exports.CommunicationLayerPreference={})).SOCKET="socket",exports.PlatformType=void 0,(ue=exports.PlatformType||(exports.PlatformType={})).NonBrowser="nodejs",ue.MetaMaskMobileWebview="in-app-browser",ue.DesktopWeb="web-desktop",ue.MobileWeb="web-mobile",ue.ReactNative="react-native";class Ke extends a.EventEmitter2{constructor({platformType:e,communicationLayerPreference:t,otherPublicKey:n,reconnect:o,walletInfo:s,dappMetadata:i,transports:a,context:r,ecies:c,analytics:l=!1,storage:d,sdkVersion:u,communicationServerUrl:h=F,logging:p,autoConnect:m={timeout:3e3}}){super(),this.state={ready:!1,authorized:!1,isOriginator:!1,paused:!1,platformType:"metamask-mobile",analytics:!1,reconnection:!1,originatorInfoSent:!1,communicationServerUrl:F,context:"",clientsConnected:!1,sessionDuration:Y,originatorConnectStarted:!1,debug:!1,_connectionStatus:exports.ConnectionStatus.DISCONNECTED},this.state.otherPublicKey=n,this.state.dappMetadata=i,this.state.walletInfo=s,this.state.transports=a,this.state.platformType=e,this.state.analytics=l,this.state.isOriginator=!n,this.state.communicationServerUrl=h,this.state.context=r,this.state.sdkVersion=u,this.setMaxListeners(50),this.setConnectionStatus(exports.ConnectionStatus.DISCONNECTED),(null==d?void 0:d.duration)&&(this.state.sessionDuration=Y),this.state.storageOptions=d,this.state.autoConnectOptions=m,this.state.debug=!0===(null==p?void 0:p.remoteLayer),!0===(null==p?void 0:p.remoteLayer)&&_.enable("RemoteCommunication:Layer"),this.state.logging=p,(null==d?void 0:d.storageManager)&&(this.state.storageManager=d.storageManager),this.initCommunicationLayer({communicationLayerPreference:t,otherPublicKey:n,reconnect:o,ecies:c,communicationServerUrl:h}),this.emitServiceStatusEvent()}initCommunicationLayer({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:s=F}){return function({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:s=F,instance:i}){var a,r,c,l,d;const{state:u}=i;if(e!==exports.CommunicationLayerPreference.SOCKET)throw new Error("Invalid communication protocol");u.communicationLayer=new de({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,transports:u.transports,communicationServerUrl:s,context:u.context,ecies:o,logging:u.logging,remote:i});let h="undefined"!=typeof document&&document.URL||"",p="undefined"!=typeof document&&document.title||"";(null===(a=u.dappMetadata)||void 0===a?void 0:a.url)&&(h=u.dappMetadata.url),(null===(r=u.dappMetadata)||void 0===r?void 0:r.name)&&(p=u.dappMetadata.name);const m={url:h,title:p,source:null===(c=u.dappMetadata)||void 0===c?void 0:c.source,icon:(null===(l=u.dappMetadata)||void 0===l?void 0:l.iconUrl)||(null===(d=u.dappMetadata)||void 0===d?void 0:d.base64Icon),platform:u.platformType,apiVersion:H.version};u.originatorInfo=m;const g={[exports.EventType.AUTHORIZED]:pe(i),[exports.EventType.MESSAGE]:xe(i),[exports.EventType.CLIENTS_CONNECTED]:ge(i,e),[exports.EventType.KEYS_EXCHANGED]:ve(i,e),[exports.EventType.SOCKET_DISCONNECTED]:ke(i),[exports.EventType.SOCKET_RECONNECT]:fe(i),[exports.EventType.CLIENTS_DISCONNECTED]:ye(i,e),[exports.EventType.KEY_INFO]:()=>{i.emitServiceStatusEvent()},[exports.EventType.CHANNEL_CREATED]:me(i),[exports.EventType.CLIENTS_WAITING]:Ee(i),[exports.EventType.RPC_UPDATE]:e=>{i.emit(exports.EventType.RPC_UPDATE,e)}};for(const[e,t]of Object.entries(g))try{u.communicationLayer.on(e,t)}catch(t){console.error(`Error registering handler for ${e}:`,t)}}({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:s,instance:this})}originatorSessionConnect(){return l(this,void 0,void 0,(function*(){return yield function(e){var t,n,o;return l(this,void 0,void 0,(function*(){const{state:s}=e;if(!s.storageManager)return void b.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] no storage manager defined - skip");const i=yield s.storageManager.getPersistedChannelConfig(null!==(t=s.channelId)&&void 0!==t?t:"");if(b.RemoteCommunication(`[RemoteCommunication: originatorSessionConnect()] autoStarted=${s.originatorConnectStarted} channelConfig`,i),null===(n=s.communicationLayer)||void 0===n?void 0:n.isConnected())return b.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] socket already connected - skip"),i;if(i){if(i.validUntil>Date.now())return s.channelConfig=i,s.originatorConnectStarted=!0,s.channelId=null==i?void 0:i.channelId,s.reconnection=!0,null===(o=s.communicationLayer)||void 0===o||o.connectToChannel({channelId:i.channelId,isOriginator:!0}),i;b.RemoteCommunication("[RemoteCommunication: autoConnect()] Session has expired")}s.originatorConnectStarted=!1}))}(this)}))}generateChannelIdConnect(){return l(this,void 0,void 0,(function*(){return function(e){var t,n,o,s,i;if(!e.communicationLayer)throw new Error("communication layer not initialized");if(e.ready)throw new Error("Channel already connected");if(e.channelId&&(null===(t=e.communicationLayer)||void 0===t?void 0:t.isConnected()))return console.warn("Channel already exists -- interrupt generateChannelId",e.channelConfig),e.channelConfig={channelId:e.channelId,validUntil:Date.now()+e.sessionDuration},null===(n=e.storageManager)||void 0===n||n.persistChannelConfig(e.channelConfig),{channelId:e.channelId,pubKey:null===(s=null===(o=e.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===s?void 0:s.ecies.public};b.RemoteCommunication("[RemoteCommunication: generateChannelId()]"),G(e);const a=e.communicationLayer.createChannel();b.RemoteCommunication("[RemoteCommunication: generateChannelId()] channel created",a);const r={channelId:a.channelId,validUntil:Date.now()+e.sessionDuration};return e.channelId=a.channelId,e.channelConfig=r,null===(i=e.storageManager)||void 0===i||i.persistChannelConfig(r),{channelId:e.channelId,pubKey:a.pubKey}}(this.state)}))}clean(){return G(this.state)}connectToChannel(e,t){return function({channelId:e,withKeyExchange:t,state:n}){var o,s,i;if(!r.validate(e))throw b.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} invalid channel channelId=${e}`),new Error(`Invalid channel ${e}`);if(b.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} channelId=${e}`),null===(o=n.communicationLayer)||void 0===o?void 0:o.isConnected())return void b.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} already connected - interrupt connection.`);n.channelId=e,null===(s=n.communicationLayer)||void 0===s||s.connectToChannel({channelId:e,withKeyExchange:t});const a={channelId:e,validUntil:Date.now()+n.sessionDuration};n.channelConfig=a,null===(i=n.storageManager)||void 0===i||i.persistChannelConfig(a)}({channelId:e,withKeyExchange:t,state:this.state})}sendMessage(e){return Se(this,e)}testStorage(){return l(this,void 0,void 0,(function*(){return function(e){var t,n;return l(this,void 0,void 0,(function*(){const o=yield null===(t=e.storageManager)||void 0===t?void 0:t.getPersistedChannelConfig(null!==(n=e.channelId)&&void 0!==n?n:"");b.RemoteCommunication("[RemoteCommunication: testStorage()] res",o)}))}(this.state)}))}getChannelConfig(){return this.state.channelConfig}isReady(){return this.state.ready}isConnected(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.isConnected()}isAuthorized(){return this.state.authorized}isPaused(){return this.state.paused}getCommunicationLayer(){return this.state.communicationLayer}ping(){var e;b.RemoteCommunication(`[RemoteCommunication: ping()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.ping()}keyCheck(){var e;b.RemoteCommunication(`[RemoteCommunication: keyCheck()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.keyCheck()}setConnectionStatus(e){this.state._connectionStatus!==e&&(this.state._connectionStatus=e,this.emit(exports.EventType.CONNECTION_STATUS,e),this.emitServiceStatusEvent())}emitServiceStatusEvent(){this.emit(exports.EventType.SERVICE_STATUS,this.getServiceStatus())}getConnectionStatus(){return this.state._connectionStatus}getServiceStatus(){return{originatorInfo:this.state.originatorInfo,keyInfo:this.getKeyInfo(),connectionStatus:this.state._connectionStatus,channelConfig:this.state.channelConfig,channelId:this.state.channelId}}getKeyInfo(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getKeyInfo()}resetKeys(){var e;null===(e=this.state.communicationLayer)||void 0===e||e.resetKeys()}setOtherPublicKey(e){var t;const n=null===(t=this.state.communicationLayer)||void 0===t?void 0:t.getKeyExchange();if(!n)throw new Error("KeyExchange is not initialized.");n.getOtherPublicKey()!==e&&n.setOtherPublicKey(e)}pause(){var e;b.RemoteCommunication(`[RemoteCommunication: pause()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.pause(),this.setConnectionStatus(exports.ConnectionStatus.PAUSED)}getVersion(){return H.version}resume(){return function(e){var t;const{state:n}=e;b.RemoteCommunication(`[RemoteCommunication: resume()] channel=${n.channelId}`),null===(t=n.communicationLayer)||void 0===t||t.resume(),e.setConnectionStatus(exports.ConnectionStatus.LINKED)}(this)}getChannelId(){return this.state.channelId}getRPCMethodTracker(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getRPCMethodTracker()}disconnect(e){return Te({options:e,instance:this})}}exports.AutoConnectType=void 0,(he=exports.AutoConnectType||(exports.AutoConnectType={})).RENEW="renew",he.LINK="link",exports.DEFAULT_SERVER_URL=F,exports.ECIES=P,exports.RemoteCommunication=Ke,exports.SendAnalytics=L,exports.SocketService=de;
//# sourceMappingURL=metamask-sdk-communication-layer.js.map

@@ -1,2 +0,2 @@

export declare const DEFAULT_SERVER_URL = "https://metamask-sdk-socket.metafi.codefi.network/";
export declare const DEFAULT_SERVER_URL = "https://metamask-sdk.api.cx.metamask.io/";
export declare const DEFAULT_SOCKET_TRANSPORTS: string[];

@@ -3,0 +3,0 @@ export declare const MIN_IN_MS: number;

@@ -1,2 +0,2 @@

import e from"cross-fetch";import t from"tty";import n from"util";import o from"os";import{Buffer as i}from"buffer";import{PrivateKey as s,encrypt as a,decrypt as c}from"eciesjs";import{EventEmitter2 as r}from"eventemitter2";import{validate as l,v4 as d}from"uuid";import{io as u}from"socket.io-client";function h(e,t,n,o){return new(n||(n=Promise))((function(i,s){function a(e){try{r(o.next(e))}catch(e){s(e)}}function c(e){try{r(o.throw(e))}catch(e){s(e)}}function r(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,c)}r((o=o.apply(e,t||[])).next())}))}function m(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var g,E,v,y,p,C={exports:{}},S={exports:{}};function f(){if(E)return g;E=1;var e=1e3,t=60*e,n=60*t,o=24*n,i=7*o,s=365.25*o;function a(e,t,n,o){var i=t>=1.5*n;return Math.round(e/n)+" "+o+(i?"s":"")}return g=function(c,r){r=r||{};var l=typeof c;if("string"===l&&c.length>0)return function(a){if((a=String(a)).length>100)return;var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!c)return;var r=parseFloat(c[1]);switch((c[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*s;case"weeks":case"week":case"w":return r*i;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*n;case"minutes":case"minute":case"mins":case"min":case"m":return r*t;case"seconds":case"second":case"secs":case"sec":case"s":return r*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(c);if("number"===l&&isFinite(c))return r.long?function(i){var s=Math.abs(i);if(s>=o)return a(i,s,o,"day");if(s>=n)return a(i,s,n,"hour");if(s>=t)return a(i,s,t,"minute");if(s>=e)return a(i,s,e,"second");return i+" ms"}(c):function(i){var s=Math.abs(i);if(s>=o)return Math.round(i/o)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))}}function k(){if(y)return v;return y=1,v=function(e){function t(e){let o,i,s,a=null;function c(...e){if(!c.enabled)return;const n=c,i=Number(new Date),s=i-(o||i);n.diff=s,n.prev=o,n.curr=i,o=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((o,i)=>{if("%%"===o)return"%";a++;const s=t.formatters[i];if("function"==typeof s){const t=e[a];o=s.call(n,t),e.splice(a,1),a--}return o})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return c.namespace=e,c.useColors=t.useColors(),c.color=t.selectColor(e),c.extend=n,c.destroy=t.destroy,Object.defineProperty(c,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{a=e}}),"function"==typeof t.init&&t.init(c),c}function n(e,n){const o=t(this.namespace+(void 0===n?":":n)+e);return o.log=this.log,o}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const o=("string"==typeof e?e:"").split(/[\s,]+/),i=o.length;for(n=0;n<i;n++)o[n]&&("-"===(e=o[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,o;for(n=0,o=t.skips.length;n<o;n++)if(t.skips[n].test(e))return!1;for(n=0,o=t.names.length;n<o;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=f(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},v}var x,I,_,K,O,A={exports:{}};function N(){return I?x:(I=1,x=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",o=t.indexOf(n+e),i=t.indexOf("--");return-1!==o&&(-1===i||o<i)})}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?C.exports=(p||(p=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(o++,"%c"===e&&(i=o))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=k()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(S,S.exports)),S.exports):C.exports=(O||(O=1,function(e,i){const s=t,a=n;i.init=function(e){e.inspectOpts={};const t=Object.keys(i.inspectOpts);for(let n=0;n<t.length;n++)e.inspectOpts[t[n]]=i.inspectOpts[t[n]]},i.log=function(...e){return process.stderr.write(a.format(...e)+"\n")},i.formatArgs=function(t){const{namespace:n,useColors:o}=this;if(o){const o=this.color,i="[3"+(o<8?o:"8;5;"+o),s=` ${i};1m${n} `;t[0]=s+t[0].split("\n").join("\n"+s),t.push(i+"m+"+e.exports.humanize(this.diff)+"")}else t[0]=(i.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+n+" "+t[0]},i.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},i.load=function(){return process.env.DEBUG},i.useColors=function(){return"colors"in i.inspectOpts?Boolean(i.inspectOpts.colors):s.isatty(process.stderr.fd)},i.destroy=a.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),i.colors=[6,2,3,4,5,1];try{const e=function(){if(K)return _;K=1;const e=o,n=t,i=N(),{env:s}=process;let a;function c(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function r(t,n){if(0===a)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(t&&!n&&void 0===a)return 0;const o=a||0;if("dumb"===s.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in s)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in s))||"codeship"===s.CI_NAME?1:o;if("TEAMCITY_VERSION"in s)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(s.TEAMCITY_VERSION)?1:0;if("truecolor"===s.COLORTERM)return 3;if("TERM_PROGRAM"in s){const e=parseInt((s.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(s.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(s.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(s.TERM)||"COLORTERM"in s?1:o}return i("no-color")||i("no-colors")||i("color=false")||i("color=never")?a=0:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(a=1),"FORCE_COLOR"in s&&(a="true"===s.FORCE_COLOR?1:"false"===s.FORCE_COLOR?0:0===s.FORCE_COLOR.length?1:Math.min(parseInt(s.FORCE_COLOR,10),3)),_={supportsColor:function(e){return c(r(e,e&&e.isTTY))},stdout:c(r(!0,n.isatty(1))),stderr:c(r(!0,n.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(i.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}i.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let o=process.env[t];return o=!!/^(yes|on|true|enabled)$/i.test(o)||!/^(no|off|false|disabled)$/i.test(o)&&("null"===o?null:Number(o)),e[n]=o,e}),{}),e.exports=k()(i);const{formatters:c}=e.exports;c.o=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},c.O=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts)}}(A,A.exports)),A.exports);var R=m(C.exports);const T=R("KeyExchange:Layer"),b=R("SocketService:Layer"),w=R("Ecies:Layer"),D=R("RemoteCommunication:Layer");T.color="##95c44e",b.color="#f638d7",w.color="#465b9c",D.color="#47a2be";const $={KeyExchange:T,SocketService:b,Ecies:w,RemoteCommunication:D};let M,L=[],P=[];function H(t){return h(this,void 0,void 0,(function*(){if(!M||!t)return;!function(){const e=P;P=L,L=e}();const n=M.endsWith("/")?`${M}debug`:`${M}/debug`,o=Object.assign({},t);if(delete o.params,t.params)for(const[e,n]of Object.entries(t.params))o[e]=n;const i=JSON.stringify(o);$.RemoteCommunication(`[sendBufferedEvents] Sending ${L.length} analytics events to ${n}`);try{const t=yield e(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:i}),o=yield t.text();$.RemoteCommunication(`[sendBufferedEvents] Response: ${o}`),L.length=0}catch(e){console.warn("Error sending analytics",e)}}))}const F=(e,t)=>h(void 0,void 0,void 0,(function*(){var n;M=t,n=e,P.push(n),H(e).catch((()=>{}))}));class Y{constructor(e){this.enabled=!0,(null==e?void 0:e.debug)&&R.enable("Ecies:Layer"),(null==e?void 0:e.pkey)?this.ecies=s.fromHex(e.pkey):this.ecies=new s,$.Ecies("[ECIES constructor()] initialized secret: ",this.ecies.toHex()),$.Ecies("[ECIES constructor()] initialized public: ",this.ecies.publicKey.toHex()),$.Ecies("[ECIES constructor()] init with",this)}generateECIES(){this.ecies=new s}getPublicKey(){return this.ecies.publicKey.toHex()}encrypt(e,t){let n=e;if(this.enabled)try{$.Ecies("[ECIES: encrypt()] using otherPublicKey",t);const o=i.from(e),s=a(t,o);n=i.from(s).toString("base64")}catch(n){throw $.Ecies("[ECIES: encrypt()] error encrypt:",n),$.Ecies("[ECIES: encrypt()] private: ",this.ecies.toHex()),$.Ecies("[ECIES: encrypt()] data: ",e),$.Ecies("[ECIES: encrypt()] otherkey: ",t),n}return n}decrypt(e){let t=e;if(this.enabled)try{$.Ecies("[ECIES: decrypt()] using privateKey",this.ecies.toHex());const n=i.from(e.toString(),"base64");t=c(this.ecies.toHex(),n).toString()}catch(t){throw $.Ecies("[ECIES: decrypt()] error decrypt",t),$.Ecies("[ECIES: decrypt()] private: ",this.ecies.toHex()),$.Ecies("[ECIES: decrypt()] encryptedData: ",e),t}return t}getKeyInfo(){return{private:this.ecies.toHex(),public:this.ecies.publicKey.toHex()}}toString(){$.Ecies("[ECIES: toString()]",this.getKeyInfo())}}var U={name:"@metamask/sdk-communication-layer",version:"0.17.0",description:"",homepage:"https://github.com/MetaMask/metamask-sdk#readme",bugs:{url:"https://github.com/MetaMask/metamask-sdk/issues"},repository:{type:"git",url:"https://github.com/MetaMask/metamask-sdk.git",directory:"packages/sdk-communication-layer"},main:"dist/node/cjs/metamask-sdk-communication-layer.js",unpkg:"dist/browser/umd/metamask-sdk-communication-layer.js",module:"dist/node/es/metamask-sdk-communication-layer.js",browser:"dist/browser/es/metamask-sdk-communication-layer.js","react-native":"dist/react-native/es/metamask-sdk-communication-layer.js",types:"dist/browser/es/src/index.d.ts",files:["/dist"],scripts:{build:"rimraf dist && rollup -c --bundleConfigAsCjs","build:tsc":"tsc","build:dev":"rimraf dist && NODE_ENV=dev rollup -c --bundleConfigAsCjs","build:post-tsc":"echo 'N/A'","build:pre-tsc":"echo 'N/A'",size:"size-limit",clean:"rimraf ./dist",lint:"yarn lint:eslint && yarn lint:misc --check","lint:changelog":"../../scripts/validate-changelog.sh @metamask/sdk-communication-layer","lint:eslint":"eslint . --cache --ext js,ts","lint:fix":"yarn lint:eslint --fix && yarn lint:misc --write","lint:misc":"prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path ../../.gitignore","prepare-manifest:preview":"../../scripts/prepare-preview-manifest.sh","publish:preview":"yarn npm publish --tag preview",prepack:"../../scripts/prepack.sh",reset:"yarn clean && rimraf ./node_modules/",test:"jest","test:coverage":"jest --coverage","test:ci":"jest --coverage --passWithNoTests --setupFilesAfterEnv ./jest-preload.js","test:dev":"jest",watch:"rollup -c --bundleConfigAsCjs -w"},dependencies:{bufferutil:"^4.0.8","date-fns":"^2.29.3",debug:"^4.3.4","utf-8-validate":"^6.0.3",uuid:"^8.3.2"},devDependencies:{"@jest/globals":"^29.3.1","@lavamoat/allow-scripts":"^2.3.1","@metamask/auto-changelog":"3.1.0","@metamask/eslint-config":"^6.0.0","@metamask/eslint-config-nodejs":"^6.0.0","@metamask/eslint-config-typescript":"^6.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.0.2","@rollup/plugin-terser":"^0.4.1","@size-limit/preset-big-lib":"^11.0.2","@types/jest":"^29.2.4","@types/node":"^20.1.3","@types/uuid":"^9.0.0","@typescript-eslint/eslint-plugin":"^4.26.0","@typescript-eslint/parser":"^4.26.0","cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eslint:"^7.30.0","eslint-config-prettier":"^8.3.0","eslint-plugin-import":"^2.23.4","eslint-plugin-jest":"^24.4.0","eslint-plugin-jsdoc":"^36.1.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.4.0",eventemitter2:"^6.4.7",jest:"^29.3.1",prettier:"^2.3.0",rimraf:"^3.0.2",rollup:"^3.21.7","rollup-plugin-jscc":"^2.0.0","rollup-plugin-natives":"^0.7.5","rollup-plugin-node-builtins":"^2.1.2","rollup-plugin-node-globals":"^1.4.0","rollup-plugin-peer-deps-external":"^2.2.4","rollup-plugin-sizes":"^1.0.6","rollup-plugin-typescript2":"^0.31.2","rollup-plugin-visualizer":"^5.9.2","size-limit":"^11.0.2","socket.io-client":"^4.5.1","stream-browserify":"^3.0.0","ts-jest":"^29.0.3","ts-node":"^10.9.1",typescript:"^4.3.2"},peerDependencies:{"cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eventemitter2:"^6.4.7","readable-stream":"^3.6.2","socket.io-client":"^4.5.1"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},lavamoat:{allowScripts:{"@lavamoat/preinstall-always-fail":!1,canvas:!0,"eciesjs>secp256k1":!1,"socket.io-client>engine.io-client>ws>bufferutil":!1,"socket.io-client>engine.io-client>ws>utf-8-validate":!1,bufferutil:!1,"utf-8-validate":!1}}};const j="https://metamask-sdk-socket.metafi.codefi.network/",G=["websocket"],z=6048e5,V={METAMASK_GETPROVIDERSTATE:"metamask_getProviderState",ETH_REQUESTACCOUNTS:"eth_requestAccounts"};function W(e){const{context:t}=e;$.RemoteCommunication(`[RemoteCommunication: clean()] context=${t}`),e.channelConfig=void 0,e.ready=!1,e.originatorConnectStarted=!1}var B,J,Z,X,Q;!function(e){e.DISCONNECTED="disconnected",e.WAITING="waiting",e.TIMEOUT="timeout",e.LINKED="linked",e.PAUSED="paused",e.TERMINATED="terminated"}(B||(B={})),function(e){e.KEY_INFO="key_info",e.SERVICE_STATUS="service_status",e.PROVIDER_UPDATE="provider_update",e.RPC_UPDATE="rpc_update",e.KEYS_EXCHANGED="keys_exchanged",e.JOIN_CHANNEL="join_channel",e.CHANNEL_CREATED="channel_created",e.CLIENTS_CONNECTED="clients_connected",e.CLIENTS_DISCONNECTED="clients_disconnected",e.CLIENTS_WAITING="clients_waiting",e.CLIENTS_READY="clients_ready",e.SOCKET_DISCONNECTED="socket_disconnected",e.SOCKET_RECONNECT="socket_reconnect",e.OTP="otp",e.SDK_RPC_CALL="sdk_rpc_call",e.AUTHORIZED="authorized",e.CONNECTION_STATUS="connection_status",e.MESSAGE="message",e.TERMINATE="terminate"}(J||(J={})),function(e){e.KEY_EXCHANGE="key_exchange"}(Z||(Z={})),function(e){e.KEY_HANDSHAKE_START="key_handshake_start",e.KEY_HANDSHAKE_CHECK="key_handshake_check",e.KEY_HANDSHAKE_SYN="key_handshake_SYN",e.KEY_HANDSHAKE_SYNACK="key_handshake_SYNACK",e.KEY_HANDSHAKE_ACK="key_handshake_ACK",e.KEY_HANDSHAKE_NONE="none"}(X||(X={}));class q extends r{constructor({communicationLayer:e,otherPublicKey:t,context:n,ecies:o,logging:i}){super(),this.keysExchanged=!1,this.step=X.KEY_HANDSHAKE_NONE,this.debug=!1,this.context=n,this.myECIES=new Y(Object.assign(Object.assign({},o),{debug:null==i?void 0:i.eciesLayer})),this.communicationLayer=e,this.myPublicKey=this.myECIES.getPublicKey(),this.debug=!0===(null==i?void 0:i.keyExchangeLayer),(null==i?void 0:i.keyExchangeLayer)&&R.enable("KeyExchange:Layer"),t&&this.setOtherPublicKey(t),this.communicationLayer.on(Z.KEY_EXCHANGE,this.onKeyExchangeMessage.bind(this))}onKeyExchangeMessage(e){$.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} keysExchanged=${this.keysExchanged}`,e);const{message:t}=e;this.keysExchanged&&$.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} received handshake while already exchanged. step=${this.step} otherPubKey=${this.otherPublicKey}`),this.emit(J.KEY_INFO,t.type),t.type===X.KEY_HANDSHAKE_SYN?(this.checkStep([X.KEY_HANDSHAKE_NONE,X.KEY_HANDSHAKE_ACK]),$.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYN",t),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_SYNACK,pubkey:this.myPublicKey}),this.setStep(X.KEY_HANDSHAKE_ACK)):t.type===X.KEY_HANDSHAKE_SYNACK?(this.checkStep([X.KEY_HANDSHAKE_SYNACK,X.KEY_HANDSHAKE_ACK,X.KEY_HANDSHAKE_NONE]),$.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYNACK"),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_ACK}),this.keysExchanged=!0,this.setStep(X.KEY_HANDSHAKE_ACK),this.emit(J.KEYS_EXCHANGED)):t.type===X.KEY_HANDSHAKE_ACK&&($.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_ACK set keysExchanged to true!"),this.checkStep([X.KEY_HANDSHAKE_ACK,X.KEY_HANDSHAKE_NONE]),this.keysExchanged=!0,this.setStep(X.KEY_HANDSHAKE_ACK),this.emit(J.KEYS_EXCHANGED))}resetKeys(e){this.clean(),this.myECIES=new Y(e)}clean(){$.KeyExchange(`[KeyExchange: clean()] context=${this.context} reset handshake state`),this.setStep(X.KEY_HANDSHAKE_NONE),this.emit(J.KEY_INFO,this.step),this.keysExchanged=!1}start({isOriginator:e,force:t}){$.KeyExchange(`[KeyExchange: start()] context=${this.context} isOriginator=${e} step=${this.step} force=${t} keysExchanged=${this.keysExchanged}`),e?!(this.keysExchanged||this.step!==X.KEY_HANDSHAKE_NONE&&this.step!==X.KEY_HANDSHAKE_SYNACK)||t?($.KeyExchange(`[KeyExchange: start()] context=${this.context} -- start key exchange (force=${t}) -- step=${this.step}`,this.step),this.clean(),this.setStep(X.KEY_HANDSHAKE_SYNACK),this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_SYN,pubkey:this.myPublicKey})):$.KeyExchange(`[KeyExchange: start()] context=${this.context} -- key exchange already ${this.keysExchanged?"done":"in progress"} -- aborted.`,this.step):this.keysExchanged&&!0!==t?$.KeyExchange("[KeyExchange: start()] don't send KEY_HANDSHAKE_START -- exchange already done."):(this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_START}),this.clean())}setStep(e){this.step=e,this.emit(J.KEY_INFO,e)}checkStep(e){e.length>0&&-1===e.indexOf(this.step.toString())&&console.warn(`[KeyExchange: checkStep()] Wrong Step "${this.step}" not within ${e}`)}setKeysExchanged(e){this.keysExchanged=e}areKeysExchanged(){return this.keysExchanged}getMyPublicKey(){return this.myPublicKey}getOtherPublicKey(){return this.otherPublicKey}setOtherPublicKey(e){$.KeyExchange("[KeyExchange: setOtherPubKey()]",e),this.otherPublicKey=e}encryptMessage(e){if(!this.otherPublicKey)throw new Error("encryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.encrypt(e,this.otherPublicKey)}decryptMessage(e){if(!this.otherPublicKey)throw new Error("decryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.decrypt(e)}getKeyInfo(){return{ecies:Object.assign(Object.assign({},this.myECIES.getKeyInfo()),{otherPubKey:this.otherPublicKey}),step:this.step,keysExchanged:this.areKeysExchanged()}}toString(){const e={keyInfo:this.getKeyInfo(),keysExchanged:this.keysExchanged,step:this.step};return JSON.stringify(e)}}!function(e){e.TERMINATE="terminate",e.ANSWER="answer",e.OFFER="offer",e.CANDIDATE="candidate",e.JSONRPC="jsonrpc",e.WALLET_INFO="wallet_info",e.ORIGINATOR_INFO="originator_info",e.PAUSE="pause",e.OTP="otp",e.AUTHORIZED="authorized",e.PING="ping",e.READY="ready"}(Q||(Q={}));const ee=e=>new Promise((t=>{setTimeout(t,e)})),te=(e,t,n=200)=>h(void 0,void 0,void 0,(function*(){let o;const i=Date.now();let s=!1;for(;!s;){if(s=Date.now()-i>3e5,o=t[e],void 0!==o.elapsedTime)return o;yield ee(n)}throw new Error(`RPC ${e} timed out`)})),ne=({rpcId:e,instance:t})=>h(void 0,void 0,void 0,(function*(){for(;t.state.lastRpcId===e||void 0===t.state.lastRpcId;)yield ee(200);return t.state.lastRpcId})),oe=e=>h(void 0,void 0,void 0,(function*(){var t,n,o,i,s;return $.SocketService(`[SocketService: reconnectSocket()] instance.state.socket?.connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} trying to reconnect after socketio disconnection`,e),yield ee(200),(null===(n=e.state.socket)||void 0===n?void 0:n.connected)||(e.state.resumed=!0,null===(o=e.state.socket)||void 0===o||o.connect(),e.emit(J.SOCKET_RECONNECT),null===(i=e.state.socket)||void 0===i||i.emit(J.JOIN_CHANNEL,e.state.channelId,`${e.state.context}connect_again`)),yield ee(100),null===(s=e.state.socket)||void 0===s?void 0:s.connected}));function ie(e){return t=>{$.SocketService(`[SocketService: handleDisconnect()] on 'disconnect' manualDisconnect=${e.state.manualDisconnect}`,t),e.state.manualDisconnect||(e.emit(J.SOCKET_DISCONNECTED),function(e){"undefined"!=typeof window&&"undefined"!=typeof document&&($.SocketService(`[SocketService: checkFocusAndReconnect()] hasFocus=${document.hasFocus()}`,e),document.hasFocus()?oe(e).then((t=>{$.SocketService(`SocketService::checkFocus reconnectSocket success=${t}`,e)})).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)})):window.addEventListener("focus",(()=>{oe(e).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)}))}),{once:!0}))}(e))}}const se=[{event:"clients_connected",handler:function(e,t){return n=>h(this,void 0,void 0,(function*(){var n,o,i,s,a,c,r,l;$.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected-${t}' resumed=${e.state.resumed} clientsPaused=${e.state.clientsPaused} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()} isOriginator=${e.state.isOriginator}`),e.emit(J.CLIENTS_CONNECTED,{isOriginator:e.state.isOriginator,keysExchanged:null===(o=e.state.keyExchange)||void 0===o?void 0:o.areKeysExchanged(),context:e.state.context}),e.state.resumed?(e.state.isOriginator||($.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} 'clients_connected' / keysExchanged=${null===(i=e.state.keyExchange)||void 0===i?void 0:i.areKeysExchanged()} -- backward compatibility`),null===(s=e.state.keyExchange)||void 0===s||s.start({isOriginator:null!==(a=e.state.isOriginator)&&void 0!==a&&a})),e.state.resumed=!1):e.state.clientsPaused?$.SocketService("[SocketService: handleClientsConnected()] 'clients_connected' skip sending originatorInfo on pause"):e.state.isOriginator||($.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected' / keysExchanged=${null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged()} -- backward compatibility`),null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l,force:!0})),e.state.clientsConnected=!0,e.state.clientsPaused=!1}))}},{event:"channel_created",handler:function(e,t){return n=>{$.SocketService(`[SocketService: handleChannelCreated()] context=${e.state.context} on 'channel_created-${t}'`,n),e.emit(J.CHANNEL_CREATED,n)}}},{event:"clients_disconnected",handler:function(e,t){return()=>{var n;e.state.clientsConnected=!1,$.SocketService(`[SocketService: handlesClientsDisconnected()] context=${e.state.context} on 'clients_disconnected-${t}'`),e.state.isOriginator&&!e.state.clientsPaused&&(null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.emit(J.CLIENTS_DISCONNECTED,t)}}},{event:"message",handler:function(e,t){return({id:n,message:o,error:i})=>{var s,a,c,r,l,d,u,h,m,g,E,v,y,p,C;if($.SocketService(`[SocketService handleMessage()] context=${e.state.context} on 'message' ${t} keysExchanged=${null===(s=e.state.keyExchange)||void 0===s?void 0:s.areKeysExchanged()}`,o),i)throw $.SocketService(`\n [SocketService handleMessage()] context=${e.state.context}::on 'message' error=${i}`),new Error(i);try{!function(e,t){if(t!==e.channelId)throw e.debug&&console.error(`Wrong id ${t} - should be ${e.channelId}`),new Error("Wrong id")}(e.state,n)}catch(e){return void console.error("ignore message --- wrong id ",o)}if(e.state.isOriginator&&(null==o?void 0:o.type)===X.KEY_HANDSHAKE_START)return $.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received HANDSHAKE_START isOriginator=${e.state.isOriginator}`,o),void(null===(a=e.state.keyExchange)||void 0===a||a.start({isOriginator:null!==(c=e.state.isOriginator)&&void 0!==c&&c,force:!0}));if((null==o?void 0:o.type)===Q.PING)return $.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' ping `),void e.emit(J.MESSAGE,{message:{type:"ping"}});if($.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' originator=${e.state.isOriginator}, type=${null==o?void 0:o.type}, keysExchanged=${null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged()}`),null===(l=null==o?void 0:o.type)||void 0===l?void 0:l.startsWith("key_handshake"))return $.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' emit KEY_EXCHANGE`,o),void e.emit(Z.KEY_EXCHANGE,{message:o,context:e.state.context});if(null===(d=e.state.keyExchange)||void 0===d?void 0:d.areKeysExchanged()){if(-1!==o.toString().indexOf("type"))return console.warn("[SocketService handleMessage() ::on 'message' received non encrypted unkwown message"),void e.emit(J.MESSAGE,o)}else{let t=!1;try{null===(u=e.state.keyExchange)||void 0===u||u.decryptMessage(o),t=!0}catch(e){}if(!t)return e.state.isOriginator?null===(m=e.state.keyExchange)||void 0===m||m.start({isOriginator:null!==(g=e.state.isOriginator)&&void 0!==g&&g}):e.sendMessage({type:X.KEY_HANDSHAKE_START}),void console.warn(`Message ignored because invalid key exchange status. step=${null===(E=e.state.keyExchange)||void 0===E?void 0:E.getKeyInfo().step}`,null===(v=e.state.keyExchange)||void 0===v?void 0:v.getKeyInfo(),o);console.warn("Invalid key exchange status detected --- updating it."),null===(h=e.state.keyExchange)||void 0===h||h.setKeysExchanged(!0)}const S=null===(y=e.state.keyExchange)||void 0===y?void 0:y.decryptMessage(o),f=JSON.parse(null!=S?S:"{}");if((null==f?void 0:f.type)===Q.PAUSE?e.state.clientsPaused=!0:e.state.clientsPaused=!1,e.state.isOriginator&&f.data){const t=f.data,n=e.state.rpcMethodTracker[t.id];if(n){const o=Date.now()-n.timestamp;$.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received answer for id=${t.id} method=${n.method} responseTime=${o}`,f);const i=Object.assign(Object.assign({},n),{result:t.result,error:t.error?{code:null===(p=t.error)||void 0===p?void 0:p.code,message:null===(C=t.error)||void 0===C?void 0:C.message}:void 0,elapsedTime:o});e.state.rpcMethodTracker[t.id]=i,e.emit(J.RPC_UPDATE,i),$.SocketService("[SocketService handleMessage()] HACK (wallet <7.3) update rpcMethodTracker",i),e.emit(J.AUTHORIZED)}}e.emit(J.MESSAGE,{message:f})}}},{event:"clients_waiting_to_join",handler:function(e,t){return n=>{$.SocketService(`[SocketService: handleClientsWaitingToJoin()] context=${e.state.context} on 'clients_waiting_to_join-${t}'`,n),e.emit(J.CLIENTS_WAITING,n)}}}],ae=[{event:J.KEY_INFO,handler:function(e){return t=>{$.SocketService("[SocketService: handleKeyInfo()] on 'KEY_INFO'",t),e.emit(J.KEY_INFO,t)}}},{event:J.KEYS_EXCHANGED,handler:function(e){return()=>{var t,n;$.SocketService(`[SocketService: handleKeysExchanged()] on 'keys_exchanged' keyschanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.emit(J.KEYS_EXCHANGED,{keysExchanged:null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged(),isOriginator:e.state.isOriginator});const o={keyInfo:e.getKeyInfo()};e.emit(J.SERVICE_STATUS,o)}}}];function ce(e,t){$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} setting socket listeners for channel ${t}...`);const{socket:n}=e.state,{keyExchange:o}=e.state;e.state.setupChannelListeners&&console.warn(`[SocketService: setupChannelListener()] context=${e.state.context} socket listeners already set up for channel ${t}`),n&&e.state.isOriginator&&(e.state.debug&&(null==n||n.io.on("error",(t=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=error`,t)})),null==n||n.io.on("reconnect",(t=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect`,t)})),null==n||n.io.on("reconnect_error",(t=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_error`,t)})),null==n||n.io.on("reconnect_failed",(()=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_failed`)})),null==n||n.io.on("ping",(()=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=ping`)}))),null==n||n.on("disconnect",(t=>($.SocketService(`[SocketService: setupChannelListener()] on 'disconnect' -- MetaMaskSDK socket disconnected '${t}' begin recovery...`),ie(e)(t))))),se.forEach((({event:o,handler:i})=>{const s=`${o}-${t}`;null==n||n.on(s,i(e,t))})),ae.forEach((({event:t,handler:n})=>{null==o||o.on(t,n(e))})),e.state.setupChannelListeners=!0}var re;!function(e){e.REQUEST="sdk_connect_request_started",e.REQUEST_MOBILE="sdk_connect_request_started_mobile",e.RECONNECT="sdk_reconnect_request_started",e.CONNECTED="sdk_connection_established",e.CONNECTED_MOBILE="sdk_connection_established_mobile",e.AUTHORIZED="sdk_connection_authorized",e.REJECTED="sdk_connection_rejected",e.TERMINATED="sdk_connection_terminated",e.DISCONNECTED="sdk_disconnected",e.SDK_USE_EXTENSION="sdk_use_extension",e.SDK_RPC_REQUEST="sdk_rpc_request",e.SDK_EXTENSION_UTILIZED="sdk_extension_utilized",e.SDK_USE_INAPP_BROWSER="sdk_use_inapp_browser"}(re||(re={}));const le="SDK_CONNECTION_ISSUE";var de;!function(e){e.RPC_CHECK="rpcCheck",e.SKIPPED_RPC="skippedRpc"}(de||(de={}));const ue=["eth_sendTransaction","eth_signTypedData","eth_signTransaction","wallet_requestPermissions","wallet_switchEthereumChain","eth_signTypedData_v3","eth_signTypedData_v4","metamask_connectSign","metamask_connectWith","metamask_batch"].map((e=>e.toLowerCase()));function he(e,t){var n,o,i,s;if(!e.state.channelId)throw new Error("Create a channel first");$.SocketService(`[SocketService: handleSendMessage()] context=${e.state.context} areKeysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`,t);(null===(o=null==t?void 0:t.type)||void 0===o?void 0:o.startsWith("key_handshake"))?function(e,t){var n;$.SocketService(`[SocketService: handleKeyHandshake()] context=${e.state.context}`,t),null===(n=e.state.socket)||void 0===n||n.emit(J.MESSAGE,{id:e.state.channelId,context:e.state.context,message:t})}(e,t):(!function(e,t){var n;if(!(null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()))throw $.SocketService(`[SocketService: validateKeyExchange()] context=${e.state.context} ERROR keys not exchanged`,t),new Error("Keys not exchanged BBB")}(e,t),function(e,t){var n;const o=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"",i=null==t?void 0:t.id;e.state.isOriginator&&i&&(e.state.rpcMethodTracker[i]={id:i,timestamp:Date.now(),method:o},e.emit(J.RPC_UPDATE,e.state.rpcMethodTracker[i]))}(e,t),function(e,t){var n,o;const i=null===(n=e.state.keyExchange)||void 0===n?void 0:n.encryptMessage(JSON.stringify(t)),s={id:e.state.channelId,context:e.state.context,message:i,plaintext:e.state.hasPlaintext?JSON.stringify(t):void 0};$.SocketService(`[SocketService: encryptAndSendMessage()] context=${e.state.context}`,s),t.type===Q.TERMINATE&&(e.state.manualDisconnect=!0),null===(o=e.state.socket)||void 0===o||o.emit(J.MESSAGE,s)}(e,t),e.remote.state.analytics&&t.method&&ue.includes(t.method.toLowerCase())&&F({id:null!==(i=e.remote.state.channelId)&&void 0!==i?i:"",event:re.SDK_RPC_REQUEST,sdkVersion:e.remote.state.sdkVersion,commLayerVersion:U.version,walletVersion:null===(s=e.remote.state.walletInfo)||void 0===s?void 0:s.version,params:{method:t.method,from:"mobile"}},e.remote.state.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),function(e,t){var n;return h(this,void 0,void 0,(function*(){const o=null==t?void 0:t.id,i=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"";if(e.state.isOriginator&&o)try{const n=te(o,e.state.rpcMethodTracker,200).then((e=>({type:de.RPC_CHECK,result:e}))),s=(()=>h(this,void 0,void 0,(function*(){const t=yield ne({instance:e,rpcId:o}),n=yield te(t,e.state.rpcMethodTracker,200);return{type:de.SKIPPED_RPC,result:n}})))(),a=yield Promise.race([n,s]);if(a.type===de.RPC_CHECK){const e=a.result;$.SocketService(`[SocketService:handleRpcReplies()] id=${t.id} ${i} ( ${e.elapsedTime} ms)`,e.result)}else{if(a.type!==de.SKIPPED_RPC)throw new Error(`Error handling RPC replies for ${o}`);{const{result:t}=a;console.warn(`[SocketService handleRpcReplies()] RPC METHOD HAS BEEN SKIPPED rpcid=${o} method=${i}`,t);const n=Object.assign(Object.assign({},e.state.rpcMethodTracker[o]),{error:new Error(le)});e.emit(J.RPC_UPDATE,n);const s={data:Object.assign(Object.assign({},n),{jsonrpc:"2.0"}),name:"metamask-provider"};e.emit(J.MESSAGE,{message:s})}}}catch(e){throw console.warn(`[SocketService handleRpcReplies()] Error rpcId=${t.id} ${i}`,e),e}}))}(e,t).catch((e=>{console.warn("Error handleRpcReplies",e)})))}class me extends r{constructor({otherPublicKey:e,reconnect:t,communicationLayerPreference:n,transports:o,communicationServerUrl:i,context:s,ecies:a,remote:c,logging:r}){super(),this.state={clientsConnected:!1,clientsPaused:!1,manualDisconnect:!1,lastRpcId:void 0,rpcMethodTracker:{},hasPlaintext:!1,communicationServerUrl:""},this.state.resumed=t,this.state.context=s,this.state.communicationLayerPreference=n,this.state.debug=!0===(null==r?void 0:r.serviceLayer),this.remote=c,!0===(null==r?void 0:r.serviceLayer)&&R.enable("SocketService:Layer"),this.state.communicationServerUrl=i,this.state.hasPlaintext=this.state.communicationServerUrl!==j&&!0===(null==r?void 0:r.plaintext);const l={autoConnect:!1,transports:G,withCredentials:!0};o&&(l.transports=o),$.SocketService(`[SocketService: constructor()] Socket IO url: ${this.state.communicationServerUrl}`),this.state.socket=u(i,l);const d={communicationLayer:this,otherPublicKey:e,sendPublicKey:!1,context:this.state.context,ecies:a,logging:r};this.state.keyExchange=new q(d)}resetKeys(){return e=this,$.SocketService("[SocketService: resetKeys()] Resetting keys."),void(null===(t=e.state.keyExchange)||void 0===t||t.resetKeys());var e,t}createChannel(){return function(e){var t,n,o,i;$.SocketService(`[SocketService: createChannel()] context=${e.state.context}`),(null===(t=e.state.socket)||void 0===t?void 0:t.connected)||null===(n=e.state.socket)||void 0===n||n.connect(),e.state.manualDisconnect=!1,e.state.isOriginator=!0;const s=d();return e.state.channelId=s,ce(e,s),null===(o=e.state.socket)||void 0===o||o.emit(J.JOIN_CHANNEL,s,`${e.state.context}createChannel`),{channelId:s,pubKey:(null===(i=e.state.keyExchange)||void 0===i?void 0:i.getMyPublicKey())||""}}(this)}connectToChannel({channelId:e,isOriginator:t=!1,withKeyExchange:n=!1}){return function({options:e,instance:t}){var n,o,i,s;const{channelId:a,withKeyExchange:c,isOriginator:r}=e;if($.SocketService(`[SocketService: connectToChannel()] context=${t.state.context} channelId=${a} isOriginator=${r}`,null===(n=t.state.keyExchange)||void 0===n?void 0:n.toString()),null===(o=t.state.socket)||void 0===o?void 0:o.connected)throw new Error("socket already connected");t.state.manualDisconnect=!1,null===(i=t.state.socket)||void 0===i||i.connect(),t.state.withKeyExchange=c,t.state.isOriginator=r,t.state.channelId=a,ce(t,a),null===(s=t.state.socket)||void 0===s||s.emit(J.JOIN_CHANNEL,a,`${t.state.context}_connectToChannel`)}({options:{channelId:e,isOriginator:t,withKeyExchange:n},instance:this})}getKeyInfo(){return this.state.keyExchange.getKeyInfo()}keyCheck(){var e,t;null===(t=(e=this).state.socket)||void 0===t||t.emit(J.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:X.KEY_HANDSHAKE_CHECK,pubkey:e.getKeyInfo().ecies.otherPubKey}})}getKeyExchange(){return this.state.keyExchange}sendMessage(e){return he(this,e)}ping(){return e=this,$.SocketService(`[SocketService: ping()] context=${e.state.context} originator=${e.state.isOriginator} keysExchanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.state.isOriginator&&((null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged())?(console.warn(`[SocketService:ping()] context=${e.state.context} sending READY message`),e.sendMessage({type:Q.READY})):(console.warn(`[SocketService: ping()] context=${e.state.context} starting key exchange`),null===(o=e.state.keyExchange)||void 0===o||o.start({isOriginator:null!==(i=e.state.isOriginator)&&void 0!==i&&i}))),void(null===(s=e.state.socket)||void 0===s||s.emit(J.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:Q.PING}}));var e,t,n,o,i,s}pause(){return e=this,$.SocketService(`[SocketService: pause()] context=${e.state.context}`),e.state.manualDisconnect=!0,(null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged())&&e.sendMessage({type:Q.PAUSE}),void(null===(n=e.state.socket)||void 0===n||n.disconnect());var e,t,n}isConnected(){var e;return null===(e=this.state.socket)||void 0===e?void 0:e.connected}resume(){return e=this,$.SocketService(`[SocketService: resume()] context=${e.state.context} connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} manualDisconnect=${e.state.manualDisconnect} resumed=${e.state.resumed} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`),(null===(o=e.state.socket)||void 0===o?void 0:o.connected)?$.SocketService("[SocketService: resume()] already connected."):(null===(i=e.state.socket)||void 0===i||i.connect(),$.SocketService(`[SocketService: resume()] after connecting socket --\x3e connected=${null===(s=e.state.socket)||void 0===s?void 0:s.connected}`),null===(a=e.state.socket)||void 0===a||a.emit(J.JOIN_CHANNEL,e.state.channelId,`${e.state.context}_resume`)),(null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged())?e.state.isOriginator||e.sendMessage({type:Q.READY}):e.state.isOriginator||null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l}),e.state.manualDisconnect=!1,void(e.state.resumed=!0);var e,t,n,o,i,s,a,c,r,l}getRPCMethodTracker(){return this.state.rpcMethodTracker}disconnect(e){return function(e,t){var n,o;$.SocketService(`[SocketService: disconnect()] context=${e.state.context}`,t),(null==t?void 0:t.terminate)&&(e.state.channelId=t.channelId,null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.state.rpcMethodTracker={},e.state.manualDisconnect=!0,null===(o=e.state.socket)||void 0===o||o.disconnect()}(this,e)}}var ge,Ee,ve;function ye(e){return()=>h(this,void 0,void 0,(function*(){var t,n,o;const{state:i}=e;if(i.authorized)return;yield(()=>h(this,void 0,void 0,(function*(){for(;!i.walletInfo;)yield ee(500)})))();const s="7.3".localeCompare((null===(t=i.walletInfo)||void 0===t?void 0:t.version)||"");if($.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' version=${null===(n=i.walletInfo)||void 0===n?void 0:n.version} compareValue=${s}`),1!==s)return;const a=i.platformType===Ee.MobileWeb||i.platformType===Ee.ReactNative||i.platformType===Ee.MetaMaskMobileWebview;$.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' platform=${i.platformType} secure=${a} channel=${i.channelId} walletVersion=${null===(o=i.walletInfo)||void 0===o?void 0:o.version}`),a&&(i.authorized=!0,e.emit(J.AUTHORIZED))}))}function pe(e){return t=>{const{state:n}=e;$.RemoteCommunication(`[RemoteCommunication: handleChannelCreatedEvent()] context=${n.context} on 'channel_created' channelId=${t}`),e.emit(J.CHANNEL_CREATED,t)}}function Ce(e,t){return()=>{var n,o,i,s;const{state:a}=e;if($.RemoteCommunication(`[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=${a.channelId} keysExchanged=${null===(o=null===(n=a.communicationLayer)||void 0===n?void 0:n.getKeyInfo())||void 0===o?void 0:o.keysExchanged}`),a.analytics){const e=a.isOriginator?re.REQUEST:re.REQUEST_MOBILE;F(Object.assign(Object.assign({id:null!==(i=a.channelId)&&void 0!==i?i:"",event:a.reconnection?re.RECONNECT:e},a.originatorInfo),{commLayer:t,sdkVersion:a.sdkVersion,walletVersion:null===(s=a.walletInfo)||void 0===s?void 0:s.version,commLayerVersion:U.version}),a.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}a.clientsConnected=!0,a.originatorInfoSent=!1,e.emit(J.CLIENTS_CONNECTED)}}function Se(e,t){return n=>{var o;const{state:i}=e;$.RemoteCommunication(`[RemoteCommunication: handleClientsDisconnectedEvent()] context=${i.context} on 'clients_disconnected' channelId=${n}`),i.clientsConnected=!1,e.emit(J.CLIENTS_DISCONNECTED,i.channelId),e.setConnectionStatus(B.DISCONNECTED),i.ready=!1,i.authorized=!1,i.analytics&&i.channelId&&F({id:i.channelId,event:re.DISCONNECTED,sdkVersion:i.sdkVersion,commLayer:t,commLayerVersion:U.version,walletVersion:null===(o=i.walletInfo)||void 0===o?void 0:o.version},i.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}}function fe(e){return t=>{var n;const{state:o}=e;if($.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] context=${o.context} on 'clients_waiting' numberUsers=${t} ready=${o.ready} autoStarted=${o.originatorConnectStarted}`),e.setConnectionStatus(B.WAITING),e.emit(J.CLIENTS_WAITING,t),o.originatorConnectStarted){$.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] on 'clients_waiting' watch autoStarted=${o.originatorConnectStarted} timeout`,o.autoConnectOptions);const t=(null===(n=o.autoConnectOptions)||void 0===n?void 0:n.timeout)||3e3,i=setTimeout((()=>{$.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] setTimeout(${t}) terminate channelConfig`,o.autoConnectOptions),o.originatorConnectStarted=!1,o.ready||e.setConnectionStatus(B.TIMEOUT),clearTimeout(i)}),t)}}}function ke(e,t){return n=>{var o,i,s,a,c;const{state:r}=e;$.RemoteCommunication(`[RemoteCommunication: handleKeysExchangedEvent()] context=${r.context} on commLayer.'keys_exchanged' channel=${r.channelId}`,n),(null===(i=null===(o=r.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.keysExchanged)&&e.setConnectionStatus(B.LINKED),function(e,t){var n,o,i,s;const{state:a}=e;$.RemoteCommunication(`[RemoteCommunication: setLastActiveDate()] channel=${a.channelId}`,t);const c={channelId:null!==(n=a.channelId)&&void 0!==n?n:"",validUntil:null!==(i=null===(o=a.channelConfig)||void 0===o?void 0:o.validUntil)&&void 0!==i?i:0,lastActive:t.getTime()};null===(s=a.storageManager)||void 0===s||s.persistChannelConfig(c)}(e,new Date),r.analytics&&r.channelId&&F({id:r.channelId,event:n.isOriginator?re.CONNECTED:re.CONNECTED_MOBILE,sdkVersion:r.sdkVersion,commLayer:t,commLayerVersion:U.version,walletVersion:null===(s=r.walletInfo)||void 0===s?void 0:s.version},r.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),r.isOriginator=n.isOriginator,n.isOriginator||(null===(a=r.communicationLayer)||void 0===a||a.sendMessage({type:Q.READY}),r.ready=!0,r.paused=!1),n.isOriginator&&!r.originatorInfoSent&&(null===(c=r.communicationLayer)||void 0===c||c.sendMessage({type:Q.ORIGINATOR_INFO,originatorInfo:r.originatorInfo,originator:r.originatorInfo}),r.originatorInfoSent=!0)}}function xe(e,t){const{state:n}=t;if($.RemoteCommunication(`[RemoteCommunication: onCommunicationLayerMessage()] context=${n.context} on 'message' typeof=${typeof e}`,e),t.state.ready=!0,n.isOriginator||e.type!==Q.ORIGINATOR_INFO)if(n.isOriginator&&e.type===Q.WALLET_INFO)!function(e,t){const{state:n}=e;n.walletInfo=t.walletInfo,n.paused=!1}(t,e);else{if(e.type===Q.TERMINATE)!function(e){const{state:t}=e;t.isOriginator&&(Ae({options:{terminate:!0,sendMessage:!1},instance:e}),console.debug(),e.emit(J.TERMINATE))}(t);else if(e.type===Q.PAUSE)!function(e){const{state:t}=e;t.paused=!0,e.setConnectionStatus(B.PAUSED)}(t);else if(e.type===Q.READY&&n.isOriginator)!function(e){const{state:t}=e;e.setConnectionStatus(B.LINKED);const n=t.paused;t.paused=!1,e.emit(J.CLIENTS_READY,{isOriginator:t.isOriginator,walletInfo:t.walletInfo}),n&&(t.authorized=!0,e.emit(J.AUTHORIZED))}(t);else{if(e.type===Q.OTP&&n.isOriginator)return void function(e,t){var n;const{state:o}=e;e.emit(J.OTP,t.otpAnswer),1==="6.6".localeCompare((null===(n=o.walletInfo)||void 0===n?void 0:n.version)||"")&&(console.warn("RemoteCommunication::on 'otp' -- backward compatibility <6.6 -- triger eth_requestAccounts"),e.emit(J.SDK_RPC_CALL,{method:V.ETH_REQUESTACCOUNTS,params:[]}))}(t,e);e.type===Q.AUTHORIZED&&n.isOriginator&&function(e){const{state:t}=e;t.authorized=!0,e.emit(J.AUTHORIZED)}(t)}t.emit(J.MESSAGE,e)}else!function(e,t){var n;const{state:o}=e;null===(n=o.communicationLayer)||void 0===n||n.sendMessage({type:Q.WALLET_INFO,walletInfo:o.walletInfo}),o.originatorInfo=t.originatorInfo||t.originator,e.emit(J.CLIENTS_READY,{isOriginator:o.isOriginator,originatorInfo:o.originatorInfo}),o.paused=!1}(t,e)}function Ie(e,t){var n,o;return h(this,void 0,void 0,(function*(){const{state:i}=e;$.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} paused=${i.paused} ready=${i.ready} authorized=${i.authorized} socket=${null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected()} clientsConnected=${i.clientsConnected} status=${i._connectionStatus}`,t),!i.paused&&i.ready&&(null===(o=i.communicationLayer)||void 0===o?void 0:o.isConnected())&&i.clientsConnected||($.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} SKIP message waiting for MM mobile readiness.`),yield new Promise((t=>{e.once(J.CLIENTS_READY,t)})),$.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} AFTER SKIP / READY -- sending pending message`));try{yield function(e,t){return h(this,void 0,void 0,(function*(){return new Promise((n=>{var o,i,s,a;const{state:c}=e;if($.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} ready=${c.ready} authorized=${c.authorized} method=${t.method}`),1==="7.3".localeCompare((null===(o=c.walletInfo)||void 0===o?void 0:o.version)||""))return $.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] compatibility hack wallet version > ${null===(i=c.walletInfo)||void 0===i?void 0:i.version}`),null===(s=c.communicationLayer)||void 0===s||s.sendMessage(t),void n();!c.isOriginator||c.authorized?(null===(a=c.communicationLayer)||void 0===a||a.sendMessage(t),n()):e.once(J.AUTHORIZED,(()=>{var e;$.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} AFTER SKIP / AUTHORIZED -- sending pending message`),null===(e=c.communicationLayer)||void 0===e||e.sendMessage(t),n()}))}))}))}(e,t)}catch(e){throw console.error(`[RemoteCommunication: sendMessage()] context=${i.context} ERROR`,e),e}}))}function _e(e){return t=>{let n=t;t.message&&(n=n.message),xe(n,e)}}function Ke(e){return()=>{const{state:t}=e;$.RemoteCommunication("[RemoteCommunication: handleSocketReconnectEvent()] on 'socket_reconnect' -- reset key exchange status / set ready to false"),t.ready=!1,t.authorized=!1,W(t),e.emitServiceStatusEvent()}}function Oe(e){return()=>{const{state:t}=e;$.RemoteCommunication("[RemoteCommunication: handleSocketDisconnectedEvent()] on 'socket_Disconnected' set ready to false"),t.ready=!1}}function Ae({options:e,instance:t}){var n,o,i,s,a,c;const{state:r}=t;$.RemoteCommunication(`[RemoteCommunication: disconnect()] channel=${r.channelId}`,e),r.ready=!1,r.paused=!1,(null==e?void 0:e.terminate)?(null===(n=r.storageManager)||void 0===n||n.terminate(null!==(o=r.channelId)&&void 0!==o?o:""),(null===(i=r.communicationLayer)||void 0===i?void 0:i.getKeyInfo().keysExchanged)&&(null==e?void 0:e.sendMessage)&&(null===(s=r.communicationLayer)||void 0===s||s.sendMessage({type:Q.TERMINATE})),r.channelId=d(),e.channelId=r.channelId,r.channelConfig=void 0,r.originatorConnectStarted=!1,null===(a=r.communicationLayer)||void 0===a||a.disconnect(e),t.setConnectionStatus(B.TERMINATED)):(null===(c=r.communicationLayer)||void 0===c||c.disconnect(e),t.setConnectionStatus(B.DISCONNECTED))}!function(e){e.SOCKET="socket"}(ge||(ge={})),function(e){e.NonBrowser="nodejs",e.MetaMaskMobileWebview="in-app-browser",e.DesktopWeb="web-desktop",e.MobileWeb="web-mobile",e.ReactNative="react-native"}(Ee||(Ee={}));class Ne extends r{constructor({platformType:e,communicationLayerPreference:t,otherPublicKey:n,reconnect:o,walletInfo:i,dappMetadata:s,transports:a,context:c,ecies:r,analytics:l=!1,storage:d,sdkVersion:u,communicationServerUrl:h=j,logging:m,autoConnect:g={timeout:3e3}}){super(),this.state={ready:!1,authorized:!1,isOriginator:!1,paused:!1,platformType:"metamask-mobile",analytics:!1,reconnection:!1,originatorInfoSent:!1,communicationServerUrl:j,context:"",clientsConnected:!1,sessionDuration:z,originatorConnectStarted:!1,debug:!1,_connectionStatus:B.DISCONNECTED},this.state.otherPublicKey=n,this.state.dappMetadata=s,this.state.walletInfo=i,this.state.transports=a,this.state.platformType=e,this.state.analytics=l,this.state.isOriginator=!n,this.state.communicationServerUrl=h,this.state.context=c,this.state.sdkVersion=u,this.setMaxListeners(50),this.setConnectionStatus(B.DISCONNECTED),(null==d?void 0:d.duration)&&(this.state.sessionDuration=z),this.state.storageOptions=d,this.state.autoConnectOptions=g,this.state.debug=!0===(null==m?void 0:m.remoteLayer),!0===(null==m?void 0:m.remoteLayer)&&R.enable("RemoteCommunication:Layer"),this.state.logging=m,(null==d?void 0:d.storageManager)&&(this.state.storageManager=d.storageManager),this.initCommunicationLayer({communicationLayerPreference:t,otherPublicKey:n,reconnect:o,ecies:r,communicationServerUrl:h}),this.emitServiceStatusEvent()}initCommunicationLayer({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=j}){return function({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=j,instance:s}){var a,c,r,l,d;const{state:u}=s;if(e!==ge.SOCKET)throw new Error("Invalid communication protocol");u.communicationLayer=new me({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,transports:u.transports,communicationServerUrl:i,context:u.context,ecies:o,logging:u.logging,remote:s});let h="undefined"!=typeof document&&document.URL||"",m="undefined"!=typeof document&&document.title||"";(null===(a=u.dappMetadata)||void 0===a?void 0:a.url)&&(h=u.dappMetadata.url),(null===(c=u.dappMetadata)||void 0===c?void 0:c.name)&&(m=u.dappMetadata.name);const g={url:h,title:m,source:null===(r=u.dappMetadata)||void 0===r?void 0:r.source,icon:(null===(l=u.dappMetadata)||void 0===l?void 0:l.iconUrl)||(null===(d=u.dappMetadata)||void 0===d?void 0:d.base64Icon),platform:u.platformType,apiVersion:U.version};u.originatorInfo=g;const E={[J.AUTHORIZED]:ye(s),[J.MESSAGE]:_e(s),[J.CLIENTS_CONNECTED]:Ce(s,e),[J.KEYS_EXCHANGED]:ke(s,e),[J.SOCKET_DISCONNECTED]:Oe(s),[J.SOCKET_RECONNECT]:Ke(s),[J.CLIENTS_DISCONNECTED]:Se(s,e),[J.KEY_INFO]:()=>{s.emitServiceStatusEvent()},[J.CHANNEL_CREATED]:pe(s),[J.CLIENTS_WAITING]:fe(s),[J.RPC_UPDATE]:e=>{s.emit(J.RPC_UPDATE,e)}};for(const[e,t]of Object.entries(E))try{u.communicationLayer.on(e,t)}catch(t){console.error(`Error registering handler for ${e}:`,t)}}({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i,instance:this})}originatorSessionConnect(){return h(this,void 0,void 0,(function*(){return yield function(e){var t,n,o;return h(this,void 0,void 0,(function*(){const{state:i}=e;if(!i.storageManager)return void $.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] no storage manager defined - skip");const s=yield i.storageManager.getPersistedChannelConfig(null!==(t=i.channelId)&&void 0!==t?t:"");if($.RemoteCommunication(`[RemoteCommunication: originatorSessionConnect()] autoStarted=${i.originatorConnectStarted} channelConfig`,s),null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected())return $.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] socket already connected - skip"),s;if(s){if(s.validUntil>Date.now())return i.channelConfig=s,i.originatorConnectStarted=!0,i.channelId=null==s?void 0:s.channelId,i.reconnection=!0,null===(o=i.communicationLayer)||void 0===o||o.connectToChannel({channelId:s.channelId,isOriginator:!0}),s;$.RemoteCommunication("[RemoteCommunication: autoConnect()] Session has expired")}i.originatorConnectStarted=!1}))}(this)}))}generateChannelIdConnect(){return h(this,void 0,void 0,(function*(){return function(e){var t,n,o,i,s;if(!e.communicationLayer)throw new Error("communication layer not initialized");if(e.ready)throw new Error("Channel already connected");if(e.channelId&&(null===(t=e.communicationLayer)||void 0===t?void 0:t.isConnected()))return console.warn("Channel already exists -- interrupt generateChannelId",e.channelConfig),e.channelConfig={channelId:e.channelId,validUntil:Date.now()+e.sessionDuration},null===(n=e.storageManager)||void 0===n||n.persistChannelConfig(e.channelConfig),{channelId:e.channelId,pubKey:null===(i=null===(o=e.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.ecies.public};$.RemoteCommunication("[RemoteCommunication: generateChannelId()]"),W(e);const a=e.communicationLayer.createChannel();$.RemoteCommunication("[RemoteCommunication: generateChannelId()] channel created",a);const c={channelId:a.channelId,validUntil:Date.now()+e.sessionDuration};return e.channelId=a.channelId,e.channelConfig=c,null===(s=e.storageManager)||void 0===s||s.persistChannelConfig(c),{channelId:e.channelId,pubKey:a.pubKey}}(this.state)}))}clean(){return W(this.state)}connectToChannel(e,t){return function({channelId:e,withKeyExchange:t,state:n}){var o,i,s;if(!l(e))throw $.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} invalid channel channelId=${e}`),new Error(`Invalid channel ${e}`);if($.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} channelId=${e}`),null===(o=n.communicationLayer)||void 0===o?void 0:o.isConnected())return void $.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} already connected - interrupt connection.`);n.channelId=e,null===(i=n.communicationLayer)||void 0===i||i.connectToChannel({channelId:e,withKeyExchange:t});const a={channelId:e,validUntil:Date.now()+n.sessionDuration};n.channelConfig=a,null===(s=n.storageManager)||void 0===s||s.persistChannelConfig(a)}({channelId:e,withKeyExchange:t,state:this.state})}sendMessage(e){return Ie(this,e)}testStorage(){return h(this,void 0,void 0,(function*(){return function(e){var t,n;return h(this,void 0,void 0,(function*(){const o=yield null===(t=e.storageManager)||void 0===t?void 0:t.getPersistedChannelConfig(null!==(n=e.channelId)&&void 0!==n?n:"");$.RemoteCommunication("[RemoteCommunication: testStorage()] res",o)}))}(this.state)}))}getChannelConfig(){return this.state.channelConfig}isReady(){return this.state.ready}isConnected(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.isConnected()}isAuthorized(){return this.state.authorized}isPaused(){return this.state.paused}getCommunicationLayer(){return this.state.communicationLayer}ping(){var e;$.RemoteCommunication(`[RemoteCommunication: ping()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.ping()}keyCheck(){var e;$.RemoteCommunication(`[RemoteCommunication: keyCheck()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.keyCheck()}setConnectionStatus(e){this.state._connectionStatus!==e&&(this.state._connectionStatus=e,this.emit(J.CONNECTION_STATUS,e),this.emitServiceStatusEvent())}emitServiceStatusEvent(){this.emit(J.SERVICE_STATUS,this.getServiceStatus())}getConnectionStatus(){return this.state._connectionStatus}getServiceStatus(){return{originatorInfo:this.state.originatorInfo,keyInfo:this.getKeyInfo(),connectionStatus:this.state._connectionStatus,channelConfig:this.state.channelConfig,channelId:this.state.channelId}}getKeyInfo(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getKeyInfo()}resetKeys(){var e;null===(e=this.state.communicationLayer)||void 0===e||e.resetKeys()}setOtherPublicKey(e){var t;const n=null===(t=this.state.communicationLayer)||void 0===t?void 0:t.getKeyExchange();if(!n)throw new Error("KeyExchange is not initialized.");n.getOtherPublicKey()!==e&&n.setOtherPublicKey(e)}pause(){var e;$.RemoteCommunication(`[RemoteCommunication: pause()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.pause(),this.setConnectionStatus(B.PAUSED)}getVersion(){return U.version}resume(){return function(e){var t;const{state:n}=e;$.RemoteCommunication(`[RemoteCommunication: resume()] channel=${n.channelId}`),null===(t=n.communicationLayer)||void 0===t||t.resume(),e.setConnectionStatus(B.LINKED)}(this)}getChannelId(){return this.state.channelId}getRPCMethodTracker(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getRPCMethodTracker()}disconnect(e){return Ae({options:e,instance:this})}}!function(e){e.RENEW="renew",e.LINK="link"}(ve||(ve={}));export{ve as AutoConnectType,ge as CommunicationLayerPreference,B as ConnectionStatus,j as DEFAULT_SERVER_URL,Y as ECIES,J as EventType,X as KeyExchangeMessageType,Q as MessageType,Ee as PlatformType,Ne as RemoteCommunication,F as SendAnalytics,me as SocketService,re as TrackingEvents};
import e from"cross-fetch";import t from"tty";import n from"util";import o from"os";import{Buffer as i}from"buffer";import{PrivateKey as s,encrypt as a,decrypt as c}from"eciesjs";import{EventEmitter2 as r}from"eventemitter2";import{validate as l,v4 as d}from"uuid";import{io as u}from"socket.io-client";function h(e,t,n,o){return new(n||(n=Promise))((function(i,s){function a(e){try{r(o.next(e))}catch(e){s(e)}}function c(e){try{r(o.throw(e))}catch(e){s(e)}}function r(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,c)}r((o=o.apply(e,t||[])).next())}))}function m(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var g,E,v,y,p,C={exports:{}},S={exports:{}};function f(){if(E)return g;E=1;var e=1e3,t=60*e,n=60*t,o=24*n,i=7*o,s=365.25*o;function a(e,t,n,o){var i=t>=1.5*n;return Math.round(e/n)+" "+o+(i?"s":"")}return g=function(c,r){r=r||{};var l=typeof c;if("string"===l&&c.length>0)return function(a){if((a=String(a)).length>100)return;var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!c)return;var r=parseFloat(c[1]);switch((c[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*s;case"weeks":case"week":case"w":return r*i;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*n;case"minutes":case"minute":case"mins":case"min":case"m":return r*t;case"seconds":case"second":case"secs":case"sec":case"s":return r*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(c);if("number"===l&&isFinite(c))return r.long?function(i){var s=Math.abs(i);if(s>=o)return a(i,s,o,"day");if(s>=n)return a(i,s,n,"hour");if(s>=t)return a(i,s,t,"minute");if(s>=e)return a(i,s,e,"second");return i+" ms"}(c):function(i){var s=Math.abs(i);if(s>=o)return Math.round(i/o)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))}}function k(){if(y)return v;return y=1,v=function(e){function t(e){let o,i,s,a=null;function c(...e){if(!c.enabled)return;const n=c,i=Number(new Date),s=i-(o||i);n.diff=s,n.prev=o,n.curr=i,o=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((o,i)=>{if("%%"===o)return"%";a++;const s=t.formatters[i];if("function"==typeof s){const t=e[a];o=s.call(n,t),e.splice(a,1),a--}return o})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return c.namespace=e,c.useColors=t.useColors(),c.color=t.selectColor(e),c.extend=n,c.destroy=t.destroy,Object.defineProperty(c,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{a=e}}),"function"==typeof t.init&&t.init(c),c}function n(e,n){const o=t(this.namespace+(void 0===n?":":n)+e);return o.log=this.log,o}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const o=("string"==typeof e?e:"").split(/[\s,]+/),i=o.length;for(n=0;n<i;n++)o[n]&&("-"===(e=o[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,o;for(n=0,o=t.skips.length;n<o;n++)if(t.skips[n].test(e))return!1;for(n=0,o=t.names.length;n<o;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=f(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},v}var x,I,_,K,O,A={exports:{}};function N(){return I?x:(I=1,x=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",o=t.indexOf(n+e),i=t.indexOf("--");return-1!==o&&(-1===i||o<i)})}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?C.exports=(p||(p=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(o++,"%c"===e&&(i=o))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=k()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(S,S.exports)),S.exports):C.exports=(O||(O=1,function(e,i){const s=t,a=n;i.init=function(e){e.inspectOpts={};const t=Object.keys(i.inspectOpts);for(let n=0;n<t.length;n++)e.inspectOpts[t[n]]=i.inspectOpts[t[n]]},i.log=function(...e){return process.stderr.write(a.format(...e)+"\n")},i.formatArgs=function(t){const{namespace:n,useColors:o}=this;if(o){const o=this.color,i="[3"+(o<8?o:"8;5;"+o),s=` ${i};1m${n} `;t[0]=s+t[0].split("\n").join("\n"+s),t.push(i+"m+"+e.exports.humanize(this.diff)+"")}else t[0]=(i.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+n+" "+t[0]},i.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},i.load=function(){return process.env.DEBUG},i.useColors=function(){return"colors"in i.inspectOpts?Boolean(i.inspectOpts.colors):s.isatty(process.stderr.fd)},i.destroy=a.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),i.colors=[6,2,3,4,5,1];try{const e=function(){if(K)return _;K=1;const e=o,n=t,i=N(),{env:s}=process;let a;function c(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function r(t,n){if(0===a)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(t&&!n&&void 0===a)return 0;const o=a||0;if("dumb"===s.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in s)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in s))||"codeship"===s.CI_NAME?1:o;if("TEAMCITY_VERSION"in s)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(s.TEAMCITY_VERSION)?1:0;if("truecolor"===s.COLORTERM)return 3;if("TERM_PROGRAM"in s){const e=parseInt((s.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(s.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(s.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(s.TERM)||"COLORTERM"in s?1:o}return i("no-color")||i("no-colors")||i("color=false")||i("color=never")?a=0:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(a=1),"FORCE_COLOR"in s&&(a="true"===s.FORCE_COLOR?1:"false"===s.FORCE_COLOR?0:0===s.FORCE_COLOR.length?1:Math.min(parseInt(s.FORCE_COLOR,10),3)),_={supportsColor:function(e){return c(r(e,e&&e.isTTY))},stdout:c(r(!0,n.isatty(1))),stderr:c(r(!0,n.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(i.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}i.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let o=process.env[t];return o=!!/^(yes|on|true|enabled)$/i.test(o)||!/^(no|off|false|disabled)$/i.test(o)&&("null"===o?null:Number(o)),e[n]=o,e}),{}),e.exports=k()(i);const{formatters:c}=e.exports;c.o=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},c.O=function(e){return this.inspectOpts.colors=this.useColors,a.inspect(e,this.inspectOpts)}}(A,A.exports)),A.exports);var R=m(C.exports);const T=R("KeyExchange:Layer"),b=R("SocketService:Layer"),w=R("Ecies:Layer"),D=R("RemoteCommunication:Layer");T.color="##95c44e",b.color="#f638d7",w.color="#465b9c",D.color="#47a2be";const $={KeyExchange:T,SocketService:b,Ecies:w,RemoteCommunication:D};let M,L=[],P=[];function H(t){return h(this,void 0,void 0,(function*(){if(!M||!t)return;!function(){const e=P;P=L,L=e}();const n=M.endsWith("/")?`${M}debug`:`${M}/debug`,o=Object.assign({},t);if(delete o.params,t.params)for(const[e,n]of Object.entries(t.params))o[e]=n;const i=JSON.stringify(o);$.RemoteCommunication(`[sendBufferedEvents] Sending ${L.length} analytics events to ${n}`);try{const t=yield e(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:i}),o=yield t.text();$.RemoteCommunication(`[sendBufferedEvents] Response: ${o}`),L.length=0}catch(e){console.warn("Error sending analytics",e)}}))}const F=(e,t)=>h(void 0,void 0,void 0,(function*(){var n;M=t,n=e,P.push(n),H(e).catch((()=>{}))}));class Y{constructor(e){this.enabled=!0,(null==e?void 0:e.debug)&&R.enable("Ecies:Layer"),(null==e?void 0:e.pkey)?this.ecies=s.fromHex(e.pkey):this.ecies=new s,$.Ecies("[ECIES constructor()] initialized secret: ",this.ecies.toHex()),$.Ecies("[ECIES constructor()] initialized public: ",this.ecies.publicKey.toHex()),$.Ecies("[ECIES constructor()] init with",this)}generateECIES(){this.ecies=new s}getPublicKey(){return this.ecies.publicKey.toHex()}encrypt(e,t){let n=e;if(this.enabled)try{$.Ecies("[ECIES: encrypt()] using otherPublicKey",t);const o=i.from(e),s=a(t,o);n=i.from(s).toString("base64")}catch(n){throw $.Ecies("[ECIES: encrypt()] error encrypt:",n),$.Ecies("[ECIES: encrypt()] private: ",this.ecies.toHex()),$.Ecies("[ECIES: encrypt()] data: ",e),$.Ecies("[ECIES: encrypt()] otherkey: ",t),n}return n}decrypt(e){let t=e;if(this.enabled)try{$.Ecies("[ECIES: decrypt()] using privateKey",this.ecies.toHex());const n=i.from(e.toString(),"base64");t=c(this.ecies.toHex(),n).toString()}catch(t){throw $.Ecies("[ECIES: decrypt()] error decrypt",t),$.Ecies("[ECIES: decrypt()] private: ",this.ecies.toHex()),$.Ecies("[ECIES: decrypt()] encryptedData: ",e),t}return t}getKeyInfo(){return{private:this.ecies.toHex(),public:this.ecies.publicKey.toHex()}}toString(){$.Ecies("[ECIES: toString()]",this.getKeyInfo())}}var U={name:"@metamask/sdk-communication-layer",version:"0.18.0",description:"",homepage:"https://github.com/MetaMask/metamask-sdk#readme",bugs:{url:"https://github.com/MetaMask/metamask-sdk/issues"},repository:{type:"git",url:"https://github.com/MetaMask/metamask-sdk.git",directory:"packages/sdk-communication-layer"},main:"dist/node/cjs/metamask-sdk-communication-layer.js",unpkg:"dist/browser/umd/metamask-sdk-communication-layer.js",module:"dist/node/es/metamask-sdk-communication-layer.js",browser:"dist/browser/es/metamask-sdk-communication-layer.js","react-native":"dist/react-native/es/metamask-sdk-communication-layer.js",types:"dist/browser/es/src/index.d.ts",files:["/dist"],scripts:{build:"rimraf dist && rollup -c --bundleConfigAsCjs","build:tsc":"tsc","build:dev":"rimraf dist && NODE_ENV=dev rollup -c --bundleConfigAsCjs","build:post-tsc":"echo 'N/A'","build:pre-tsc":"echo 'N/A'",size:"size-limit",clean:"rimraf ./dist",lint:"yarn lint:eslint && yarn lint:misc --check","lint:changelog":"../../scripts/validate-changelog.sh @metamask/sdk-communication-layer","lint:eslint":"eslint . --cache --ext js,ts","lint:fix":"yarn lint:eslint --fix && yarn lint:misc --write","lint:misc":"prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path ../../.gitignore","prepare-manifest:preview":"../../scripts/prepare-preview-manifest.sh","publish:preview":"yarn npm publish --tag preview",prepack:"../../scripts/prepack.sh",reset:"yarn clean && rimraf ./node_modules/",test:"jest","test:coverage":"jest --coverage","test:ci":"jest --coverage --passWithNoTests --setupFilesAfterEnv ./jest-preload.js","test:dev":"jest",watch:"rollup -c --bundleConfigAsCjs -w"},dependencies:{bufferutil:"^4.0.8","date-fns":"^2.29.3",debug:"^4.3.4","utf-8-validate":"^6.0.3",uuid:"^8.3.2"},devDependencies:{"@jest/globals":"^29.3.1","@lavamoat/allow-scripts":"^2.3.1","@metamask/auto-changelog":"3.1.0","@metamask/eslint-config":"^6.0.0","@metamask/eslint-config-nodejs":"^6.0.0","@metamask/eslint-config-typescript":"^6.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.0.2","@rollup/plugin-terser":"^0.4.1","@size-limit/preset-big-lib":"^11.0.2","@types/jest":"^29.2.4","@types/node":"^20.1.3","@types/uuid":"^9.0.0","@typescript-eslint/eslint-plugin":"^4.26.0","@typescript-eslint/parser":"^4.26.0","cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eslint:"^7.30.0","eslint-config-prettier":"^8.3.0","eslint-plugin-import":"^2.23.4","eslint-plugin-jest":"^24.4.0","eslint-plugin-jsdoc":"^36.1.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.4.0",eventemitter2:"^6.4.7",jest:"^29.3.1",prettier:"^2.3.0",rimraf:"^3.0.2",rollup:"^3.21.7","rollup-plugin-jscc":"^2.0.0","rollup-plugin-natives":"^0.7.5","rollup-plugin-node-builtins":"^2.1.2","rollup-plugin-node-globals":"^1.4.0","rollup-plugin-peer-deps-external":"^2.2.4","rollup-plugin-sizes":"^1.0.6","rollup-plugin-typescript2":"^0.31.2","rollup-plugin-visualizer":"^5.9.2","size-limit":"^11.0.2","socket.io-client":"^4.5.1","stream-browserify":"^3.0.0","ts-jest":"^29.0.3","ts-node":"^10.9.1",typescript:"^4.3.2"},peerDependencies:{"cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eventemitter2:"^6.4.7","readable-stream":"^3.6.2","socket.io-client":"^4.5.1"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},lavamoat:{allowScripts:{"@lavamoat/preinstall-always-fail":!1,canvas:!0,"eciesjs>secp256k1":!1,"socket.io-client>engine.io-client>ws>bufferutil":!1,"socket.io-client>engine.io-client>ws>utf-8-validate":!1,bufferutil:!1,"utf-8-validate":!1}}};const j="https://metamask-sdk.api.cx.metamask.io/",G=["websocket"],z=6048e5,V={METAMASK_GETPROVIDERSTATE:"metamask_getProviderState",ETH_REQUESTACCOUNTS:"eth_requestAccounts"};function W(e){const{context:t}=e;$.RemoteCommunication(`[RemoteCommunication: clean()] context=${t}`),e.channelConfig=void 0,e.ready=!1,e.originatorConnectStarted=!1}var B,J,Z,X,Q;!function(e){e.DISCONNECTED="disconnected",e.WAITING="waiting",e.TIMEOUT="timeout",e.LINKED="linked",e.PAUSED="paused",e.TERMINATED="terminated"}(B||(B={})),function(e){e.KEY_INFO="key_info",e.SERVICE_STATUS="service_status",e.PROVIDER_UPDATE="provider_update",e.RPC_UPDATE="rpc_update",e.KEYS_EXCHANGED="keys_exchanged",e.JOIN_CHANNEL="join_channel",e.CHANNEL_CREATED="channel_created",e.CLIENTS_CONNECTED="clients_connected",e.CLIENTS_DISCONNECTED="clients_disconnected",e.CLIENTS_WAITING="clients_waiting",e.CLIENTS_READY="clients_ready",e.SOCKET_DISCONNECTED="socket_disconnected",e.SOCKET_RECONNECT="socket_reconnect",e.OTP="otp",e.SDK_RPC_CALL="sdk_rpc_call",e.AUTHORIZED="authorized",e.CONNECTION_STATUS="connection_status",e.MESSAGE="message",e.TERMINATE="terminate"}(J||(J={})),function(e){e.KEY_EXCHANGE="key_exchange"}(Z||(Z={})),function(e){e.KEY_HANDSHAKE_START="key_handshake_start",e.KEY_HANDSHAKE_CHECK="key_handshake_check",e.KEY_HANDSHAKE_SYN="key_handshake_SYN",e.KEY_HANDSHAKE_SYNACK="key_handshake_SYNACK",e.KEY_HANDSHAKE_ACK="key_handshake_ACK",e.KEY_HANDSHAKE_NONE="none"}(X||(X={}));class q extends r{constructor({communicationLayer:e,otherPublicKey:t,context:n,ecies:o,logging:i}){super(),this.keysExchanged=!1,this.step=X.KEY_HANDSHAKE_NONE,this.debug=!1,this.context=n,this.myECIES=new Y(Object.assign(Object.assign({},o),{debug:null==i?void 0:i.eciesLayer})),this.communicationLayer=e,this.myPublicKey=this.myECIES.getPublicKey(),this.debug=!0===(null==i?void 0:i.keyExchangeLayer),(null==i?void 0:i.keyExchangeLayer)&&R.enable("KeyExchange:Layer"),t&&this.setOtherPublicKey(t),this.communicationLayer.on(Z.KEY_EXCHANGE,this.onKeyExchangeMessage.bind(this))}onKeyExchangeMessage(e){$.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} keysExchanged=${this.keysExchanged}`,e);const{message:t}=e;this.keysExchanged&&$.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} received handshake while already exchanged. step=${this.step} otherPubKey=${this.otherPublicKey}`),this.emit(J.KEY_INFO,t.type),t.type===X.KEY_HANDSHAKE_SYN?(this.checkStep([X.KEY_HANDSHAKE_NONE,X.KEY_HANDSHAKE_ACK]),$.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYN",t),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_SYNACK,pubkey:this.myPublicKey}),this.setStep(X.KEY_HANDSHAKE_ACK)):t.type===X.KEY_HANDSHAKE_SYNACK?(this.checkStep([X.KEY_HANDSHAKE_SYNACK,X.KEY_HANDSHAKE_ACK,X.KEY_HANDSHAKE_NONE]),$.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYNACK"),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_ACK}),this.keysExchanged=!0,this.setStep(X.KEY_HANDSHAKE_ACK),this.emit(J.KEYS_EXCHANGED)):t.type===X.KEY_HANDSHAKE_ACK&&($.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_ACK set keysExchanged to true!"),this.checkStep([X.KEY_HANDSHAKE_ACK,X.KEY_HANDSHAKE_NONE]),this.keysExchanged=!0,this.setStep(X.KEY_HANDSHAKE_ACK),this.emit(J.KEYS_EXCHANGED))}resetKeys(e){this.clean(),this.myECIES=new Y(e)}clean(){$.KeyExchange(`[KeyExchange: clean()] context=${this.context} reset handshake state`),this.setStep(X.KEY_HANDSHAKE_NONE),this.emit(J.KEY_INFO,this.step),this.keysExchanged=!1}start({isOriginator:e,force:t}){$.KeyExchange(`[KeyExchange: start()] context=${this.context} isOriginator=${e} step=${this.step} force=${t} keysExchanged=${this.keysExchanged}`),e?!(this.keysExchanged||this.step!==X.KEY_HANDSHAKE_NONE&&this.step!==X.KEY_HANDSHAKE_SYNACK)||t?($.KeyExchange(`[KeyExchange: start()] context=${this.context} -- start key exchange (force=${t}) -- step=${this.step}`,this.step),this.clean(),this.setStep(X.KEY_HANDSHAKE_SYNACK),this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_SYN,pubkey:this.myPublicKey})):$.KeyExchange(`[KeyExchange: start()] context=${this.context} -- key exchange already ${this.keysExchanged?"done":"in progress"} -- aborted.`,this.step):this.keysExchanged&&!0!==t?$.KeyExchange("[KeyExchange: start()] don't send KEY_HANDSHAKE_START -- exchange already done."):(this.communicationLayer.sendMessage({type:X.KEY_HANDSHAKE_START}),this.clean())}setStep(e){this.step=e,this.emit(J.KEY_INFO,e)}checkStep(e){e.length>0&&-1===e.indexOf(this.step.toString())&&console.warn(`[KeyExchange: checkStep()] Wrong Step "${this.step}" not within ${e}`)}setKeysExchanged(e){this.keysExchanged=e}areKeysExchanged(){return this.keysExchanged}getMyPublicKey(){return this.myPublicKey}getOtherPublicKey(){return this.otherPublicKey}setOtherPublicKey(e){$.KeyExchange("[KeyExchange: setOtherPubKey()]",e),this.otherPublicKey=e}encryptMessage(e){if(!this.otherPublicKey)throw new Error("encryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.encrypt(e,this.otherPublicKey)}decryptMessage(e){if(!this.otherPublicKey)throw new Error("decryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.decrypt(e)}getKeyInfo(){return{ecies:Object.assign(Object.assign({},this.myECIES.getKeyInfo()),{otherPubKey:this.otherPublicKey}),step:this.step,keysExchanged:this.areKeysExchanged()}}toString(){const e={keyInfo:this.getKeyInfo(),keysExchanged:this.keysExchanged,step:this.step};return JSON.stringify(e)}}!function(e){e.TERMINATE="terminate",e.ANSWER="answer",e.OFFER="offer",e.CANDIDATE="candidate",e.JSONRPC="jsonrpc",e.WALLET_INFO="wallet_info",e.ORIGINATOR_INFO="originator_info",e.PAUSE="pause",e.OTP="otp",e.AUTHORIZED="authorized",e.PING="ping",e.READY="ready"}(Q||(Q={}));const ee=e=>new Promise((t=>{setTimeout(t,e)})),te=(e,t,n=200)=>h(void 0,void 0,void 0,(function*(){let o;const i=Date.now();let s=!1;for(;!s;){if(s=Date.now()-i>3e5,o=t[e],void 0!==o.elapsedTime)return o;yield ee(n)}throw new Error(`RPC ${e} timed out`)})),ne=({rpcId:e,instance:t})=>h(void 0,void 0,void 0,(function*(){for(;t.state.lastRpcId===e||void 0===t.state.lastRpcId;)yield ee(200);return t.state.lastRpcId})),oe=e=>h(void 0,void 0,void 0,(function*(){var t,n,o,i,s;return $.SocketService(`[SocketService: reconnectSocket()] instance.state.socket?.connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} trying to reconnect after socketio disconnection`,e),yield ee(200),(null===(n=e.state.socket)||void 0===n?void 0:n.connected)||(e.state.resumed=!0,null===(o=e.state.socket)||void 0===o||o.connect(),e.emit(J.SOCKET_RECONNECT),null===(i=e.state.socket)||void 0===i||i.emit(J.JOIN_CHANNEL,e.state.channelId,`${e.state.context}connect_again`)),yield ee(100),null===(s=e.state.socket)||void 0===s?void 0:s.connected}));function ie(e){return t=>{$.SocketService(`[SocketService: handleDisconnect()] on 'disconnect' manualDisconnect=${e.state.manualDisconnect}`,t),e.state.manualDisconnect||(e.emit(J.SOCKET_DISCONNECTED),function(e){"undefined"!=typeof window&&"undefined"!=typeof document&&($.SocketService(`[SocketService: checkFocusAndReconnect()] hasFocus=${document.hasFocus()}`,e),document.hasFocus()?oe(e).then((t=>{$.SocketService(`SocketService::checkFocus reconnectSocket success=${t}`,e)})).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)})):window.addEventListener("focus",(()=>{oe(e).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)}))}),{once:!0}))}(e))}}const se=[{event:"clients_connected",handler:function(e,t){return n=>h(this,void 0,void 0,(function*(){var n,o,i,s,a,c,r,l;$.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected-${t}' resumed=${e.state.resumed} clientsPaused=${e.state.clientsPaused} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()} isOriginator=${e.state.isOriginator}`),e.emit(J.CLIENTS_CONNECTED,{isOriginator:e.state.isOriginator,keysExchanged:null===(o=e.state.keyExchange)||void 0===o?void 0:o.areKeysExchanged(),context:e.state.context}),e.state.resumed?(e.state.isOriginator||($.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} 'clients_connected' / keysExchanged=${null===(i=e.state.keyExchange)||void 0===i?void 0:i.areKeysExchanged()} -- backward compatibility`),null===(s=e.state.keyExchange)||void 0===s||s.start({isOriginator:null!==(a=e.state.isOriginator)&&void 0!==a&&a})),e.state.resumed=!1):e.state.clientsPaused?$.SocketService("[SocketService: handleClientsConnected()] 'clients_connected' skip sending originatorInfo on pause"):e.state.isOriginator||($.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected' / keysExchanged=${null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged()} -- backward compatibility`),null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l,force:!0})),e.state.clientsConnected=!0,e.state.clientsPaused=!1}))}},{event:"channel_created",handler:function(e,t){return n=>{$.SocketService(`[SocketService: handleChannelCreated()] context=${e.state.context} on 'channel_created-${t}'`,n),e.emit(J.CHANNEL_CREATED,n)}}},{event:"clients_disconnected",handler:function(e,t){return()=>{var n;e.state.clientsConnected=!1,$.SocketService(`[SocketService: handlesClientsDisconnected()] context=${e.state.context} on 'clients_disconnected-${t}'`),e.state.isOriginator&&!e.state.clientsPaused&&(null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.emit(J.CLIENTS_DISCONNECTED,t)}}},{event:"message",handler:function(e,t){return({id:n,message:o,error:i})=>{var s,a,c,r,l,d,u,h,m,g,E,v,y,p,C;if($.SocketService(`[SocketService handleMessage()] context=${e.state.context} on 'message' ${t} keysExchanged=${null===(s=e.state.keyExchange)||void 0===s?void 0:s.areKeysExchanged()}`,o),i)throw $.SocketService(`\n [SocketService handleMessage()] context=${e.state.context}::on 'message' error=${i}`),new Error(i);try{!function(e,t){if(t!==e.channelId)throw e.debug&&console.error(`Wrong id ${t} - should be ${e.channelId}`),new Error("Wrong id")}(e.state,n)}catch(e){return void console.error("ignore message --- wrong id ",o)}if(e.state.isOriginator&&(null==o?void 0:o.type)===X.KEY_HANDSHAKE_START)return $.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received HANDSHAKE_START isOriginator=${e.state.isOriginator}`,o),void(null===(a=e.state.keyExchange)||void 0===a||a.start({isOriginator:null!==(c=e.state.isOriginator)&&void 0!==c&&c,force:!0}));if((null==o?void 0:o.type)===Q.PING)return $.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' ping `),void e.emit(J.MESSAGE,{message:{type:"ping"}});if($.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' originator=${e.state.isOriginator}, type=${null==o?void 0:o.type}, keysExchanged=${null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged()}`),null===(l=null==o?void 0:o.type)||void 0===l?void 0:l.startsWith("key_handshake"))return $.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' emit KEY_EXCHANGE`,o),void e.emit(Z.KEY_EXCHANGE,{message:o,context:e.state.context});if(null===(d=e.state.keyExchange)||void 0===d?void 0:d.areKeysExchanged()){if(-1!==o.toString().indexOf("type"))return console.warn("[SocketService handleMessage() ::on 'message' received non encrypted unkwown message"),void e.emit(J.MESSAGE,o)}else{let t=!1;try{null===(u=e.state.keyExchange)||void 0===u||u.decryptMessage(o),t=!0}catch(e){}if(!t)return e.state.isOriginator?null===(m=e.state.keyExchange)||void 0===m||m.start({isOriginator:null!==(g=e.state.isOriginator)&&void 0!==g&&g}):e.sendMessage({type:X.KEY_HANDSHAKE_START}),void console.warn(`Message ignored because invalid key exchange status. step=${null===(E=e.state.keyExchange)||void 0===E?void 0:E.getKeyInfo().step}`,null===(v=e.state.keyExchange)||void 0===v?void 0:v.getKeyInfo(),o);console.warn("Invalid key exchange status detected --- updating it."),null===(h=e.state.keyExchange)||void 0===h||h.setKeysExchanged(!0)}const S=null===(y=e.state.keyExchange)||void 0===y?void 0:y.decryptMessage(o),f=JSON.parse(null!=S?S:"{}");if((null==f?void 0:f.type)===Q.PAUSE?e.state.clientsPaused=!0:e.state.clientsPaused=!1,e.state.isOriginator&&f.data){const t=f.data,n=e.state.rpcMethodTracker[t.id];if(n){const o=Date.now()-n.timestamp;$.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received answer for id=${t.id} method=${n.method} responseTime=${o}`,f);const i=Object.assign(Object.assign({},n),{result:t.result,error:t.error?{code:null===(p=t.error)||void 0===p?void 0:p.code,message:null===(C=t.error)||void 0===C?void 0:C.message}:void 0,elapsedTime:o});e.state.rpcMethodTracker[t.id]=i,e.emit(J.RPC_UPDATE,i),$.SocketService("[SocketService handleMessage()] HACK (wallet <7.3) update rpcMethodTracker",i),e.emit(J.AUTHORIZED)}}e.emit(J.MESSAGE,{message:f})}}},{event:"clients_waiting_to_join",handler:function(e,t){return n=>{$.SocketService(`[SocketService: handleClientsWaitingToJoin()] context=${e.state.context} on 'clients_waiting_to_join-${t}'`,n),e.emit(J.CLIENTS_WAITING,n)}}}],ae=[{event:J.KEY_INFO,handler:function(e){return t=>{$.SocketService("[SocketService: handleKeyInfo()] on 'KEY_INFO'",t),e.emit(J.KEY_INFO,t)}}},{event:J.KEYS_EXCHANGED,handler:function(e){return()=>{var t,n;$.SocketService(`[SocketService: handleKeysExchanged()] on 'keys_exchanged' keyschanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.emit(J.KEYS_EXCHANGED,{keysExchanged:null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged(),isOriginator:e.state.isOriginator});const o={keyInfo:e.getKeyInfo()};e.emit(J.SERVICE_STATUS,o)}}}];function ce(e,t){$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} setting socket listeners for channel ${t}...`);const{socket:n}=e.state,{keyExchange:o}=e.state;e.state.setupChannelListeners&&console.warn(`[SocketService: setupChannelListener()] context=${e.state.context} socket listeners already set up for channel ${t}`),n&&e.state.isOriginator&&(e.state.debug&&(null==n||n.io.on("error",(t=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=error`,t)})),null==n||n.io.on("reconnect",(t=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect`,t)})),null==n||n.io.on("reconnect_error",(t=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_error`,t)})),null==n||n.io.on("reconnect_failed",(()=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_failed`)})),null==n||n.io.on("ping",(()=>{$.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=ping`)}))),null==n||n.on("disconnect",(t=>($.SocketService(`[SocketService: setupChannelListener()] on 'disconnect' -- MetaMaskSDK socket disconnected '${t}' begin recovery...`),ie(e)(t))))),se.forEach((({event:o,handler:i})=>{const s=`${o}-${t}`;null==n||n.on(s,i(e,t))})),ae.forEach((({event:t,handler:n})=>{null==o||o.on(t,n(e))})),e.state.setupChannelListeners=!0}var re;!function(e){e.REQUEST="sdk_connect_request_started",e.REQUEST_MOBILE="sdk_connect_request_started_mobile",e.RECONNECT="sdk_reconnect_request_started",e.CONNECTED="sdk_connection_established",e.CONNECTED_MOBILE="sdk_connection_established_mobile",e.AUTHORIZED="sdk_connection_authorized",e.REJECTED="sdk_connection_rejected",e.TERMINATED="sdk_connection_terminated",e.DISCONNECTED="sdk_disconnected",e.SDK_USE_EXTENSION="sdk_use_extension",e.SDK_RPC_REQUEST="sdk_rpc_request",e.SDK_EXTENSION_UTILIZED="sdk_extension_utilized",e.SDK_USE_INAPP_BROWSER="sdk_use_inapp_browser"}(re||(re={}));const le="SDK_CONNECTION_ISSUE";var de;!function(e){e.RPC_CHECK="rpcCheck",e.SKIPPED_RPC="skippedRpc"}(de||(de={}));const ue=["eth_sendTransaction","eth_signTypedData","eth_signTransaction","wallet_requestPermissions","wallet_switchEthereumChain","eth_signTypedData_v3","eth_signTypedData_v4","metamask_connectSign","metamask_connectWith","metamask_batch"].map((e=>e.toLowerCase()));function he(e,t){var n,o,i,s;if(!e.state.channelId)throw new Error("Create a channel first");$.SocketService(`[SocketService: handleSendMessage()] context=${e.state.context} areKeysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`,t);(null===(o=null==t?void 0:t.type)||void 0===o?void 0:o.startsWith("key_handshake"))?function(e,t){var n;$.SocketService(`[SocketService: handleKeyHandshake()] context=${e.state.context}`,t),null===(n=e.state.socket)||void 0===n||n.emit(J.MESSAGE,{id:e.state.channelId,context:e.state.context,message:t})}(e,t):(!function(e,t){var n;if(!(null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()))throw $.SocketService(`[SocketService: validateKeyExchange()] context=${e.state.context} ERROR keys not exchanged`,t),new Error("Keys not exchanged BBB")}(e,t),function(e,t){var n;const o=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"",i=null==t?void 0:t.id;e.state.isOriginator&&i&&(e.state.rpcMethodTracker[i]={id:i,timestamp:Date.now(),method:o},e.emit(J.RPC_UPDATE,e.state.rpcMethodTracker[i]))}(e,t),function(e,t){var n,o;const i=null===(n=e.state.keyExchange)||void 0===n?void 0:n.encryptMessage(JSON.stringify(t)),s={id:e.state.channelId,context:e.state.context,message:i,plaintext:e.state.hasPlaintext?JSON.stringify(t):void 0};$.SocketService(`[SocketService: encryptAndSendMessage()] context=${e.state.context}`,s),t.type===Q.TERMINATE&&(e.state.manualDisconnect=!0),null===(o=e.state.socket)||void 0===o||o.emit(J.MESSAGE,s)}(e,t),e.remote.state.analytics&&t.method&&ue.includes(t.method.toLowerCase())&&F({id:null!==(i=e.remote.state.channelId)&&void 0!==i?i:"",event:re.SDK_RPC_REQUEST,sdkVersion:e.remote.state.sdkVersion,commLayerVersion:U.version,walletVersion:null===(s=e.remote.state.walletInfo)||void 0===s?void 0:s.version,params:{method:t.method,from:"mobile"}},e.remote.state.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),function(e,t){var n;return h(this,void 0,void 0,(function*(){const o=null==t?void 0:t.id,i=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"";if(e.state.isOriginator&&o)try{const n=te(o,e.state.rpcMethodTracker,200).then((e=>({type:de.RPC_CHECK,result:e}))),s=(()=>h(this,void 0,void 0,(function*(){const t=yield ne({instance:e,rpcId:o}),n=yield te(t,e.state.rpcMethodTracker,200);return{type:de.SKIPPED_RPC,result:n}})))(),a=yield Promise.race([n,s]);if(a.type===de.RPC_CHECK){const e=a.result;$.SocketService(`[SocketService:handleRpcReplies()] id=${t.id} ${i} ( ${e.elapsedTime} ms)`,e.result)}else{if(a.type!==de.SKIPPED_RPC)throw new Error(`Error handling RPC replies for ${o}`);{const{result:t}=a;console.warn(`[SocketService handleRpcReplies()] RPC METHOD HAS BEEN SKIPPED rpcid=${o} method=${i}`,t);const n=Object.assign(Object.assign({},e.state.rpcMethodTracker[o]),{error:new Error(le)});e.emit(J.RPC_UPDATE,n);const s={data:Object.assign(Object.assign({},n),{jsonrpc:"2.0"}),name:"metamask-provider"};e.emit(J.MESSAGE,{message:s})}}}catch(e){throw console.warn(`[SocketService handleRpcReplies()] Error rpcId=${t.id} ${i}`,e),e}}))}(e,t).catch((e=>{console.warn("Error handleRpcReplies",e)})))}class me extends r{constructor({otherPublicKey:e,reconnect:t,communicationLayerPreference:n,transports:o,communicationServerUrl:i,context:s,ecies:a,remote:c,logging:r}){super(),this.state={clientsConnected:!1,clientsPaused:!1,manualDisconnect:!1,lastRpcId:void 0,rpcMethodTracker:{},hasPlaintext:!1,communicationServerUrl:""},this.state.resumed=t,this.state.context=s,this.state.communicationLayerPreference=n,this.state.debug=!0===(null==r?void 0:r.serviceLayer),this.remote=c,!0===(null==r?void 0:r.serviceLayer)&&R.enable("SocketService:Layer"),this.state.communicationServerUrl=i,this.state.hasPlaintext=this.state.communicationServerUrl!==j&&!0===(null==r?void 0:r.plaintext);const l={autoConnect:!1,transports:G,withCredentials:!0};o&&(l.transports=o),$.SocketService(`[SocketService: constructor()] Socket IO url: ${this.state.communicationServerUrl}`),this.state.socket=u(i,l);const d={communicationLayer:this,otherPublicKey:e,sendPublicKey:!1,context:this.state.context,ecies:a,logging:r};this.state.keyExchange=new q(d)}resetKeys(){return e=this,$.SocketService("[SocketService: resetKeys()] Resetting keys."),void(null===(t=e.state.keyExchange)||void 0===t||t.resetKeys());var e,t}createChannel(){return function(e){var t,n,o,i;$.SocketService(`[SocketService: createChannel()] context=${e.state.context}`),(null===(t=e.state.socket)||void 0===t?void 0:t.connected)||null===(n=e.state.socket)||void 0===n||n.connect(),e.state.manualDisconnect=!1,e.state.isOriginator=!0;const s=d();return e.state.channelId=s,ce(e,s),null===(o=e.state.socket)||void 0===o||o.emit(J.JOIN_CHANNEL,s,`${e.state.context}createChannel`),{channelId:s,pubKey:(null===(i=e.state.keyExchange)||void 0===i?void 0:i.getMyPublicKey())||""}}(this)}connectToChannel({channelId:e,isOriginator:t=!1,withKeyExchange:n=!1}){return function({options:e,instance:t}){var n,o,i,s;const{channelId:a,withKeyExchange:c,isOriginator:r}=e;if($.SocketService(`[SocketService: connectToChannel()] context=${t.state.context} channelId=${a} isOriginator=${r}`,null===(n=t.state.keyExchange)||void 0===n?void 0:n.toString()),null===(o=t.state.socket)||void 0===o?void 0:o.connected)throw new Error("socket already connected");t.state.manualDisconnect=!1,null===(i=t.state.socket)||void 0===i||i.connect(),t.state.withKeyExchange=c,t.state.isOriginator=r,t.state.channelId=a,ce(t,a),null===(s=t.state.socket)||void 0===s||s.emit(J.JOIN_CHANNEL,a,`${t.state.context}_connectToChannel`)}({options:{channelId:e,isOriginator:t,withKeyExchange:n},instance:this})}getKeyInfo(){return this.state.keyExchange.getKeyInfo()}keyCheck(){var e,t;null===(t=(e=this).state.socket)||void 0===t||t.emit(J.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:X.KEY_HANDSHAKE_CHECK,pubkey:e.getKeyInfo().ecies.otherPubKey}})}getKeyExchange(){return this.state.keyExchange}sendMessage(e){return he(this,e)}ping(){return e=this,$.SocketService(`[SocketService: ping()] context=${e.state.context} originator=${e.state.isOriginator} keysExchanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.state.isOriginator&&((null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged())?(console.warn(`[SocketService:ping()] context=${e.state.context} sending READY message`),e.sendMessage({type:Q.READY})):(console.warn(`[SocketService: ping()] context=${e.state.context} starting key exchange`),null===(o=e.state.keyExchange)||void 0===o||o.start({isOriginator:null!==(i=e.state.isOriginator)&&void 0!==i&&i}))),void(null===(s=e.state.socket)||void 0===s||s.emit(J.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:Q.PING}}));var e,t,n,o,i,s}pause(){return e=this,$.SocketService(`[SocketService: pause()] context=${e.state.context}`),e.state.manualDisconnect=!0,(null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged())&&e.sendMessage({type:Q.PAUSE}),void(null===(n=e.state.socket)||void 0===n||n.disconnect());var e,t,n}isConnected(){var e;return null===(e=this.state.socket)||void 0===e?void 0:e.connected}resume(){return e=this,$.SocketService(`[SocketService: resume()] context=${e.state.context} connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} manualDisconnect=${e.state.manualDisconnect} resumed=${e.state.resumed} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`),(null===(o=e.state.socket)||void 0===o?void 0:o.connected)?$.SocketService("[SocketService: resume()] already connected."):(null===(i=e.state.socket)||void 0===i||i.connect(),$.SocketService(`[SocketService: resume()] after connecting socket --\x3e connected=${null===(s=e.state.socket)||void 0===s?void 0:s.connected}`),null===(a=e.state.socket)||void 0===a||a.emit(J.JOIN_CHANNEL,e.state.channelId,`${e.state.context}_resume`)),(null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged())?e.state.isOriginator||e.sendMessage({type:Q.READY}):e.state.isOriginator||null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l}),e.state.manualDisconnect=!1,void(e.state.resumed=!0);var e,t,n,o,i,s,a,c,r,l}getRPCMethodTracker(){return this.state.rpcMethodTracker}disconnect(e){return function(e,t){var n,o;$.SocketService(`[SocketService: disconnect()] context=${e.state.context}`,t),(null==t?void 0:t.terminate)&&(e.state.channelId=t.channelId,null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.state.rpcMethodTracker={},e.state.manualDisconnect=!0,null===(o=e.state.socket)||void 0===o||o.disconnect()}(this,e)}}var ge,Ee,ve;function ye(e){return()=>h(this,void 0,void 0,(function*(){var t,n,o;const{state:i}=e;if(i.authorized)return;yield(()=>h(this,void 0,void 0,(function*(){for(;!i.walletInfo;)yield ee(500)})))();const s="7.3".localeCompare((null===(t=i.walletInfo)||void 0===t?void 0:t.version)||"");if($.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' version=${null===(n=i.walletInfo)||void 0===n?void 0:n.version} compareValue=${s}`),1!==s)return;const a=i.platformType===Ee.MobileWeb||i.platformType===Ee.ReactNative||i.platformType===Ee.MetaMaskMobileWebview;$.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' platform=${i.platformType} secure=${a} channel=${i.channelId} walletVersion=${null===(o=i.walletInfo)||void 0===o?void 0:o.version}`),a&&(i.authorized=!0,e.emit(J.AUTHORIZED))}))}function pe(e){return t=>{const{state:n}=e;$.RemoteCommunication(`[RemoteCommunication: handleChannelCreatedEvent()] context=${n.context} on 'channel_created' channelId=${t}`),e.emit(J.CHANNEL_CREATED,t)}}function Ce(e,t){return()=>{var n,o,i,s;const{state:a}=e;if($.RemoteCommunication(`[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=${a.channelId} keysExchanged=${null===(o=null===(n=a.communicationLayer)||void 0===n?void 0:n.getKeyInfo())||void 0===o?void 0:o.keysExchanged}`),a.analytics){const e=a.isOriginator?re.REQUEST:re.REQUEST_MOBILE;F(Object.assign(Object.assign({id:null!==(i=a.channelId)&&void 0!==i?i:"",event:a.reconnection?re.RECONNECT:e},a.originatorInfo),{commLayer:t,sdkVersion:a.sdkVersion,walletVersion:null===(s=a.walletInfo)||void 0===s?void 0:s.version,commLayerVersion:U.version}),a.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}a.clientsConnected=!0,a.originatorInfoSent=!1,e.emit(J.CLIENTS_CONNECTED)}}function Se(e,t){return n=>{var o;const{state:i}=e;$.RemoteCommunication(`[RemoteCommunication: handleClientsDisconnectedEvent()] context=${i.context} on 'clients_disconnected' channelId=${n}`),i.clientsConnected=!1,e.emit(J.CLIENTS_DISCONNECTED,i.channelId),e.setConnectionStatus(B.DISCONNECTED),i.ready=!1,i.authorized=!1,i.analytics&&i.channelId&&F({id:i.channelId,event:re.DISCONNECTED,sdkVersion:i.sdkVersion,commLayer:t,commLayerVersion:U.version,walletVersion:null===(o=i.walletInfo)||void 0===o?void 0:o.version},i.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}}function fe(e){return t=>{var n;const{state:o}=e;if($.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] context=${o.context} on 'clients_waiting' numberUsers=${t} ready=${o.ready} autoStarted=${o.originatorConnectStarted}`),e.setConnectionStatus(B.WAITING),e.emit(J.CLIENTS_WAITING,t),o.originatorConnectStarted){$.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] on 'clients_waiting' watch autoStarted=${o.originatorConnectStarted} timeout`,o.autoConnectOptions);const t=(null===(n=o.autoConnectOptions)||void 0===n?void 0:n.timeout)||3e3,i=setTimeout((()=>{$.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] setTimeout(${t}) terminate channelConfig`,o.autoConnectOptions),o.originatorConnectStarted=!1,o.ready||e.setConnectionStatus(B.TIMEOUT),clearTimeout(i)}),t)}}}function ke(e,t){return n=>{var o,i,s,a,c;const{state:r}=e;$.RemoteCommunication(`[RemoteCommunication: handleKeysExchangedEvent()] context=${r.context} on commLayer.'keys_exchanged' channel=${r.channelId}`,n),(null===(i=null===(o=r.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.keysExchanged)&&e.setConnectionStatus(B.LINKED),function(e,t){var n,o,i,s;const{state:a}=e;$.RemoteCommunication(`[RemoteCommunication: setLastActiveDate()] channel=${a.channelId}`,t);const c={channelId:null!==(n=a.channelId)&&void 0!==n?n:"",validUntil:null!==(i=null===(o=a.channelConfig)||void 0===o?void 0:o.validUntil)&&void 0!==i?i:0,lastActive:t.getTime()};null===(s=a.storageManager)||void 0===s||s.persistChannelConfig(c)}(e,new Date),r.analytics&&r.channelId&&F({id:r.channelId,event:n.isOriginator?re.CONNECTED:re.CONNECTED_MOBILE,sdkVersion:r.sdkVersion,commLayer:t,commLayerVersion:U.version,walletVersion:null===(s=r.walletInfo)||void 0===s?void 0:s.version},r.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),r.isOriginator=n.isOriginator,n.isOriginator||(null===(a=r.communicationLayer)||void 0===a||a.sendMessage({type:Q.READY}),r.ready=!0,r.paused=!1),n.isOriginator&&!r.originatorInfoSent&&(null===(c=r.communicationLayer)||void 0===c||c.sendMessage({type:Q.ORIGINATOR_INFO,originatorInfo:r.originatorInfo,originator:r.originatorInfo}),r.originatorInfoSent=!0)}}function xe(e,t){const{state:n}=t;if($.RemoteCommunication(`[RemoteCommunication: onCommunicationLayerMessage()] context=${n.context} on 'message' typeof=${typeof e}`,e),t.state.ready=!0,n.isOriginator||e.type!==Q.ORIGINATOR_INFO)if(n.isOriginator&&e.type===Q.WALLET_INFO)!function(e,t){const{state:n}=e;n.walletInfo=t.walletInfo,n.paused=!1}(t,e);else{if(e.type===Q.TERMINATE)!function(e){const{state:t}=e;t.isOriginator&&(Ae({options:{terminate:!0,sendMessage:!1},instance:e}),console.debug(),e.emit(J.TERMINATE))}(t);else if(e.type===Q.PAUSE)!function(e){const{state:t}=e;t.paused=!0,e.setConnectionStatus(B.PAUSED)}(t);else if(e.type===Q.READY&&n.isOriginator)!function(e){const{state:t}=e;e.setConnectionStatus(B.LINKED);const n=t.paused;t.paused=!1,e.emit(J.CLIENTS_READY,{isOriginator:t.isOriginator,walletInfo:t.walletInfo}),n&&(t.authorized=!0,e.emit(J.AUTHORIZED))}(t);else{if(e.type===Q.OTP&&n.isOriginator)return void function(e,t){var n;const{state:o}=e;e.emit(J.OTP,t.otpAnswer),1==="6.6".localeCompare((null===(n=o.walletInfo)||void 0===n?void 0:n.version)||"")&&(console.warn("RemoteCommunication::on 'otp' -- backward compatibility <6.6 -- triger eth_requestAccounts"),e.emit(J.SDK_RPC_CALL,{method:V.ETH_REQUESTACCOUNTS,params:[]}))}(t,e);e.type===Q.AUTHORIZED&&n.isOriginator&&function(e){const{state:t}=e;t.authorized=!0,e.emit(J.AUTHORIZED)}(t)}t.emit(J.MESSAGE,e)}else!function(e,t){var n;const{state:o}=e;null===(n=o.communicationLayer)||void 0===n||n.sendMessage({type:Q.WALLET_INFO,walletInfo:o.walletInfo}),o.originatorInfo=t.originatorInfo||t.originator,e.emit(J.CLIENTS_READY,{isOriginator:o.isOriginator,originatorInfo:o.originatorInfo}),o.paused=!1}(t,e)}function Ie(e,t){var n,o;return h(this,void 0,void 0,(function*(){const{state:i}=e;$.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} paused=${i.paused} ready=${i.ready} authorized=${i.authorized} socket=${null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected()} clientsConnected=${i.clientsConnected} status=${i._connectionStatus}`,t),!i.paused&&i.ready&&(null===(o=i.communicationLayer)||void 0===o?void 0:o.isConnected())&&i.clientsConnected||($.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} SKIP message waiting for MM mobile readiness.`),yield new Promise((t=>{e.once(J.CLIENTS_READY,t)})),$.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} AFTER SKIP / READY -- sending pending message`));try{yield function(e,t){return h(this,void 0,void 0,(function*(){return new Promise((n=>{var o,i,s,a;const{state:c}=e;if($.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} ready=${c.ready} authorized=${c.authorized} method=${t.method}`),1==="7.3".localeCompare((null===(o=c.walletInfo)||void 0===o?void 0:o.version)||""))return $.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] compatibility hack wallet version > ${null===(i=c.walletInfo)||void 0===i?void 0:i.version}`),null===(s=c.communicationLayer)||void 0===s||s.sendMessage(t),void n();!c.isOriginator||c.authorized?(null===(a=c.communicationLayer)||void 0===a||a.sendMessage(t),n()):e.once(J.AUTHORIZED,(()=>{var e;$.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} AFTER SKIP / AUTHORIZED -- sending pending message`),null===(e=c.communicationLayer)||void 0===e||e.sendMessage(t),n()}))}))}))}(e,t)}catch(e){throw console.error(`[RemoteCommunication: sendMessage()] context=${i.context} ERROR`,e),e}}))}function _e(e){return t=>{let n=t;t.message&&(n=n.message),xe(n,e)}}function Ke(e){return()=>{const{state:t}=e;$.RemoteCommunication("[RemoteCommunication: handleSocketReconnectEvent()] on 'socket_reconnect' -- reset key exchange status / set ready to false"),t.ready=!1,t.authorized=!1,W(t),e.emitServiceStatusEvent()}}function Oe(e){return()=>{const{state:t}=e;$.RemoteCommunication("[RemoteCommunication: handleSocketDisconnectedEvent()] on 'socket_Disconnected' set ready to false"),t.ready=!1}}function Ae({options:e,instance:t}){var n,o,i,s,a,c;const{state:r}=t;$.RemoteCommunication(`[RemoteCommunication: disconnect()] channel=${r.channelId}`,e),r.ready=!1,r.paused=!1,(null==e?void 0:e.terminate)?(null===(n=r.storageManager)||void 0===n||n.terminate(null!==(o=r.channelId)&&void 0!==o?o:""),(null===(i=r.communicationLayer)||void 0===i?void 0:i.getKeyInfo().keysExchanged)&&(null==e?void 0:e.sendMessage)&&(null===(s=r.communicationLayer)||void 0===s||s.sendMessage({type:Q.TERMINATE})),r.channelId=d(),e.channelId=r.channelId,r.channelConfig=void 0,r.originatorConnectStarted=!1,null===(a=r.communicationLayer)||void 0===a||a.disconnect(e),t.setConnectionStatus(B.TERMINATED)):(null===(c=r.communicationLayer)||void 0===c||c.disconnect(e),t.setConnectionStatus(B.DISCONNECTED))}!function(e){e.SOCKET="socket"}(ge||(ge={})),function(e){e.NonBrowser="nodejs",e.MetaMaskMobileWebview="in-app-browser",e.DesktopWeb="web-desktop",e.MobileWeb="web-mobile",e.ReactNative="react-native"}(Ee||(Ee={}));class Ne extends r{constructor({platformType:e,communicationLayerPreference:t,otherPublicKey:n,reconnect:o,walletInfo:i,dappMetadata:s,transports:a,context:c,ecies:r,analytics:l=!1,storage:d,sdkVersion:u,communicationServerUrl:h=j,logging:m,autoConnect:g={timeout:3e3}}){super(),this.state={ready:!1,authorized:!1,isOriginator:!1,paused:!1,platformType:"metamask-mobile",analytics:!1,reconnection:!1,originatorInfoSent:!1,communicationServerUrl:j,context:"",clientsConnected:!1,sessionDuration:z,originatorConnectStarted:!1,debug:!1,_connectionStatus:B.DISCONNECTED},this.state.otherPublicKey=n,this.state.dappMetadata=s,this.state.walletInfo=i,this.state.transports=a,this.state.platformType=e,this.state.analytics=l,this.state.isOriginator=!n,this.state.communicationServerUrl=h,this.state.context=c,this.state.sdkVersion=u,this.setMaxListeners(50),this.setConnectionStatus(B.DISCONNECTED),(null==d?void 0:d.duration)&&(this.state.sessionDuration=z),this.state.storageOptions=d,this.state.autoConnectOptions=g,this.state.debug=!0===(null==m?void 0:m.remoteLayer),!0===(null==m?void 0:m.remoteLayer)&&R.enable("RemoteCommunication:Layer"),this.state.logging=m,(null==d?void 0:d.storageManager)&&(this.state.storageManager=d.storageManager),this.initCommunicationLayer({communicationLayerPreference:t,otherPublicKey:n,reconnect:o,ecies:r,communicationServerUrl:h}),this.emitServiceStatusEvent()}initCommunicationLayer({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=j}){return function({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=j,instance:s}){var a,c,r,l,d;const{state:u}=s;if(e!==ge.SOCKET)throw new Error("Invalid communication protocol");u.communicationLayer=new me({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,transports:u.transports,communicationServerUrl:i,context:u.context,ecies:o,logging:u.logging,remote:s});let h="undefined"!=typeof document&&document.URL||"",m="undefined"!=typeof document&&document.title||"";(null===(a=u.dappMetadata)||void 0===a?void 0:a.url)&&(h=u.dappMetadata.url),(null===(c=u.dappMetadata)||void 0===c?void 0:c.name)&&(m=u.dappMetadata.name);const g={url:h,title:m,source:null===(r=u.dappMetadata)||void 0===r?void 0:r.source,icon:(null===(l=u.dappMetadata)||void 0===l?void 0:l.iconUrl)||(null===(d=u.dappMetadata)||void 0===d?void 0:d.base64Icon),platform:u.platformType,apiVersion:U.version};u.originatorInfo=g;const E={[J.AUTHORIZED]:ye(s),[J.MESSAGE]:_e(s),[J.CLIENTS_CONNECTED]:Ce(s,e),[J.KEYS_EXCHANGED]:ke(s,e),[J.SOCKET_DISCONNECTED]:Oe(s),[J.SOCKET_RECONNECT]:Ke(s),[J.CLIENTS_DISCONNECTED]:Se(s,e),[J.KEY_INFO]:()=>{s.emitServiceStatusEvent()},[J.CHANNEL_CREATED]:pe(s),[J.CLIENTS_WAITING]:fe(s),[J.RPC_UPDATE]:e=>{s.emit(J.RPC_UPDATE,e)}};for(const[e,t]of Object.entries(E))try{u.communicationLayer.on(e,t)}catch(t){console.error(`Error registering handler for ${e}:`,t)}}({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i,instance:this})}originatorSessionConnect(){return h(this,void 0,void 0,(function*(){return yield function(e){var t,n,o;return h(this,void 0,void 0,(function*(){const{state:i}=e;if(!i.storageManager)return void $.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] no storage manager defined - skip");const s=yield i.storageManager.getPersistedChannelConfig(null!==(t=i.channelId)&&void 0!==t?t:"");if($.RemoteCommunication(`[RemoteCommunication: originatorSessionConnect()] autoStarted=${i.originatorConnectStarted} channelConfig`,s),null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected())return $.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] socket already connected - skip"),s;if(s){if(s.validUntil>Date.now())return i.channelConfig=s,i.originatorConnectStarted=!0,i.channelId=null==s?void 0:s.channelId,i.reconnection=!0,null===(o=i.communicationLayer)||void 0===o||o.connectToChannel({channelId:s.channelId,isOriginator:!0}),s;$.RemoteCommunication("[RemoteCommunication: autoConnect()] Session has expired")}i.originatorConnectStarted=!1}))}(this)}))}generateChannelIdConnect(){return h(this,void 0,void 0,(function*(){return function(e){var t,n,o,i,s;if(!e.communicationLayer)throw new Error("communication layer not initialized");if(e.ready)throw new Error("Channel already connected");if(e.channelId&&(null===(t=e.communicationLayer)||void 0===t?void 0:t.isConnected()))return console.warn("Channel already exists -- interrupt generateChannelId",e.channelConfig),e.channelConfig={channelId:e.channelId,validUntil:Date.now()+e.sessionDuration},null===(n=e.storageManager)||void 0===n||n.persistChannelConfig(e.channelConfig),{channelId:e.channelId,pubKey:null===(i=null===(o=e.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.ecies.public};$.RemoteCommunication("[RemoteCommunication: generateChannelId()]"),W(e);const a=e.communicationLayer.createChannel();$.RemoteCommunication("[RemoteCommunication: generateChannelId()] channel created",a);const c={channelId:a.channelId,validUntil:Date.now()+e.sessionDuration};return e.channelId=a.channelId,e.channelConfig=c,null===(s=e.storageManager)||void 0===s||s.persistChannelConfig(c),{channelId:e.channelId,pubKey:a.pubKey}}(this.state)}))}clean(){return W(this.state)}connectToChannel(e,t){return function({channelId:e,withKeyExchange:t,state:n}){var o,i,s;if(!l(e))throw $.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} invalid channel channelId=${e}`),new Error(`Invalid channel ${e}`);if($.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} channelId=${e}`),null===(o=n.communicationLayer)||void 0===o?void 0:o.isConnected())return void $.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} already connected - interrupt connection.`);n.channelId=e,null===(i=n.communicationLayer)||void 0===i||i.connectToChannel({channelId:e,withKeyExchange:t});const a={channelId:e,validUntil:Date.now()+n.sessionDuration};n.channelConfig=a,null===(s=n.storageManager)||void 0===s||s.persistChannelConfig(a)}({channelId:e,withKeyExchange:t,state:this.state})}sendMessage(e){return Ie(this,e)}testStorage(){return h(this,void 0,void 0,(function*(){return function(e){var t,n;return h(this,void 0,void 0,(function*(){const o=yield null===(t=e.storageManager)||void 0===t?void 0:t.getPersistedChannelConfig(null!==(n=e.channelId)&&void 0!==n?n:"");$.RemoteCommunication("[RemoteCommunication: testStorage()] res",o)}))}(this.state)}))}getChannelConfig(){return this.state.channelConfig}isReady(){return this.state.ready}isConnected(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.isConnected()}isAuthorized(){return this.state.authorized}isPaused(){return this.state.paused}getCommunicationLayer(){return this.state.communicationLayer}ping(){var e;$.RemoteCommunication(`[RemoteCommunication: ping()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.ping()}keyCheck(){var e;$.RemoteCommunication(`[RemoteCommunication: keyCheck()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.keyCheck()}setConnectionStatus(e){this.state._connectionStatus!==e&&(this.state._connectionStatus=e,this.emit(J.CONNECTION_STATUS,e),this.emitServiceStatusEvent())}emitServiceStatusEvent(){this.emit(J.SERVICE_STATUS,this.getServiceStatus())}getConnectionStatus(){return this.state._connectionStatus}getServiceStatus(){return{originatorInfo:this.state.originatorInfo,keyInfo:this.getKeyInfo(),connectionStatus:this.state._connectionStatus,channelConfig:this.state.channelConfig,channelId:this.state.channelId}}getKeyInfo(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getKeyInfo()}resetKeys(){var e;null===(e=this.state.communicationLayer)||void 0===e||e.resetKeys()}setOtherPublicKey(e){var t;const n=null===(t=this.state.communicationLayer)||void 0===t?void 0:t.getKeyExchange();if(!n)throw new Error("KeyExchange is not initialized.");n.getOtherPublicKey()!==e&&n.setOtherPublicKey(e)}pause(){var e;$.RemoteCommunication(`[RemoteCommunication: pause()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.pause(),this.setConnectionStatus(B.PAUSED)}getVersion(){return U.version}resume(){return function(e){var t;const{state:n}=e;$.RemoteCommunication(`[RemoteCommunication: resume()] channel=${n.channelId}`),null===(t=n.communicationLayer)||void 0===t||t.resume(),e.setConnectionStatus(B.LINKED)}(this)}getChannelId(){return this.state.channelId}getRPCMethodTracker(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getRPCMethodTracker()}disconnect(e){return Ae({options:e,instance:this})}}!function(e){e.RENEW="renew",e.LINK="link"}(ve||(ve={}));export{ve as AutoConnectType,ge as CommunicationLayerPreference,B as ConnectionStatus,j as DEFAULT_SERVER_URL,Y as ECIES,J as EventType,X as KeyExchangeMessageType,Q as MessageType,Ee as PlatformType,Ne as RemoteCommunication,F as SendAnalytics,me as SocketService,re as TrackingEvents};
//# sourceMappingURL=metamask-sdk-communication-layer.js.map

@@ -1,2 +0,2 @@

export declare const DEFAULT_SERVER_URL = "https://metamask-sdk-socket.metafi.codefi.network/";
export declare const DEFAULT_SERVER_URL = "https://metamask-sdk.api.cx.metamask.io/";
export declare const DEFAULT_SOCKET_TRANSPORTS: string[];

@@ -3,0 +3,0 @@ export declare const MIN_IN_MS: number;

@@ -1,2 +0,2 @@

import e from"cross-fetch";import{Buffer as t}from"buffer";import{PrivateKey as n,encrypt as o,decrypt as i}from"eciesjs";import{EventEmitter2 as s}from"eventemitter2";import{validate as a,v4 as c}from"uuid";import{io as r}from"socket.io-client";function l(e,t,n,o){return new(n||(n=Promise))((function(i,s){function a(e){try{r(o.next(e))}catch(e){s(e)}}function c(e){try{r(o.throw(e))}catch(e){s(e)}}function r(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,c)}r((o=o.apply(e,t||[])).next())}))}function d(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var u,h,m={exports:{}};function g(){if(h)return u;h=1;var e=1e3,t=60*e,n=60*t,o=24*n,i=7*o,s=365.25*o;function a(e,t,n,o){var i=t>=1.5*n;return Math.round(e/n)+" "+o+(i?"s":"")}return u=function(c,r){r=r||{};var l=typeof c;if("string"===l&&c.length>0)return function(a){if((a=String(a)).length>100)return;var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!c)return;var r=parseFloat(c[1]);switch((c[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*s;case"weeks":case"week":case"w":return r*i;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*n;case"minutes":case"minute":case"mins":case"min":case"m":return r*t;case"seconds":case"second":case"secs":case"sec":case"s":return r*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(c);if("number"===l&&isFinite(c))return r.long?function(i){var s=Math.abs(i);if(s>=o)return a(i,s,o,"day");if(s>=n)return a(i,s,n,"hour");if(s>=t)return a(i,s,t,"minute");if(s>=e)return a(i,s,e,"second");return i+" ms"}(c):function(i){var s=Math.abs(i);if(s>=o)return Math.round(i/o)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))}}var E=function(e){function t(e){let o,i,s,a=null;function c(...e){if(!c.enabled)return;const n=c,i=Number(new Date),s=i-(o||i);n.diff=s,n.prev=o,n.curr=i,o=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((o,i)=>{if("%%"===o)return"%";a++;const s=t.formatters[i];if("function"==typeof s){const t=e[a];o=s.call(n,t),e.splice(a,1),a--}return o})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return c.namespace=e,c.useColors=t.useColors(),c.color=t.selectColor(e),c.extend=n,c.destroy=t.destroy,Object.defineProperty(c,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{a=e}}),"function"==typeof t.init&&t.init(c),c}function n(e,n){const o=t(this.namespace+(void 0===n?":":n)+e);return o.log=this.log,o}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const o=("string"==typeof e?e:"").split(/[\s,]+/),i=o.length;for(n=0;n<i;n++)o[n]&&("-"===(e=o[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,o;for(n=0,o=t.skips.length;n<o;n++)if(t.skips[n].test(e))return!1;for(n=0,o=t.names.length;n<o;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=g(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(o++,"%c"===e&&(i=o))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=E(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(m,m.exports);var v=d(m.exports);const y=v("KeyExchange:Layer"),C=v("SocketService:Layer"),p=v("Ecies:Layer"),S=v("RemoteCommunication:Layer");y.color="##95c44e",C.color="#f638d7",p.color="#465b9c",S.color="#47a2be";const f={KeyExchange:y,SocketService:C,Ecies:p,RemoteCommunication:S};let k,x=[],I=[];function K(t){return l(this,void 0,void 0,(function*(){if(!k||!t)return;!function(){const e=I;I=x,x=e}();const n=k.endsWith("/")?`${k}debug`:`${k}/debug`,o=Object.assign({},t);if(delete o.params,t.params)for(const[e,n]of Object.entries(t.params))o[e]=n;const i=JSON.stringify(o);f.RemoteCommunication(`[sendBufferedEvents] Sending ${x.length} analytics events to ${n}`);try{const t=yield e(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:i}),o=yield t.text();f.RemoteCommunication(`[sendBufferedEvents] Response: ${o}`),x.length=0}catch(e){console.warn("Error sending analytics",e)}}))}const _=(e,t)=>l(void 0,void 0,void 0,(function*(){var n;k=t,n=e,I.push(n),K(e).catch((()=>{}))}));class N{constructor(e){this.enabled=!0,(null==e?void 0:e.debug)&&v.enable("Ecies:Layer"),(null==e?void 0:e.pkey)?this.ecies=n.fromHex(e.pkey):this.ecies=new n,f.Ecies("[ECIES constructor()] initialized secret: ",this.ecies.toHex()),f.Ecies("[ECIES constructor()] initialized public: ",this.ecies.publicKey.toHex()),f.Ecies("[ECIES constructor()] init with",this)}generateECIES(){this.ecies=new n}getPublicKey(){return this.ecies.publicKey.toHex()}encrypt(e,n){let i=e;if(this.enabled)try{f.Ecies("[ECIES: encrypt()] using otherPublicKey",n);const s=t.from(e),a=o(n,s);i=t.from(a).toString("base64")}catch(t){throw f.Ecies("[ECIES: encrypt()] error encrypt:",t),f.Ecies("[ECIES: encrypt()] private: ",this.ecies.toHex()),f.Ecies("[ECIES: encrypt()] data: ",e),f.Ecies("[ECIES: encrypt()] otherkey: ",n),t}return i}decrypt(e){let n=e;if(this.enabled)try{f.Ecies("[ECIES: decrypt()] using privateKey",this.ecies.toHex());const o=t.from(e.toString(),"base64");n=i(this.ecies.toHex(),o).toString()}catch(t){throw f.Ecies("[ECIES: decrypt()] error decrypt",t),f.Ecies("[ECIES: decrypt()] private: ",this.ecies.toHex()),f.Ecies("[ECIES: decrypt()] encryptedData: ",e),t}return n}getKeyInfo(){return{private:this.ecies.toHex(),public:this.ecies.publicKey.toHex()}}toString(){f.Ecies("[ECIES: toString()]",this.getKeyInfo())}}var A={name:"@metamask/sdk-communication-layer",version:"0.17.0",description:"",homepage:"https://github.com/MetaMask/metamask-sdk#readme",bugs:{url:"https://github.com/MetaMask/metamask-sdk/issues"},repository:{type:"git",url:"https://github.com/MetaMask/metamask-sdk.git",directory:"packages/sdk-communication-layer"},main:"dist/node/cjs/metamask-sdk-communication-layer.js",unpkg:"dist/browser/umd/metamask-sdk-communication-layer.js",module:"dist/node/es/metamask-sdk-communication-layer.js",browser:"dist/browser/es/metamask-sdk-communication-layer.js","react-native":"dist/react-native/es/metamask-sdk-communication-layer.js",types:"dist/browser/es/src/index.d.ts",files:["/dist"],scripts:{build:"rimraf dist && rollup -c --bundleConfigAsCjs","build:tsc":"tsc","build:dev":"rimraf dist && NODE_ENV=dev rollup -c --bundleConfigAsCjs","build:post-tsc":"echo 'N/A'","build:pre-tsc":"echo 'N/A'",size:"size-limit",clean:"rimraf ./dist",lint:"yarn lint:eslint && yarn lint:misc --check","lint:changelog":"../../scripts/validate-changelog.sh @metamask/sdk-communication-layer","lint:eslint":"eslint . --cache --ext js,ts","lint:fix":"yarn lint:eslint --fix && yarn lint:misc --write","lint:misc":"prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path ../../.gitignore","prepare-manifest:preview":"../../scripts/prepare-preview-manifest.sh","publish:preview":"yarn npm publish --tag preview",prepack:"../../scripts/prepack.sh",reset:"yarn clean && rimraf ./node_modules/",test:"jest","test:coverage":"jest --coverage","test:ci":"jest --coverage --passWithNoTests --setupFilesAfterEnv ./jest-preload.js","test:dev":"jest",watch:"rollup -c --bundleConfigAsCjs -w"},dependencies:{bufferutil:"^4.0.8","date-fns":"^2.29.3",debug:"^4.3.4","utf-8-validate":"^6.0.3",uuid:"^8.3.2"},devDependencies:{"@jest/globals":"^29.3.1","@lavamoat/allow-scripts":"^2.3.1","@metamask/auto-changelog":"3.1.0","@metamask/eslint-config":"^6.0.0","@metamask/eslint-config-nodejs":"^6.0.0","@metamask/eslint-config-typescript":"^6.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.0.2","@rollup/plugin-terser":"^0.4.1","@size-limit/preset-big-lib":"^11.0.2","@types/jest":"^29.2.4","@types/node":"^20.1.3","@types/uuid":"^9.0.0","@typescript-eslint/eslint-plugin":"^4.26.0","@typescript-eslint/parser":"^4.26.0","cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eslint:"^7.30.0","eslint-config-prettier":"^8.3.0","eslint-plugin-import":"^2.23.4","eslint-plugin-jest":"^24.4.0","eslint-plugin-jsdoc":"^36.1.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.4.0",eventemitter2:"^6.4.7",jest:"^29.3.1",prettier:"^2.3.0",rimraf:"^3.0.2",rollup:"^3.21.7","rollup-plugin-jscc":"^2.0.0","rollup-plugin-natives":"^0.7.5","rollup-plugin-node-builtins":"^2.1.2","rollup-plugin-node-globals":"^1.4.0","rollup-plugin-peer-deps-external":"^2.2.4","rollup-plugin-sizes":"^1.0.6","rollup-plugin-typescript2":"^0.31.2","rollup-plugin-visualizer":"^5.9.2","size-limit":"^11.0.2","socket.io-client":"^4.5.1","stream-browserify":"^3.0.0","ts-jest":"^29.0.3","ts-node":"^10.9.1",typescript:"^4.3.2"},peerDependencies:{"cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eventemitter2:"^6.4.7","readable-stream":"^3.6.2","socket.io-client":"^4.5.1"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},lavamoat:{allowScripts:{"@lavamoat/preinstall-always-fail":!1,canvas:!0,"eciesjs>secp256k1":!1,"socket.io-client>engine.io-client>ws>bufferutil":!1,"socket.io-client>engine.io-client>ws>utf-8-validate":!1,bufferutil:!1,"utf-8-validate":!1}}};const O="https://metamask-sdk-socket.metafi.codefi.network/",T=["websocket"],R=6048e5,b={METAMASK_GETPROVIDERSTATE:"metamask_getProviderState",ETH_REQUESTACCOUNTS:"eth_requestAccounts"};function w(e){const{context:t}=e;f.RemoteCommunication(`[RemoteCommunication: clean()] context=${t}`),e.channelConfig=void 0,e.ready=!1,e.originatorConnectStarted=!1}var D,$,L,M,P;!function(e){e.DISCONNECTED="disconnected",e.WAITING="waiting",e.TIMEOUT="timeout",e.LINKED="linked",e.PAUSED="paused",e.TERMINATED="terminated"}(D||(D={})),function(e){e.KEY_INFO="key_info",e.SERVICE_STATUS="service_status",e.PROVIDER_UPDATE="provider_update",e.RPC_UPDATE="rpc_update",e.KEYS_EXCHANGED="keys_exchanged",e.JOIN_CHANNEL="join_channel",e.CHANNEL_CREATED="channel_created",e.CLIENTS_CONNECTED="clients_connected",e.CLIENTS_DISCONNECTED="clients_disconnected",e.CLIENTS_WAITING="clients_waiting",e.CLIENTS_READY="clients_ready",e.SOCKET_DISCONNECTED="socket_disconnected",e.SOCKET_RECONNECT="socket_reconnect",e.OTP="otp",e.SDK_RPC_CALL="sdk_rpc_call",e.AUTHORIZED="authorized",e.CONNECTION_STATUS="connection_status",e.MESSAGE="message",e.TERMINATE="terminate"}($||($={})),function(e){e.KEY_EXCHANGE="key_exchange"}(L||(L={})),function(e){e.KEY_HANDSHAKE_START="key_handshake_start",e.KEY_HANDSHAKE_CHECK="key_handshake_check",e.KEY_HANDSHAKE_SYN="key_handshake_SYN",e.KEY_HANDSHAKE_SYNACK="key_handshake_SYNACK",e.KEY_HANDSHAKE_ACK="key_handshake_ACK",e.KEY_HANDSHAKE_NONE="none"}(M||(M={}));class H extends s{constructor({communicationLayer:e,otherPublicKey:t,context:n,ecies:o,logging:i}){super(),this.keysExchanged=!1,this.step=M.KEY_HANDSHAKE_NONE,this.debug=!1,this.context=n,this.myECIES=new N(Object.assign(Object.assign({},o),{debug:null==i?void 0:i.eciesLayer})),this.communicationLayer=e,this.myPublicKey=this.myECIES.getPublicKey(),this.debug=!0===(null==i?void 0:i.keyExchangeLayer),(null==i?void 0:i.keyExchangeLayer)&&v.enable("KeyExchange:Layer"),t&&this.setOtherPublicKey(t),this.communicationLayer.on(L.KEY_EXCHANGE,this.onKeyExchangeMessage.bind(this))}onKeyExchangeMessage(e){f.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} keysExchanged=${this.keysExchanged}`,e);const{message:t}=e;this.keysExchanged&&f.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} received handshake while already exchanged. step=${this.step} otherPubKey=${this.otherPublicKey}`),this.emit($.KEY_INFO,t.type),t.type===M.KEY_HANDSHAKE_SYN?(this.checkStep([M.KEY_HANDSHAKE_NONE,M.KEY_HANDSHAKE_ACK]),f.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYN",t),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_SYNACK,pubkey:this.myPublicKey}),this.setStep(M.KEY_HANDSHAKE_ACK)):t.type===M.KEY_HANDSHAKE_SYNACK?(this.checkStep([M.KEY_HANDSHAKE_SYNACK,M.KEY_HANDSHAKE_ACK,M.KEY_HANDSHAKE_NONE]),f.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYNACK"),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_ACK}),this.keysExchanged=!0,this.setStep(M.KEY_HANDSHAKE_ACK),this.emit($.KEYS_EXCHANGED)):t.type===M.KEY_HANDSHAKE_ACK&&(f.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_ACK set keysExchanged to true!"),this.checkStep([M.KEY_HANDSHAKE_ACK,M.KEY_HANDSHAKE_NONE]),this.keysExchanged=!0,this.setStep(M.KEY_HANDSHAKE_ACK),this.emit($.KEYS_EXCHANGED))}resetKeys(e){this.clean(),this.myECIES=new N(e)}clean(){f.KeyExchange(`[KeyExchange: clean()] context=${this.context} reset handshake state`),this.setStep(M.KEY_HANDSHAKE_NONE),this.emit($.KEY_INFO,this.step),this.keysExchanged=!1}start({isOriginator:e,force:t}){f.KeyExchange(`[KeyExchange: start()] context=${this.context} isOriginator=${e} step=${this.step} force=${t} keysExchanged=${this.keysExchanged}`),e?!(this.keysExchanged||this.step!==M.KEY_HANDSHAKE_NONE&&this.step!==M.KEY_HANDSHAKE_SYNACK)||t?(f.KeyExchange(`[KeyExchange: start()] context=${this.context} -- start key exchange (force=${t}) -- step=${this.step}`,this.step),this.clean(),this.setStep(M.KEY_HANDSHAKE_SYNACK),this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_SYN,pubkey:this.myPublicKey})):f.KeyExchange(`[KeyExchange: start()] context=${this.context} -- key exchange already ${this.keysExchanged?"done":"in progress"} -- aborted.`,this.step):this.keysExchanged&&!0!==t?f.KeyExchange("[KeyExchange: start()] don't send KEY_HANDSHAKE_START -- exchange already done."):(this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_START}),this.clean())}setStep(e){this.step=e,this.emit($.KEY_INFO,e)}checkStep(e){e.length>0&&-1===e.indexOf(this.step.toString())&&console.warn(`[KeyExchange: checkStep()] Wrong Step "${this.step}" not within ${e}`)}setKeysExchanged(e){this.keysExchanged=e}areKeysExchanged(){return this.keysExchanged}getMyPublicKey(){return this.myPublicKey}getOtherPublicKey(){return this.otherPublicKey}setOtherPublicKey(e){f.KeyExchange("[KeyExchange: setOtherPubKey()]",e),this.otherPublicKey=e}encryptMessage(e){if(!this.otherPublicKey)throw new Error("encryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.encrypt(e,this.otherPublicKey)}decryptMessage(e){if(!this.otherPublicKey)throw new Error("decryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.decrypt(e)}getKeyInfo(){return{ecies:Object.assign(Object.assign({},this.myECIES.getKeyInfo()),{otherPubKey:this.otherPublicKey}),step:this.step,keysExchanged:this.areKeysExchanged()}}toString(){const e={keyInfo:this.getKeyInfo(),keysExchanged:this.keysExchanged,step:this.step};return JSON.stringify(e)}}!function(e){e.TERMINATE="terminate",e.ANSWER="answer",e.OFFER="offer",e.CANDIDATE="candidate",e.JSONRPC="jsonrpc",e.WALLET_INFO="wallet_info",e.ORIGINATOR_INFO="originator_info",e.PAUSE="pause",e.OTP="otp",e.AUTHORIZED="authorized",e.PING="ping",e.READY="ready"}(P||(P={}));const F=e=>new Promise((t=>{setTimeout(t,e)})),Y=(e,t,n=200)=>l(void 0,void 0,void 0,(function*(){let o;const i=Date.now();let s=!1;for(;!s;){if(s=Date.now()-i>3e5,o=t[e],void 0!==o.elapsedTime)return o;yield F(n)}throw new Error(`RPC ${e} timed out`)})),U=({rpcId:e,instance:t})=>l(void 0,void 0,void 0,(function*(){for(;t.state.lastRpcId===e||void 0===t.state.lastRpcId;)yield F(200);return t.state.lastRpcId})),j=e=>l(void 0,void 0,void 0,(function*(){var t,n,o,i,s;return f.SocketService(`[SocketService: reconnectSocket()] instance.state.socket?.connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} trying to reconnect after socketio disconnection`,e),yield F(200),(null===(n=e.state.socket)||void 0===n?void 0:n.connected)||(e.state.resumed=!0,null===(o=e.state.socket)||void 0===o||o.connect(),e.emit($.SOCKET_RECONNECT),null===(i=e.state.socket)||void 0===i||i.emit($.JOIN_CHANNEL,e.state.channelId,`${e.state.context}connect_again`)),yield F(100),null===(s=e.state.socket)||void 0===s?void 0:s.connected}));function z(e){return t=>{f.SocketService(`[SocketService: handleDisconnect()] on 'disconnect' manualDisconnect=${e.state.manualDisconnect}`,t),e.state.manualDisconnect||(e.emit($.SOCKET_DISCONNECTED),function(e){"undefined"!=typeof window&&"undefined"!=typeof document&&(f.SocketService(`[SocketService: checkFocusAndReconnect()] hasFocus=${document.hasFocus()}`,e),document.hasFocus()?j(e).then((t=>{f.SocketService(`SocketService::checkFocus reconnectSocket success=${t}`,e)})).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)})):window.addEventListener("focus",(()=>{j(e).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)}))}),{once:!0}))}(e))}}const G=[{event:"clients_connected",handler:function(e,t){return n=>l(this,void 0,void 0,(function*(){var n,o,i,s,a,c,r,l;f.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected-${t}' resumed=${e.state.resumed} clientsPaused=${e.state.clientsPaused} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()} isOriginator=${e.state.isOriginator}`),e.emit($.CLIENTS_CONNECTED,{isOriginator:e.state.isOriginator,keysExchanged:null===(o=e.state.keyExchange)||void 0===o?void 0:o.areKeysExchanged(),context:e.state.context}),e.state.resumed?(e.state.isOriginator||(f.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} 'clients_connected' / keysExchanged=${null===(i=e.state.keyExchange)||void 0===i?void 0:i.areKeysExchanged()} -- backward compatibility`),null===(s=e.state.keyExchange)||void 0===s||s.start({isOriginator:null!==(a=e.state.isOriginator)&&void 0!==a&&a})),e.state.resumed=!1):e.state.clientsPaused?f.SocketService("[SocketService: handleClientsConnected()] 'clients_connected' skip sending originatorInfo on pause"):e.state.isOriginator||(f.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected' / keysExchanged=${null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged()} -- backward compatibility`),null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l,force:!0})),e.state.clientsConnected=!0,e.state.clientsPaused=!1}))}},{event:"channel_created",handler:function(e,t){return n=>{f.SocketService(`[SocketService: handleChannelCreated()] context=${e.state.context} on 'channel_created-${t}'`,n),e.emit($.CHANNEL_CREATED,n)}}},{event:"clients_disconnected",handler:function(e,t){return()=>{var n;e.state.clientsConnected=!1,f.SocketService(`[SocketService: handlesClientsDisconnected()] context=${e.state.context} on 'clients_disconnected-${t}'`),e.state.isOriginator&&!e.state.clientsPaused&&(null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.emit($.CLIENTS_DISCONNECTED,t)}}},{event:"message",handler:function(e,t){return({id:n,message:o,error:i})=>{var s,a,c,r,l,d,u,h,m,g,E,v,y,C,p;if(f.SocketService(`[SocketService handleMessage()] context=${e.state.context} on 'message' ${t} keysExchanged=${null===(s=e.state.keyExchange)||void 0===s?void 0:s.areKeysExchanged()}`,o),i)throw f.SocketService(`\n [SocketService handleMessage()] context=${e.state.context}::on 'message' error=${i}`),new Error(i);try{!function(e,t){if(t!==e.channelId)throw e.debug&&console.error(`Wrong id ${t} - should be ${e.channelId}`),new Error("Wrong id")}(e.state,n)}catch(e){return void console.error("ignore message --- wrong id ",o)}if(e.state.isOriginator&&(null==o?void 0:o.type)===M.KEY_HANDSHAKE_START)return f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received HANDSHAKE_START isOriginator=${e.state.isOriginator}`,o),void(null===(a=e.state.keyExchange)||void 0===a||a.start({isOriginator:null!==(c=e.state.isOriginator)&&void 0!==c&&c,force:!0}));if((null==o?void 0:o.type)===P.PING)return f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' ping `),void e.emit($.MESSAGE,{message:{type:"ping"}});if(f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' originator=${e.state.isOriginator}, type=${null==o?void 0:o.type}, keysExchanged=${null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged()}`),null===(l=null==o?void 0:o.type)||void 0===l?void 0:l.startsWith("key_handshake"))return f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' emit KEY_EXCHANGE`,o),void e.emit(L.KEY_EXCHANGE,{message:o,context:e.state.context});if(null===(d=e.state.keyExchange)||void 0===d?void 0:d.areKeysExchanged()){if(-1!==o.toString().indexOf("type"))return console.warn("[SocketService handleMessage() ::on 'message' received non encrypted unkwown message"),void e.emit($.MESSAGE,o)}else{let t=!1;try{null===(u=e.state.keyExchange)||void 0===u||u.decryptMessage(o),t=!0}catch(e){}if(!t)return e.state.isOriginator?null===(m=e.state.keyExchange)||void 0===m||m.start({isOriginator:null!==(g=e.state.isOriginator)&&void 0!==g&&g}):e.sendMessage({type:M.KEY_HANDSHAKE_START}),void console.warn(`Message ignored because invalid key exchange status. step=${null===(E=e.state.keyExchange)||void 0===E?void 0:E.getKeyInfo().step}`,null===(v=e.state.keyExchange)||void 0===v?void 0:v.getKeyInfo(),o);console.warn("Invalid key exchange status detected --- updating it."),null===(h=e.state.keyExchange)||void 0===h||h.setKeysExchanged(!0)}const S=null===(y=e.state.keyExchange)||void 0===y?void 0:y.decryptMessage(o),k=JSON.parse(null!=S?S:"{}");if((null==k?void 0:k.type)===P.PAUSE?e.state.clientsPaused=!0:e.state.clientsPaused=!1,e.state.isOriginator&&k.data){const t=k.data,n=e.state.rpcMethodTracker[t.id];if(n){const o=Date.now()-n.timestamp;f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received answer for id=${t.id} method=${n.method} responseTime=${o}`,k);const i=Object.assign(Object.assign({},n),{result:t.result,error:t.error?{code:null===(C=t.error)||void 0===C?void 0:C.code,message:null===(p=t.error)||void 0===p?void 0:p.message}:void 0,elapsedTime:o});e.state.rpcMethodTracker[t.id]=i,e.emit($.RPC_UPDATE,i),f.SocketService("[SocketService handleMessage()] HACK (wallet <7.3) update rpcMethodTracker",i),e.emit($.AUTHORIZED)}}e.emit($.MESSAGE,{message:k})}}},{event:"clients_waiting_to_join",handler:function(e,t){return n=>{f.SocketService(`[SocketService: handleClientsWaitingToJoin()] context=${e.state.context} on 'clients_waiting_to_join-${t}'`,n),e.emit($.CLIENTS_WAITING,n)}}}],W=[{event:$.KEY_INFO,handler:function(e){return t=>{f.SocketService("[SocketService: handleKeyInfo()] on 'KEY_INFO'",t),e.emit($.KEY_INFO,t)}}},{event:$.KEYS_EXCHANGED,handler:function(e){return()=>{var t,n;f.SocketService(`[SocketService: handleKeysExchanged()] on 'keys_exchanged' keyschanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.emit($.KEYS_EXCHANGED,{keysExchanged:null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged(),isOriginator:e.state.isOriginator});const o={keyInfo:e.getKeyInfo()};e.emit($.SERVICE_STATUS,o)}}}];function V(e,t){f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} setting socket listeners for channel ${t}...`);const{socket:n}=e.state,{keyExchange:o}=e.state;e.state.setupChannelListeners&&console.warn(`[SocketService: setupChannelListener()] context=${e.state.context} socket listeners already set up for channel ${t}`),n&&e.state.isOriginator&&(e.state.debug&&(null==n||n.io.on("error",(t=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=error`,t)})),null==n||n.io.on("reconnect",(t=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect`,t)})),null==n||n.io.on("reconnect_error",(t=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_error`,t)})),null==n||n.io.on("reconnect_failed",(()=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_failed`)})),null==n||n.io.on("ping",(()=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=ping`)}))),null==n||n.on("disconnect",(t=>(f.SocketService(`[SocketService: setupChannelListener()] on 'disconnect' -- MetaMaskSDK socket disconnected '${t}' begin recovery...`),z(e)(t))))),G.forEach((({event:o,handler:i})=>{const s=`${o}-${t}`;null==n||n.on(s,i(e,t))})),W.forEach((({event:t,handler:n})=>{null==o||o.on(t,n(e))})),e.state.setupChannelListeners=!0}var J;!function(e){e.REQUEST="sdk_connect_request_started",e.REQUEST_MOBILE="sdk_connect_request_started_mobile",e.RECONNECT="sdk_reconnect_request_started",e.CONNECTED="sdk_connection_established",e.CONNECTED_MOBILE="sdk_connection_established_mobile",e.AUTHORIZED="sdk_connection_authorized",e.REJECTED="sdk_connection_rejected",e.TERMINATED="sdk_connection_terminated",e.DISCONNECTED="sdk_disconnected",e.SDK_USE_EXTENSION="sdk_use_extension",e.SDK_RPC_REQUEST="sdk_rpc_request",e.SDK_EXTENSION_UTILIZED="sdk_extension_utilized",e.SDK_USE_INAPP_BROWSER="sdk_use_inapp_browser"}(J||(J={}));const Z="SDK_CONNECTION_ISSUE";var B;!function(e){e.RPC_CHECK="rpcCheck",e.SKIPPED_RPC="skippedRpc"}(B||(B={}));const X=["eth_sendTransaction","eth_signTypedData","eth_signTransaction","wallet_requestPermissions","wallet_switchEthereumChain","eth_signTypedData_v3","eth_signTypedData_v4","metamask_connectSign","metamask_connectWith","metamask_batch"].map((e=>e.toLowerCase()));function Q(e,t){var n,o,i,s;if(!e.state.channelId)throw new Error("Create a channel first");f.SocketService(`[SocketService: handleSendMessage()] context=${e.state.context} areKeysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`,t);(null===(o=null==t?void 0:t.type)||void 0===o?void 0:o.startsWith("key_handshake"))?function(e,t){var n;f.SocketService(`[SocketService: handleKeyHandshake()] context=${e.state.context}`,t),null===(n=e.state.socket)||void 0===n||n.emit($.MESSAGE,{id:e.state.channelId,context:e.state.context,message:t})}(e,t):(!function(e,t){var n;if(!(null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()))throw f.SocketService(`[SocketService: validateKeyExchange()] context=${e.state.context} ERROR keys not exchanged`,t),new Error("Keys not exchanged BBB")}(e,t),function(e,t){var n;const o=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"",i=null==t?void 0:t.id;e.state.isOriginator&&i&&(e.state.rpcMethodTracker[i]={id:i,timestamp:Date.now(),method:o},e.emit($.RPC_UPDATE,e.state.rpcMethodTracker[i]))}(e,t),function(e,t){var n,o;const i=null===(n=e.state.keyExchange)||void 0===n?void 0:n.encryptMessage(JSON.stringify(t)),s={id:e.state.channelId,context:e.state.context,message:i,plaintext:e.state.hasPlaintext?JSON.stringify(t):void 0};f.SocketService(`[SocketService: encryptAndSendMessage()] context=${e.state.context}`,s),t.type===P.TERMINATE&&(e.state.manualDisconnect=!0),null===(o=e.state.socket)||void 0===o||o.emit($.MESSAGE,s)}(e,t),e.remote.state.analytics&&t.method&&X.includes(t.method.toLowerCase())&&_({id:null!==(i=e.remote.state.channelId)&&void 0!==i?i:"",event:J.SDK_RPC_REQUEST,sdkVersion:e.remote.state.sdkVersion,commLayerVersion:A.version,walletVersion:null===(s=e.remote.state.walletInfo)||void 0===s?void 0:s.version,params:{method:t.method,from:"mobile"}},e.remote.state.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),function(e,t){var n;return l(this,void 0,void 0,(function*(){const o=null==t?void 0:t.id,i=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"";if(e.state.isOriginator&&o)try{const n=Y(o,e.state.rpcMethodTracker,200).then((e=>({type:B.RPC_CHECK,result:e}))),s=(()=>l(this,void 0,void 0,(function*(){const t=yield U({instance:e,rpcId:o}),n=yield Y(t,e.state.rpcMethodTracker,200);return{type:B.SKIPPED_RPC,result:n}})))(),a=yield Promise.race([n,s]);if(a.type===B.RPC_CHECK){const e=a.result;f.SocketService(`[SocketService:handleRpcReplies()] id=${t.id} ${i} ( ${e.elapsedTime} ms)`,e.result)}else{if(a.type!==B.SKIPPED_RPC)throw new Error(`Error handling RPC replies for ${o}`);{const{result:t}=a;console.warn(`[SocketService handleRpcReplies()] RPC METHOD HAS BEEN SKIPPED rpcid=${o} method=${i}`,t);const n=Object.assign(Object.assign({},e.state.rpcMethodTracker[o]),{error:new Error(Z)});e.emit($.RPC_UPDATE,n);const s={data:Object.assign(Object.assign({},n),{jsonrpc:"2.0"}),name:"metamask-provider"};e.emit($.MESSAGE,{message:s})}}}catch(e){throw console.warn(`[SocketService handleRpcReplies()] Error rpcId=${t.id} ${i}`,e),e}}))}(e,t).catch((e=>{console.warn("Error handleRpcReplies",e)})))}class q extends s{constructor({otherPublicKey:e,reconnect:t,communicationLayerPreference:n,transports:o,communicationServerUrl:i,context:s,ecies:a,remote:c,logging:l}){super(),this.state={clientsConnected:!1,clientsPaused:!1,manualDisconnect:!1,lastRpcId:void 0,rpcMethodTracker:{},hasPlaintext:!1,communicationServerUrl:""},this.state.resumed=t,this.state.context=s,this.state.communicationLayerPreference=n,this.state.debug=!0===(null==l?void 0:l.serviceLayer),this.remote=c,!0===(null==l?void 0:l.serviceLayer)&&v.enable("SocketService:Layer"),this.state.communicationServerUrl=i,this.state.hasPlaintext=this.state.communicationServerUrl!==O&&!0===(null==l?void 0:l.plaintext);const d={autoConnect:!1,transports:T,withCredentials:!0};o&&(d.transports=o),f.SocketService(`[SocketService: constructor()] Socket IO url: ${this.state.communicationServerUrl}`),this.state.socket=r(i,d);const u={communicationLayer:this,otherPublicKey:e,sendPublicKey:!1,context:this.state.context,ecies:a,logging:l};this.state.keyExchange=new H(u)}resetKeys(){return e=this,f.SocketService("[SocketService: resetKeys()] Resetting keys."),void(null===(t=e.state.keyExchange)||void 0===t||t.resetKeys());var e,t}createChannel(){return function(e){var t,n,o,i;f.SocketService(`[SocketService: createChannel()] context=${e.state.context}`),(null===(t=e.state.socket)||void 0===t?void 0:t.connected)||null===(n=e.state.socket)||void 0===n||n.connect(),e.state.manualDisconnect=!1,e.state.isOriginator=!0;const s=c();return e.state.channelId=s,V(e,s),null===(o=e.state.socket)||void 0===o||o.emit($.JOIN_CHANNEL,s,`${e.state.context}createChannel`),{channelId:s,pubKey:(null===(i=e.state.keyExchange)||void 0===i?void 0:i.getMyPublicKey())||""}}(this)}connectToChannel({channelId:e,isOriginator:t=!1,withKeyExchange:n=!1}){return function({options:e,instance:t}){var n,o,i,s;const{channelId:a,withKeyExchange:c,isOriginator:r}=e;if(f.SocketService(`[SocketService: connectToChannel()] context=${t.state.context} channelId=${a} isOriginator=${r}`,null===(n=t.state.keyExchange)||void 0===n?void 0:n.toString()),null===(o=t.state.socket)||void 0===o?void 0:o.connected)throw new Error("socket already connected");t.state.manualDisconnect=!1,null===(i=t.state.socket)||void 0===i||i.connect(),t.state.withKeyExchange=c,t.state.isOriginator=r,t.state.channelId=a,V(t,a),null===(s=t.state.socket)||void 0===s||s.emit($.JOIN_CHANNEL,a,`${t.state.context}_connectToChannel`)}({options:{channelId:e,isOriginator:t,withKeyExchange:n},instance:this})}getKeyInfo(){return this.state.keyExchange.getKeyInfo()}keyCheck(){var e,t;null===(t=(e=this).state.socket)||void 0===t||t.emit($.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:M.KEY_HANDSHAKE_CHECK,pubkey:e.getKeyInfo().ecies.otherPubKey}})}getKeyExchange(){return this.state.keyExchange}sendMessage(e){return Q(this,e)}ping(){return e=this,f.SocketService(`[SocketService: ping()] context=${e.state.context} originator=${e.state.isOriginator} keysExchanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.state.isOriginator&&((null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged())?(console.warn(`[SocketService:ping()] context=${e.state.context} sending READY message`),e.sendMessage({type:P.READY})):(console.warn(`[SocketService: ping()] context=${e.state.context} starting key exchange`),null===(o=e.state.keyExchange)||void 0===o||o.start({isOriginator:null!==(i=e.state.isOriginator)&&void 0!==i&&i}))),void(null===(s=e.state.socket)||void 0===s||s.emit($.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:P.PING}}));var e,t,n,o,i,s}pause(){return e=this,f.SocketService(`[SocketService: pause()] context=${e.state.context}`),e.state.manualDisconnect=!0,(null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged())&&e.sendMessage({type:P.PAUSE}),void(null===(n=e.state.socket)||void 0===n||n.disconnect());var e,t,n}isConnected(){var e;return null===(e=this.state.socket)||void 0===e?void 0:e.connected}resume(){return e=this,f.SocketService(`[SocketService: resume()] context=${e.state.context} connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} manualDisconnect=${e.state.manualDisconnect} resumed=${e.state.resumed} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`),(null===(o=e.state.socket)||void 0===o?void 0:o.connected)?f.SocketService("[SocketService: resume()] already connected."):(null===(i=e.state.socket)||void 0===i||i.connect(),f.SocketService(`[SocketService: resume()] after connecting socket --\x3e connected=${null===(s=e.state.socket)||void 0===s?void 0:s.connected}`),null===(a=e.state.socket)||void 0===a||a.emit($.JOIN_CHANNEL,e.state.channelId,`${e.state.context}_resume`)),(null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged())?e.state.isOriginator||e.sendMessage({type:P.READY}):e.state.isOriginator||null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l}),e.state.manualDisconnect=!1,void(e.state.resumed=!0);var e,t,n,o,i,s,a,c,r,l}getRPCMethodTracker(){return this.state.rpcMethodTracker}disconnect(e){return function(e,t){var n,o;f.SocketService(`[SocketService: disconnect()] context=${e.state.context}`,t),(null==t?void 0:t.terminate)&&(e.state.channelId=t.channelId,null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.state.rpcMethodTracker={},e.state.manualDisconnect=!0,null===(o=e.state.socket)||void 0===o||o.disconnect()}(this,e)}}var ee,te,ne;function oe(e){return()=>l(this,void 0,void 0,(function*(){var t,n,o;const{state:i}=e;if(i.authorized)return;yield(()=>l(this,void 0,void 0,(function*(){for(;!i.walletInfo;)yield F(500)})))();const s="7.3".localeCompare((null===(t=i.walletInfo)||void 0===t?void 0:t.version)||"");if(f.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' version=${null===(n=i.walletInfo)||void 0===n?void 0:n.version} compareValue=${s}`),1!==s)return;const a=i.platformType===te.MobileWeb||i.platformType===te.ReactNative||i.platformType===te.MetaMaskMobileWebview;f.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' platform=${i.platformType} secure=${a} channel=${i.channelId} walletVersion=${null===(o=i.walletInfo)||void 0===o?void 0:o.version}`),a&&(i.authorized=!0,e.emit($.AUTHORIZED))}))}function ie(e){return t=>{const{state:n}=e;f.RemoteCommunication(`[RemoteCommunication: handleChannelCreatedEvent()] context=${n.context} on 'channel_created' channelId=${t}`),e.emit($.CHANNEL_CREATED,t)}}function se(e,t){return()=>{var n,o,i,s;const{state:a}=e;if(f.RemoteCommunication(`[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=${a.channelId} keysExchanged=${null===(o=null===(n=a.communicationLayer)||void 0===n?void 0:n.getKeyInfo())||void 0===o?void 0:o.keysExchanged}`),a.analytics){const e=a.isOriginator?J.REQUEST:J.REQUEST_MOBILE;_(Object.assign(Object.assign({id:null!==(i=a.channelId)&&void 0!==i?i:"",event:a.reconnection?J.RECONNECT:e},a.originatorInfo),{commLayer:t,sdkVersion:a.sdkVersion,walletVersion:null===(s=a.walletInfo)||void 0===s?void 0:s.version,commLayerVersion:A.version}),a.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}a.clientsConnected=!0,a.originatorInfoSent=!1,e.emit($.CLIENTS_CONNECTED)}}function ae(e,t){return n=>{var o;const{state:i}=e;f.RemoteCommunication(`[RemoteCommunication: handleClientsDisconnectedEvent()] context=${i.context} on 'clients_disconnected' channelId=${n}`),i.clientsConnected=!1,e.emit($.CLIENTS_DISCONNECTED,i.channelId),e.setConnectionStatus(D.DISCONNECTED),i.ready=!1,i.authorized=!1,i.analytics&&i.channelId&&_({id:i.channelId,event:J.DISCONNECTED,sdkVersion:i.sdkVersion,commLayer:t,commLayerVersion:A.version,walletVersion:null===(o=i.walletInfo)||void 0===o?void 0:o.version},i.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}}function ce(e){return t=>{var n;const{state:o}=e;if(f.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] context=${o.context} on 'clients_waiting' numberUsers=${t} ready=${o.ready} autoStarted=${o.originatorConnectStarted}`),e.setConnectionStatus(D.WAITING),e.emit($.CLIENTS_WAITING,t),o.originatorConnectStarted){f.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] on 'clients_waiting' watch autoStarted=${o.originatorConnectStarted} timeout`,o.autoConnectOptions);const t=(null===(n=o.autoConnectOptions)||void 0===n?void 0:n.timeout)||3e3,i=setTimeout((()=>{f.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] setTimeout(${t}) terminate channelConfig`,o.autoConnectOptions),o.originatorConnectStarted=!1,o.ready||e.setConnectionStatus(D.TIMEOUT),clearTimeout(i)}),t)}}}function re(e,t){return n=>{var o,i,s,a,c;const{state:r}=e;f.RemoteCommunication(`[RemoteCommunication: handleKeysExchangedEvent()] context=${r.context} on commLayer.'keys_exchanged' channel=${r.channelId}`,n),(null===(i=null===(o=r.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.keysExchanged)&&e.setConnectionStatus(D.LINKED),function(e,t){var n,o,i,s;const{state:a}=e;f.RemoteCommunication(`[RemoteCommunication: setLastActiveDate()] channel=${a.channelId}`,t);const c={channelId:null!==(n=a.channelId)&&void 0!==n?n:"",validUntil:null!==(i=null===(o=a.channelConfig)||void 0===o?void 0:o.validUntil)&&void 0!==i?i:0,lastActive:t.getTime()};null===(s=a.storageManager)||void 0===s||s.persistChannelConfig(c)}(e,new Date),r.analytics&&r.channelId&&_({id:r.channelId,event:n.isOriginator?J.CONNECTED:J.CONNECTED_MOBILE,sdkVersion:r.sdkVersion,commLayer:t,commLayerVersion:A.version,walletVersion:null===(s=r.walletInfo)||void 0===s?void 0:s.version},r.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),r.isOriginator=n.isOriginator,n.isOriginator||(null===(a=r.communicationLayer)||void 0===a||a.sendMessage({type:P.READY}),r.ready=!0,r.paused=!1),n.isOriginator&&!r.originatorInfoSent&&(null===(c=r.communicationLayer)||void 0===c||c.sendMessage({type:P.ORIGINATOR_INFO,originatorInfo:r.originatorInfo,originator:r.originatorInfo}),r.originatorInfoSent=!0)}}function le(e,t){const{state:n}=t;if(f.RemoteCommunication(`[RemoteCommunication: onCommunicationLayerMessage()] context=${n.context} on 'message' typeof=${typeof e}`,e),t.state.ready=!0,n.isOriginator||e.type!==P.ORIGINATOR_INFO)if(n.isOriginator&&e.type===P.WALLET_INFO)!function(e,t){const{state:n}=e;n.walletInfo=t.walletInfo,n.paused=!1}(t,e);else{if(e.type===P.TERMINATE)!function(e){const{state:t}=e;t.isOriginator&&(ge({options:{terminate:!0,sendMessage:!1},instance:e}),console.debug(),e.emit($.TERMINATE))}(t);else if(e.type===P.PAUSE)!function(e){const{state:t}=e;t.paused=!0,e.setConnectionStatus(D.PAUSED)}(t);else if(e.type===P.READY&&n.isOriginator)!function(e){const{state:t}=e;e.setConnectionStatus(D.LINKED);const n=t.paused;t.paused=!1,e.emit($.CLIENTS_READY,{isOriginator:t.isOriginator,walletInfo:t.walletInfo}),n&&(t.authorized=!0,e.emit($.AUTHORIZED))}(t);else{if(e.type===P.OTP&&n.isOriginator)return void function(e,t){var n;const{state:o}=e;e.emit($.OTP,t.otpAnswer),1==="6.6".localeCompare((null===(n=o.walletInfo)||void 0===n?void 0:n.version)||"")&&(console.warn("RemoteCommunication::on 'otp' -- backward compatibility <6.6 -- triger eth_requestAccounts"),e.emit($.SDK_RPC_CALL,{method:b.ETH_REQUESTACCOUNTS,params:[]}))}(t,e);e.type===P.AUTHORIZED&&n.isOriginator&&function(e){const{state:t}=e;t.authorized=!0,e.emit($.AUTHORIZED)}(t)}t.emit($.MESSAGE,e)}else!function(e,t){var n;const{state:o}=e;null===(n=o.communicationLayer)||void 0===n||n.sendMessage({type:P.WALLET_INFO,walletInfo:o.walletInfo}),o.originatorInfo=t.originatorInfo||t.originator,e.emit($.CLIENTS_READY,{isOriginator:o.isOriginator,originatorInfo:o.originatorInfo}),o.paused=!1}(t,e)}function de(e,t){var n,o;return l(this,void 0,void 0,(function*(){const{state:i}=e;f.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} paused=${i.paused} ready=${i.ready} authorized=${i.authorized} socket=${null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected()} clientsConnected=${i.clientsConnected} status=${i._connectionStatus}`,t),!i.paused&&i.ready&&(null===(o=i.communicationLayer)||void 0===o?void 0:o.isConnected())&&i.clientsConnected||(f.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} SKIP message waiting for MM mobile readiness.`),yield new Promise((t=>{e.once($.CLIENTS_READY,t)})),f.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} AFTER SKIP / READY -- sending pending message`));try{yield function(e,t){return l(this,void 0,void 0,(function*(){return new Promise((n=>{var o,i,s,a;const{state:c}=e;if(f.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} ready=${c.ready} authorized=${c.authorized} method=${t.method}`),1==="7.3".localeCompare((null===(o=c.walletInfo)||void 0===o?void 0:o.version)||""))return f.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] compatibility hack wallet version > ${null===(i=c.walletInfo)||void 0===i?void 0:i.version}`),null===(s=c.communicationLayer)||void 0===s||s.sendMessage(t),void n();!c.isOriginator||c.authorized?(null===(a=c.communicationLayer)||void 0===a||a.sendMessage(t),n()):e.once($.AUTHORIZED,(()=>{var e;f.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} AFTER SKIP / AUTHORIZED -- sending pending message`),null===(e=c.communicationLayer)||void 0===e||e.sendMessage(t),n()}))}))}))}(e,t)}catch(e){throw console.error(`[RemoteCommunication: sendMessage()] context=${i.context} ERROR`,e),e}}))}function ue(e){return t=>{let n=t;t.message&&(n=n.message),le(n,e)}}function he(e){return()=>{const{state:t}=e;f.RemoteCommunication("[RemoteCommunication: handleSocketReconnectEvent()] on 'socket_reconnect' -- reset key exchange status / set ready to false"),t.ready=!1,t.authorized=!1,w(t),e.emitServiceStatusEvent()}}function me(e){return()=>{const{state:t}=e;f.RemoteCommunication("[RemoteCommunication: handleSocketDisconnectedEvent()] on 'socket_Disconnected' set ready to false"),t.ready=!1}}function ge({options:e,instance:t}){var n,o,i,s,a,r;const{state:l}=t;f.RemoteCommunication(`[RemoteCommunication: disconnect()] channel=${l.channelId}`,e),l.ready=!1,l.paused=!1,(null==e?void 0:e.terminate)?(null===(n=l.storageManager)||void 0===n||n.terminate(null!==(o=l.channelId)&&void 0!==o?o:""),(null===(i=l.communicationLayer)||void 0===i?void 0:i.getKeyInfo().keysExchanged)&&(null==e?void 0:e.sendMessage)&&(null===(s=l.communicationLayer)||void 0===s||s.sendMessage({type:P.TERMINATE})),l.channelId=c(),e.channelId=l.channelId,l.channelConfig=void 0,l.originatorConnectStarted=!1,null===(a=l.communicationLayer)||void 0===a||a.disconnect(e),t.setConnectionStatus(D.TERMINATED)):(null===(r=l.communicationLayer)||void 0===r||r.disconnect(e),t.setConnectionStatus(D.DISCONNECTED))}!function(e){e.SOCKET="socket"}(ee||(ee={})),function(e){e.NonBrowser="nodejs",e.MetaMaskMobileWebview="in-app-browser",e.DesktopWeb="web-desktop",e.MobileWeb="web-mobile",e.ReactNative="react-native"}(te||(te={}));class Ee extends s{constructor({platformType:e,communicationLayerPreference:t,otherPublicKey:n,reconnect:o,walletInfo:i,dappMetadata:s,transports:a,context:c,ecies:r,analytics:l=!1,storage:d,sdkVersion:u,communicationServerUrl:h=O,logging:m,autoConnect:g={timeout:3e3}}){super(),this.state={ready:!1,authorized:!1,isOriginator:!1,paused:!1,platformType:"metamask-mobile",analytics:!1,reconnection:!1,originatorInfoSent:!1,communicationServerUrl:O,context:"",clientsConnected:!1,sessionDuration:R,originatorConnectStarted:!1,debug:!1,_connectionStatus:D.DISCONNECTED},this.state.otherPublicKey=n,this.state.dappMetadata=s,this.state.walletInfo=i,this.state.transports=a,this.state.platformType=e,this.state.analytics=l,this.state.isOriginator=!n,this.state.communicationServerUrl=h,this.state.context=c,this.state.sdkVersion=u,this.setMaxListeners(50),this.setConnectionStatus(D.DISCONNECTED),(null==d?void 0:d.duration)&&(this.state.sessionDuration=R),this.state.storageOptions=d,this.state.autoConnectOptions=g,this.state.debug=!0===(null==m?void 0:m.remoteLayer),!0===(null==m?void 0:m.remoteLayer)&&v.enable("RemoteCommunication:Layer"),this.state.logging=m,(null==d?void 0:d.storageManager)&&(this.state.storageManager=d.storageManager),this.initCommunicationLayer({communicationLayerPreference:t,otherPublicKey:n,reconnect:o,ecies:r,communicationServerUrl:h}),this.emitServiceStatusEvent()}initCommunicationLayer({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=O}){return function({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=O,instance:s}){var a,c,r,l,d;const{state:u}=s;if(e!==ee.SOCKET)throw new Error("Invalid communication protocol");u.communicationLayer=new q({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,transports:u.transports,communicationServerUrl:i,context:u.context,ecies:o,logging:u.logging,remote:s});let h="undefined"!=typeof document&&document.URL||"",m="undefined"!=typeof document&&document.title||"";(null===(a=u.dappMetadata)||void 0===a?void 0:a.url)&&(h=u.dappMetadata.url),(null===(c=u.dappMetadata)||void 0===c?void 0:c.name)&&(m=u.dappMetadata.name);const g={url:h,title:m,source:null===(r=u.dappMetadata)||void 0===r?void 0:r.source,icon:(null===(l=u.dappMetadata)||void 0===l?void 0:l.iconUrl)||(null===(d=u.dappMetadata)||void 0===d?void 0:d.base64Icon),platform:u.platformType,apiVersion:A.version};u.originatorInfo=g;const E={[$.AUTHORIZED]:oe(s),[$.MESSAGE]:ue(s),[$.CLIENTS_CONNECTED]:se(s,e),[$.KEYS_EXCHANGED]:re(s,e),[$.SOCKET_DISCONNECTED]:me(s),[$.SOCKET_RECONNECT]:he(s),[$.CLIENTS_DISCONNECTED]:ae(s,e),[$.KEY_INFO]:()=>{s.emitServiceStatusEvent()},[$.CHANNEL_CREATED]:ie(s),[$.CLIENTS_WAITING]:ce(s),[$.RPC_UPDATE]:e=>{s.emit($.RPC_UPDATE,e)}};for(const[e,t]of Object.entries(E))try{u.communicationLayer.on(e,t)}catch(t){console.error(`Error registering handler for ${e}:`,t)}}({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i,instance:this})}originatorSessionConnect(){return l(this,void 0,void 0,(function*(){return yield function(e){var t,n,o;return l(this,void 0,void 0,(function*(){const{state:i}=e;if(!i.storageManager)return void f.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] no storage manager defined - skip");const s=yield i.storageManager.getPersistedChannelConfig(null!==(t=i.channelId)&&void 0!==t?t:"");if(f.RemoteCommunication(`[RemoteCommunication: originatorSessionConnect()] autoStarted=${i.originatorConnectStarted} channelConfig`,s),null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected())return f.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] socket already connected - skip"),s;if(s){if(s.validUntil>Date.now())return i.channelConfig=s,i.originatorConnectStarted=!0,i.channelId=null==s?void 0:s.channelId,i.reconnection=!0,null===(o=i.communicationLayer)||void 0===o||o.connectToChannel({channelId:s.channelId,isOriginator:!0}),s;f.RemoteCommunication("[RemoteCommunication: autoConnect()] Session has expired")}i.originatorConnectStarted=!1}))}(this)}))}generateChannelIdConnect(){return l(this,void 0,void 0,(function*(){return function(e){var t,n,o,i,s;if(!e.communicationLayer)throw new Error("communication layer not initialized");if(e.ready)throw new Error("Channel already connected");if(e.channelId&&(null===(t=e.communicationLayer)||void 0===t?void 0:t.isConnected()))return console.warn("Channel already exists -- interrupt generateChannelId",e.channelConfig),e.channelConfig={channelId:e.channelId,validUntil:Date.now()+e.sessionDuration},null===(n=e.storageManager)||void 0===n||n.persistChannelConfig(e.channelConfig),{channelId:e.channelId,pubKey:null===(i=null===(o=e.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.ecies.public};f.RemoteCommunication("[RemoteCommunication: generateChannelId()]"),w(e);const a=e.communicationLayer.createChannel();f.RemoteCommunication("[RemoteCommunication: generateChannelId()] channel created",a);const c={channelId:a.channelId,validUntil:Date.now()+e.sessionDuration};return e.channelId=a.channelId,e.channelConfig=c,null===(s=e.storageManager)||void 0===s||s.persistChannelConfig(c),{channelId:e.channelId,pubKey:a.pubKey}}(this.state)}))}clean(){return w(this.state)}connectToChannel(e,t){return function({channelId:e,withKeyExchange:t,state:n}){var o,i,s;if(!a(e))throw f.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} invalid channel channelId=${e}`),new Error(`Invalid channel ${e}`);if(f.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} channelId=${e}`),null===(o=n.communicationLayer)||void 0===o?void 0:o.isConnected())return void f.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} already connected - interrupt connection.`);n.channelId=e,null===(i=n.communicationLayer)||void 0===i||i.connectToChannel({channelId:e,withKeyExchange:t});const c={channelId:e,validUntil:Date.now()+n.sessionDuration};n.channelConfig=c,null===(s=n.storageManager)||void 0===s||s.persistChannelConfig(c)}({channelId:e,withKeyExchange:t,state:this.state})}sendMessage(e){return de(this,e)}testStorage(){return l(this,void 0,void 0,(function*(){return function(e){var t,n;return l(this,void 0,void 0,(function*(){const o=yield null===(t=e.storageManager)||void 0===t?void 0:t.getPersistedChannelConfig(null!==(n=e.channelId)&&void 0!==n?n:"");f.RemoteCommunication("[RemoteCommunication: testStorage()] res",o)}))}(this.state)}))}getChannelConfig(){return this.state.channelConfig}isReady(){return this.state.ready}isConnected(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.isConnected()}isAuthorized(){return this.state.authorized}isPaused(){return this.state.paused}getCommunicationLayer(){return this.state.communicationLayer}ping(){var e;f.RemoteCommunication(`[RemoteCommunication: ping()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.ping()}keyCheck(){var e;f.RemoteCommunication(`[RemoteCommunication: keyCheck()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.keyCheck()}setConnectionStatus(e){this.state._connectionStatus!==e&&(this.state._connectionStatus=e,this.emit($.CONNECTION_STATUS,e),this.emitServiceStatusEvent())}emitServiceStatusEvent(){this.emit($.SERVICE_STATUS,this.getServiceStatus())}getConnectionStatus(){return this.state._connectionStatus}getServiceStatus(){return{originatorInfo:this.state.originatorInfo,keyInfo:this.getKeyInfo(),connectionStatus:this.state._connectionStatus,channelConfig:this.state.channelConfig,channelId:this.state.channelId}}getKeyInfo(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getKeyInfo()}resetKeys(){var e;null===(e=this.state.communicationLayer)||void 0===e||e.resetKeys()}setOtherPublicKey(e){var t;const n=null===(t=this.state.communicationLayer)||void 0===t?void 0:t.getKeyExchange();if(!n)throw new Error("KeyExchange is not initialized.");n.getOtherPublicKey()!==e&&n.setOtherPublicKey(e)}pause(){var e;f.RemoteCommunication(`[RemoteCommunication: pause()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.pause(),this.setConnectionStatus(D.PAUSED)}getVersion(){return A.version}resume(){return function(e){var t;const{state:n}=e;f.RemoteCommunication(`[RemoteCommunication: resume()] channel=${n.channelId}`),null===(t=n.communicationLayer)||void 0===t||t.resume(),e.setConnectionStatus(D.LINKED)}(this)}getChannelId(){return this.state.channelId}getRPCMethodTracker(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getRPCMethodTracker()}disconnect(e){return ge({options:e,instance:this})}}!function(e){e.RENEW="renew",e.LINK="link"}(ne||(ne={}));export{ne as AutoConnectType,ee as CommunicationLayerPreference,D as ConnectionStatus,O as DEFAULT_SERVER_URL,N as ECIES,$ as EventType,M as KeyExchangeMessageType,P as MessageType,te as PlatformType,Ee as RemoteCommunication,_ as SendAnalytics,q as SocketService,J as TrackingEvents};
import e from"cross-fetch";import{Buffer as t}from"buffer";import{PrivateKey as n,encrypt as o,decrypt as i}from"eciesjs";import{EventEmitter2 as s}from"eventemitter2";import{validate as a,v4 as c}from"uuid";import{io as r}from"socket.io-client";function l(e,t,n,o){return new(n||(n=Promise))((function(i,s){function a(e){try{r(o.next(e))}catch(e){s(e)}}function c(e){try{r(o.throw(e))}catch(e){s(e)}}function r(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,c)}r((o=o.apply(e,t||[])).next())}))}function d(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var u,h,m={exports:{}};function g(){if(h)return u;h=1;var e=1e3,t=60*e,n=60*t,o=24*n,i=7*o,s=365.25*o;function a(e,t,n,o){var i=t>=1.5*n;return Math.round(e/n)+" "+o+(i?"s":"")}return u=function(c,r){r=r||{};var l=typeof c;if("string"===l&&c.length>0)return function(a){if((a=String(a)).length>100)return;var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!c)return;var r=parseFloat(c[1]);switch((c[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*s;case"weeks":case"week":case"w":return r*i;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*n;case"minutes":case"minute":case"mins":case"min":case"m":return r*t;case"seconds":case"second":case"secs":case"sec":case"s":return r*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(c);if("number"===l&&isFinite(c))return r.long?function(i){var s=Math.abs(i);if(s>=o)return a(i,s,o,"day");if(s>=n)return a(i,s,n,"hour");if(s>=t)return a(i,s,t,"minute");if(s>=e)return a(i,s,e,"second");return i+" ms"}(c):function(i){var s=Math.abs(i);if(s>=o)return Math.round(i/o)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))}}var E=function(e){function t(e){let o,i,s,a=null;function c(...e){if(!c.enabled)return;const n=c,i=Number(new Date),s=i-(o||i);n.diff=s,n.prev=o,n.curr=i,o=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((o,i)=>{if("%%"===o)return"%";a++;const s=t.formatters[i];if("function"==typeof s){const t=e[a];o=s.call(n,t),e.splice(a,1),a--}return o})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return c.namespace=e,c.useColors=t.useColors(),c.color=t.selectColor(e),c.extend=n,c.destroy=t.destroy,Object.defineProperty(c,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{a=e}}),"function"==typeof t.init&&t.init(c),c}function n(e,n){const o=t(this.namespace+(void 0===n?":":n)+e);return o.log=this.log,o}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const o=("string"==typeof e?e:"").split(/[\s,]+/),i=o.length;for(n=0;n<i;n++)o[n]&&("-"===(e=o[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,o;for(n=0,o=t.skips.length;n<o;n++)if(t.skips[n].test(e))return!1;for(n=0,o=t.names.length;n<o;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=g(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(o++,"%c"===e&&(i=o))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=E(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(m,m.exports);var v=d(m.exports);const y=v("KeyExchange:Layer"),C=v("SocketService:Layer"),p=v("Ecies:Layer"),S=v("RemoteCommunication:Layer");y.color="##95c44e",C.color="#f638d7",p.color="#465b9c",S.color="#47a2be";const f={KeyExchange:y,SocketService:C,Ecies:p,RemoteCommunication:S};let k,x=[],I=[];function K(t){return l(this,void 0,void 0,(function*(){if(!k||!t)return;!function(){const e=I;I=x,x=e}();const n=k.endsWith("/")?`${k}debug`:`${k}/debug`,o=Object.assign({},t);if(delete o.params,t.params)for(const[e,n]of Object.entries(t.params))o[e]=n;const i=JSON.stringify(o);f.RemoteCommunication(`[sendBufferedEvents] Sending ${x.length} analytics events to ${n}`);try{const t=yield e(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:i}),o=yield t.text();f.RemoteCommunication(`[sendBufferedEvents] Response: ${o}`),x.length=0}catch(e){console.warn("Error sending analytics",e)}}))}const _=(e,t)=>l(void 0,void 0,void 0,(function*(){var n;k=t,n=e,I.push(n),K(e).catch((()=>{}))}));class N{constructor(e){this.enabled=!0,(null==e?void 0:e.debug)&&v.enable("Ecies:Layer"),(null==e?void 0:e.pkey)?this.ecies=n.fromHex(e.pkey):this.ecies=new n,f.Ecies("[ECIES constructor()] initialized secret: ",this.ecies.toHex()),f.Ecies("[ECIES constructor()] initialized public: ",this.ecies.publicKey.toHex()),f.Ecies("[ECIES constructor()] init with",this)}generateECIES(){this.ecies=new n}getPublicKey(){return this.ecies.publicKey.toHex()}encrypt(e,n){let i=e;if(this.enabled)try{f.Ecies("[ECIES: encrypt()] using otherPublicKey",n);const s=t.from(e),a=o(n,s);i=t.from(a).toString("base64")}catch(t){throw f.Ecies("[ECIES: encrypt()] error encrypt:",t),f.Ecies("[ECIES: encrypt()] private: ",this.ecies.toHex()),f.Ecies("[ECIES: encrypt()] data: ",e),f.Ecies("[ECIES: encrypt()] otherkey: ",n),t}return i}decrypt(e){let n=e;if(this.enabled)try{f.Ecies("[ECIES: decrypt()] using privateKey",this.ecies.toHex());const o=t.from(e.toString(),"base64");n=i(this.ecies.toHex(),o).toString()}catch(t){throw f.Ecies("[ECIES: decrypt()] error decrypt",t),f.Ecies("[ECIES: decrypt()] private: ",this.ecies.toHex()),f.Ecies("[ECIES: decrypt()] encryptedData: ",e),t}return n}getKeyInfo(){return{private:this.ecies.toHex(),public:this.ecies.publicKey.toHex()}}toString(){f.Ecies("[ECIES: toString()]",this.getKeyInfo())}}var A={name:"@metamask/sdk-communication-layer",version:"0.18.0",description:"",homepage:"https://github.com/MetaMask/metamask-sdk#readme",bugs:{url:"https://github.com/MetaMask/metamask-sdk/issues"},repository:{type:"git",url:"https://github.com/MetaMask/metamask-sdk.git",directory:"packages/sdk-communication-layer"},main:"dist/node/cjs/metamask-sdk-communication-layer.js",unpkg:"dist/browser/umd/metamask-sdk-communication-layer.js",module:"dist/node/es/metamask-sdk-communication-layer.js",browser:"dist/browser/es/metamask-sdk-communication-layer.js","react-native":"dist/react-native/es/metamask-sdk-communication-layer.js",types:"dist/browser/es/src/index.d.ts",files:["/dist"],scripts:{build:"rimraf dist && rollup -c --bundleConfigAsCjs","build:tsc":"tsc","build:dev":"rimraf dist && NODE_ENV=dev rollup -c --bundleConfigAsCjs","build:post-tsc":"echo 'N/A'","build:pre-tsc":"echo 'N/A'",size:"size-limit",clean:"rimraf ./dist",lint:"yarn lint:eslint && yarn lint:misc --check","lint:changelog":"../../scripts/validate-changelog.sh @metamask/sdk-communication-layer","lint:eslint":"eslint . --cache --ext js,ts","lint:fix":"yarn lint:eslint --fix && yarn lint:misc --write","lint:misc":"prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path ../../.gitignore","prepare-manifest:preview":"../../scripts/prepare-preview-manifest.sh","publish:preview":"yarn npm publish --tag preview",prepack:"../../scripts/prepack.sh",reset:"yarn clean && rimraf ./node_modules/",test:"jest","test:coverage":"jest --coverage","test:ci":"jest --coverage --passWithNoTests --setupFilesAfterEnv ./jest-preload.js","test:dev":"jest",watch:"rollup -c --bundleConfigAsCjs -w"},dependencies:{bufferutil:"^4.0.8","date-fns":"^2.29.3",debug:"^4.3.4","utf-8-validate":"^6.0.3",uuid:"^8.3.2"},devDependencies:{"@jest/globals":"^29.3.1","@lavamoat/allow-scripts":"^2.3.1","@metamask/auto-changelog":"3.1.0","@metamask/eslint-config":"^6.0.0","@metamask/eslint-config-nodejs":"^6.0.0","@metamask/eslint-config-typescript":"^6.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.0.2","@rollup/plugin-terser":"^0.4.1","@size-limit/preset-big-lib":"^11.0.2","@types/jest":"^29.2.4","@types/node":"^20.1.3","@types/uuid":"^9.0.0","@typescript-eslint/eslint-plugin":"^4.26.0","@typescript-eslint/parser":"^4.26.0","cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eslint:"^7.30.0","eslint-config-prettier":"^8.3.0","eslint-plugin-import":"^2.23.4","eslint-plugin-jest":"^24.4.0","eslint-plugin-jsdoc":"^36.1.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.4.0",eventemitter2:"^6.4.7",jest:"^29.3.1",prettier:"^2.3.0",rimraf:"^3.0.2",rollup:"^3.21.7","rollup-plugin-jscc":"^2.0.0","rollup-plugin-natives":"^0.7.5","rollup-plugin-node-builtins":"^2.1.2","rollup-plugin-node-globals":"^1.4.0","rollup-plugin-peer-deps-external":"^2.2.4","rollup-plugin-sizes":"^1.0.6","rollup-plugin-typescript2":"^0.31.2","rollup-plugin-visualizer":"^5.9.2","size-limit":"^11.0.2","socket.io-client":"^4.5.1","stream-browserify":"^3.0.0","ts-jest":"^29.0.3","ts-node":"^10.9.1",typescript:"^4.3.2"},peerDependencies:{"cross-fetch":"^3.1.5",eciesjs:"^0.3.16",eventemitter2:"^6.4.7","readable-stream":"^3.6.2","socket.io-client":"^4.5.1"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},lavamoat:{allowScripts:{"@lavamoat/preinstall-always-fail":!1,canvas:!0,"eciesjs>secp256k1":!1,"socket.io-client>engine.io-client>ws>bufferutil":!1,"socket.io-client>engine.io-client>ws>utf-8-validate":!1,bufferutil:!1,"utf-8-validate":!1}}};const O="https://metamask-sdk.api.cx.metamask.io/",T=["websocket"],R=6048e5,b={METAMASK_GETPROVIDERSTATE:"metamask_getProviderState",ETH_REQUESTACCOUNTS:"eth_requestAccounts"};function w(e){const{context:t}=e;f.RemoteCommunication(`[RemoteCommunication: clean()] context=${t}`),e.channelConfig=void 0,e.ready=!1,e.originatorConnectStarted=!1}var D,$,L,M,P;!function(e){e.DISCONNECTED="disconnected",e.WAITING="waiting",e.TIMEOUT="timeout",e.LINKED="linked",e.PAUSED="paused",e.TERMINATED="terminated"}(D||(D={})),function(e){e.KEY_INFO="key_info",e.SERVICE_STATUS="service_status",e.PROVIDER_UPDATE="provider_update",e.RPC_UPDATE="rpc_update",e.KEYS_EXCHANGED="keys_exchanged",e.JOIN_CHANNEL="join_channel",e.CHANNEL_CREATED="channel_created",e.CLIENTS_CONNECTED="clients_connected",e.CLIENTS_DISCONNECTED="clients_disconnected",e.CLIENTS_WAITING="clients_waiting",e.CLIENTS_READY="clients_ready",e.SOCKET_DISCONNECTED="socket_disconnected",e.SOCKET_RECONNECT="socket_reconnect",e.OTP="otp",e.SDK_RPC_CALL="sdk_rpc_call",e.AUTHORIZED="authorized",e.CONNECTION_STATUS="connection_status",e.MESSAGE="message",e.TERMINATE="terminate"}($||($={})),function(e){e.KEY_EXCHANGE="key_exchange"}(L||(L={})),function(e){e.KEY_HANDSHAKE_START="key_handshake_start",e.KEY_HANDSHAKE_CHECK="key_handshake_check",e.KEY_HANDSHAKE_SYN="key_handshake_SYN",e.KEY_HANDSHAKE_SYNACK="key_handshake_SYNACK",e.KEY_HANDSHAKE_ACK="key_handshake_ACK",e.KEY_HANDSHAKE_NONE="none"}(M||(M={}));class H extends s{constructor({communicationLayer:e,otherPublicKey:t,context:n,ecies:o,logging:i}){super(),this.keysExchanged=!1,this.step=M.KEY_HANDSHAKE_NONE,this.debug=!1,this.context=n,this.myECIES=new N(Object.assign(Object.assign({},o),{debug:null==i?void 0:i.eciesLayer})),this.communicationLayer=e,this.myPublicKey=this.myECIES.getPublicKey(),this.debug=!0===(null==i?void 0:i.keyExchangeLayer),(null==i?void 0:i.keyExchangeLayer)&&v.enable("KeyExchange:Layer"),t&&this.setOtherPublicKey(t),this.communicationLayer.on(L.KEY_EXCHANGE,this.onKeyExchangeMessage.bind(this))}onKeyExchangeMessage(e){f.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} keysExchanged=${this.keysExchanged}`,e);const{message:t}=e;this.keysExchanged&&f.KeyExchange(`[KeyExchange: onKeyExchangeMessage()] context=${this.context} received handshake while already exchanged. step=${this.step} otherPubKey=${this.otherPublicKey}`),this.emit($.KEY_INFO,t.type),t.type===M.KEY_HANDSHAKE_SYN?(this.checkStep([M.KEY_HANDSHAKE_NONE,M.KEY_HANDSHAKE_ACK]),f.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYN",t),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_SYNACK,pubkey:this.myPublicKey}),this.setStep(M.KEY_HANDSHAKE_ACK)):t.type===M.KEY_HANDSHAKE_SYNACK?(this.checkStep([M.KEY_HANDSHAKE_SYNACK,M.KEY_HANDSHAKE_ACK,M.KEY_HANDSHAKE_NONE]),f.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_SYNACK"),t.pubkey&&this.setOtherPublicKey(t.pubkey),this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_ACK}),this.keysExchanged=!0,this.setStep(M.KEY_HANDSHAKE_ACK),this.emit($.KEYS_EXCHANGED)):t.type===M.KEY_HANDSHAKE_ACK&&(f.KeyExchange("[KeyExchange: onKeyExchangeMessage()] KEY_HANDSHAKE_ACK set keysExchanged to true!"),this.checkStep([M.KEY_HANDSHAKE_ACK,M.KEY_HANDSHAKE_NONE]),this.keysExchanged=!0,this.setStep(M.KEY_HANDSHAKE_ACK),this.emit($.KEYS_EXCHANGED))}resetKeys(e){this.clean(),this.myECIES=new N(e)}clean(){f.KeyExchange(`[KeyExchange: clean()] context=${this.context} reset handshake state`),this.setStep(M.KEY_HANDSHAKE_NONE),this.emit($.KEY_INFO,this.step),this.keysExchanged=!1}start({isOriginator:e,force:t}){f.KeyExchange(`[KeyExchange: start()] context=${this.context} isOriginator=${e} step=${this.step} force=${t} keysExchanged=${this.keysExchanged}`),e?!(this.keysExchanged||this.step!==M.KEY_HANDSHAKE_NONE&&this.step!==M.KEY_HANDSHAKE_SYNACK)||t?(f.KeyExchange(`[KeyExchange: start()] context=${this.context} -- start key exchange (force=${t}) -- step=${this.step}`,this.step),this.clean(),this.setStep(M.KEY_HANDSHAKE_SYNACK),this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_SYN,pubkey:this.myPublicKey})):f.KeyExchange(`[KeyExchange: start()] context=${this.context} -- key exchange already ${this.keysExchanged?"done":"in progress"} -- aborted.`,this.step):this.keysExchanged&&!0!==t?f.KeyExchange("[KeyExchange: start()] don't send KEY_HANDSHAKE_START -- exchange already done."):(this.communicationLayer.sendMessage({type:M.KEY_HANDSHAKE_START}),this.clean())}setStep(e){this.step=e,this.emit($.KEY_INFO,e)}checkStep(e){e.length>0&&-1===e.indexOf(this.step.toString())&&console.warn(`[KeyExchange: checkStep()] Wrong Step "${this.step}" not within ${e}`)}setKeysExchanged(e){this.keysExchanged=e}areKeysExchanged(){return this.keysExchanged}getMyPublicKey(){return this.myPublicKey}getOtherPublicKey(){return this.otherPublicKey}setOtherPublicKey(e){f.KeyExchange("[KeyExchange: setOtherPubKey()]",e),this.otherPublicKey=e}encryptMessage(e){if(!this.otherPublicKey)throw new Error("encryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.encrypt(e,this.otherPublicKey)}decryptMessage(e){if(!this.otherPublicKey)throw new Error("decryptMessage: Keys not exchanged - missing otherPubKey");return this.myECIES.decrypt(e)}getKeyInfo(){return{ecies:Object.assign(Object.assign({},this.myECIES.getKeyInfo()),{otherPubKey:this.otherPublicKey}),step:this.step,keysExchanged:this.areKeysExchanged()}}toString(){const e={keyInfo:this.getKeyInfo(),keysExchanged:this.keysExchanged,step:this.step};return JSON.stringify(e)}}!function(e){e.TERMINATE="terminate",e.ANSWER="answer",e.OFFER="offer",e.CANDIDATE="candidate",e.JSONRPC="jsonrpc",e.WALLET_INFO="wallet_info",e.ORIGINATOR_INFO="originator_info",e.PAUSE="pause",e.OTP="otp",e.AUTHORIZED="authorized",e.PING="ping",e.READY="ready"}(P||(P={}));const F=e=>new Promise((t=>{setTimeout(t,e)})),Y=(e,t,n=200)=>l(void 0,void 0,void 0,(function*(){let o;const i=Date.now();let s=!1;for(;!s;){if(s=Date.now()-i>3e5,o=t[e],void 0!==o.elapsedTime)return o;yield F(n)}throw new Error(`RPC ${e} timed out`)})),U=({rpcId:e,instance:t})=>l(void 0,void 0,void 0,(function*(){for(;t.state.lastRpcId===e||void 0===t.state.lastRpcId;)yield F(200);return t.state.lastRpcId})),j=e=>l(void 0,void 0,void 0,(function*(){var t,n,o,i,s;return f.SocketService(`[SocketService: reconnectSocket()] instance.state.socket?.connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} trying to reconnect after socketio disconnection`,e),yield F(200),(null===(n=e.state.socket)||void 0===n?void 0:n.connected)||(e.state.resumed=!0,null===(o=e.state.socket)||void 0===o||o.connect(),e.emit($.SOCKET_RECONNECT),null===(i=e.state.socket)||void 0===i||i.emit($.JOIN_CHANNEL,e.state.channelId,`${e.state.context}connect_again`)),yield F(100),null===(s=e.state.socket)||void 0===s?void 0:s.connected}));function z(e){return t=>{f.SocketService(`[SocketService: handleDisconnect()] on 'disconnect' manualDisconnect=${e.state.manualDisconnect}`,t),e.state.manualDisconnect||(e.emit($.SOCKET_DISCONNECTED),function(e){"undefined"!=typeof window&&"undefined"!=typeof document&&(f.SocketService(`[SocketService: checkFocusAndReconnect()] hasFocus=${document.hasFocus()}`,e),document.hasFocus()?j(e).then((t=>{f.SocketService(`SocketService::checkFocus reconnectSocket success=${t}`,e)})).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)})):window.addEventListener("focus",(()=>{j(e).catch((e=>{console.error("SocketService::checkFocus Error reconnecting socket",e)}))}),{once:!0}))}(e))}}const G=[{event:"clients_connected",handler:function(e,t){return n=>l(this,void 0,void 0,(function*(){var n,o,i,s,a,c,r,l;f.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected-${t}' resumed=${e.state.resumed} clientsPaused=${e.state.clientsPaused} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()} isOriginator=${e.state.isOriginator}`),e.emit($.CLIENTS_CONNECTED,{isOriginator:e.state.isOriginator,keysExchanged:null===(o=e.state.keyExchange)||void 0===o?void 0:o.areKeysExchanged(),context:e.state.context}),e.state.resumed?(e.state.isOriginator||(f.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} 'clients_connected' / keysExchanged=${null===(i=e.state.keyExchange)||void 0===i?void 0:i.areKeysExchanged()} -- backward compatibility`),null===(s=e.state.keyExchange)||void 0===s||s.start({isOriginator:null!==(a=e.state.isOriginator)&&void 0!==a&&a})),e.state.resumed=!1):e.state.clientsPaused?f.SocketService("[SocketService: handleClientsConnected()] 'clients_connected' skip sending originatorInfo on pause"):e.state.isOriginator||(f.SocketService(`[SocketService: handleClientsConnected()] context=${e.state.context} on 'clients_connected' / keysExchanged=${null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged()} -- backward compatibility`),null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l,force:!0})),e.state.clientsConnected=!0,e.state.clientsPaused=!1}))}},{event:"channel_created",handler:function(e,t){return n=>{f.SocketService(`[SocketService: handleChannelCreated()] context=${e.state.context} on 'channel_created-${t}'`,n),e.emit($.CHANNEL_CREATED,n)}}},{event:"clients_disconnected",handler:function(e,t){return()=>{var n;e.state.clientsConnected=!1,f.SocketService(`[SocketService: handlesClientsDisconnected()] context=${e.state.context} on 'clients_disconnected-${t}'`),e.state.isOriginator&&!e.state.clientsPaused&&(null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.emit($.CLIENTS_DISCONNECTED,t)}}},{event:"message",handler:function(e,t){return({id:n,message:o,error:i})=>{var s,a,c,r,l,d,u,h,m,g,E,v,y,C,p;if(f.SocketService(`[SocketService handleMessage()] context=${e.state.context} on 'message' ${t} keysExchanged=${null===(s=e.state.keyExchange)||void 0===s?void 0:s.areKeysExchanged()}`,o),i)throw f.SocketService(`\n [SocketService handleMessage()] context=${e.state.context}::on 'message' error=${i}`),new Error(i);try{!function(e,t){if(t!==e.channelId)throw e.debug&&console.error(`Wrong id ${t} - should be ${e.channelId}`),new Error("Wrong id")}(e.state,n)}catch(e){return void console.error("ignore message --- wrong id ",o)}if(e.state.isOriginator&&(null==o?void 0:o.type)===M.KEY_HANDSHAKE_START)return f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received HANDSHAKE_START isOriginator=${e.state.isOriginator}`,o),void(null===(a=e.state.keyExchange)||void 0===a||a.start({isOriginator:null!==(c=e.state.isOriginator)&&void 0!==c&&c,force:!0}));if((null==o?void 0:o.type)===P.PING)return f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' ping `),void e.emit($.MESSAGE,{message:{type:"ping"}});if(f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' originator=${e.state.isOriginator}, type=${null==o?void 0:o.type}, keysExchanged=${null===(r=e.state.keyExchange)||void 0===r?void 0:r.areKeysExchanged()}`),null===(l=null==o?void 0:o.type)||void 0===l?void 0:l.startsWith("key_handshake"))return f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' emit KEY_EXCHANGE`,o),void e.emit(L.KEY_EXCHANGE,{message:o,context:e.state.context});if(null===(d=e.state.keyExchange)||void 0===d?void 0:d.areKeysExchanged()){if(-1!==o.toString().indexOf("type"))return console.warn("[SocketService handleMessage() ::on 'message' received non encrypted unkwown message"),void e.emit($.MESSAGE,o)}else{let t=!1;try{null===(u=e.state.keyExchange)||void 0===u||u.decryptMessage(o),t=!0}catch(e){}if(!t)return e.state.isOriginator?null===(m=e.state.keyExchange)||void 0===m||m.start({isOriginator:null!==(g=e.state.isOriginator)&&void 0!==g&&g}):e.sendMessage({type:M.KEY_HANDSHAKE_START}),void console.warn(`Message ignored because invalid key exchange status. step=${null===(E=e.state.keyExchange)||void 0===E?void 0:E.getKeyInfo().step}`,null===(v=e.state.keyExchange)||void 0===v?void 0:v.getKeyInfo(),o);console.warn("Invalid key exchange status detected --- updating it."),null===(h=e.state.keyExchange)||void 0===h||h.setKeysExchanged(!0)}const S=null===(y=e.state.keyExchange)||void 0===y?void 0:y.decryptMessage(o),k=JSON.parse(null!=S?S:"{}");if((null==k?void 0:k.type)===P.PAUSE?e.state.clientsPaused=!0:e.state.clientsPaused=!1,e.state.isOriginator&&k.data){const t=k.data,n=e.state.rpcMethodTracker[t.id];if(n){const o=Date.now()-n.timestamp;f.SocketService(`[SocketService handleMessage()] context=${e.state.context}::on 'message' received answer for id=${t.id} method=${n.method} responseTime=${o}`,k);const i=Object.assign(Object.assign({},n),{result:t.result,error:t.error?{code:null===(C=t.error)||void 0===C?void 0:C.code,message:null===(p=t.error)||void 0===p?void 0:p.message}:void 0,elapsedTime:o});e.state.rpcMethodTracker[t.id]=i,e.emit($.RPC_UPDATE,i),f.SocketService("[SocketService handleMessage()] HACK (wallet <7.3) update rpcMethodTracker",i),e.emit($.AUTHORIZED)}}e.emit($.MESSAGE,{message:k})}}},{event:"clients_waiting_to_join",handler:function(e,t){return n=>{f.SocketService(`[SocketService: handleClientsWaitingToJoin()] context=${e.state.context} on 'clients_waiting_to_join-${t}'`,n),e.emit($.CLIENTS_WAITING,n)}}}],W=[{event:$.KEY_INFO,handler:function(e){return t=>{f.SocketService("[SocketService: handleKeyInfo()] on 'KEY_INFO'",t),e.emit($.KEY_INFO,t)}}},{event:$.KEYS_EXCHANGED,handler:function(e){return()=>{var t,n;f.SocketService(`[SocketService: handleKeysExchanged()] on 'keys_exchanged' keyschanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.emit($.KEYS_EXCHANGED,{keysExchanged:null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged(),isOriginator:e.state.isOriginator});const o={keyInfo:e.getKeyInfo()};e.emit($.SERVICE_STATUS,o)}}}];function V(e,t){f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} setting socket listeners for channel ${t}...`);const{socket:n}=e.state,{keyExchange:o}=e.state;e.state.setupChannelListeners&&console.warn(`[SocketService: setupChannelListener()] context=${e.state.context} socket listeners already set up for channel ${t}`),n&&e.state.isOriginator&&(e.state.debug&&(null==n||n.io.on("error",(t=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=error`,t)})),null==n||n.io.on("reconnect",(t=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect`,t)})),null==n||n.io.on("reconnect_error",(t=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_error`,t)})),null==n||n.io.on("reconnect_failed",(()=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=reconnect_failed`)})),null==n||n.io.on("ping",(()=>{f.SocketService(`[SocketService: setupChannelListener()] context=${e.state.context} socket event=ping`)}))),null==n||n.on("disconnect",(t=>(f.SocketService(`[SocketService: setupChannelListener()] on 'disconnect' -- MetaMaskSDK socket disconnected '${t}' begin recovery...`),z(e)(t))))),G.forEach((({event:o,handler:i})=>{const s=`${o}-${t}`;null==n||n.on(s,i(e,t))})),W.forEach((({event:t,handler:n})=>{null==o||o.on(t,n(e))})),e.state.setupChannelListeners=!0}var J;!function(e){e.REQUEST="sdk_connect_request_started",e.REQUEST_MOBILE="sdk_connect_request_started_mobile",e.RECONNECT="sdk_reconnect_request_started",e.CONNECTED="sdk_connection_established",e.CONNECTED_MOBILE="sdk_connection_established_mobile",e.AUTHORIZED="sdk_connection_authorized",e.REJECTED="sdk_connection_rejected",e.TERMINATED="sdk_connection_terminated",e.DISCONNECTED="sdk_disconnected",e.SDK_USE_EXTENSION="sdk_use_extension",e.SDK_RPC_REQUEST="sdk_rpc_request",e.SDK_EXTENSION_UTILIZED="sdk_extension_utilized",e.SDK_USE_INAPP_BROWSER="sdk_use_inapp_browser"}(J||(J={}));const Z="SDK_CONNECTION_ISSUE";var B;!function(e){e.RPC_CHECK="rpcCheck",e.SKIPPED_RPC="skippedRpc"}(B||(B={}));const X=["eth_sendTransaction","eth_signTypedData","eth_signTransaction","wallet_requestPermissions","wallet_switchEthereumChain","eth_signTypedData_v3","eth_signTypedData_v4","metamask_connectSign","metamask_connectWith","metamask_batch"].map((e=>e.toLowerCase()));function Q(e,t){var n,o,i,s;if(!e.state.channelId)throw new Error("Create a channel first");f.SocketService(`[SocketService: handleSendMessage()] context=${e.state.context} areKeysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`,t);(null===(o=null==t?void 0:t.type)||void 0===o?void 0:o.startsWith("key_handshake"))?function(e,t){var n;f.SocketService(`[SocketService: handleKeyHandshake()] context=${e.state.context}`,t),null===(n=e.state.socket)||void 0===n||n.emit($.MESSAGE,{id:e.state.channelId,context:e.state.context,message:t})}(e,t):(!function(e,t){var n;if(!(null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()))throw f.SocketService(`[SocketService: validateKeyExchange()] context=${e.state.context} ERROR keys not exchanged`,t),new Error("Keys not exchanged BBB")}(e,t),function(e,t){var n;const o=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"",i=null==t?void 0:t.id;e.state.isOriginator&&i&&(e.state.rpcMethodTracker[i]={id:i,timestamp:Date.now(),method:o},e.emit($.RPC_UPDATE,e.state.rpcMethodTracker[i]))}(e,t),function(e,t){var n,o;const i=null===(n=e.state.keyExchange)||void 0===n?void 0:n.encryptMessage(JSON.stringify(t)),s={id:e.state.channelId,context:e.state.context,message:i,plaintext:e.state.hasPlaintext?JSON.stringify(t):void 0};f.SocketService(`[SocketService: encryptAndSendMessage()] context=${e.state.context}`,s),t.type===P.TERMINATE&&(e.state.manualDisconnect=!0),null===(o=e.state.socket)||void 0===o||o.emit($.MESSAGE,s)}(e,t),e.remote.state.analytics&&t.method&&X.includes(t.method.toLowerCase())&&_({id:null!==(i=e.remote.state.channelId)&&void 0!==i?i:"",event:J.SDK_RPC_REQUEST,sdkVersion:e.remote.state.sdkVersion,commLayerVersion:A.version,walletVersion:null===(s=e.remote.state.walletInfo)||void 0===s?void 0:s.version,params:{method:t.method,from:"mobile"}},e.remote.state.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),function(e,t){var n;return l(this,void 0,void 0,(function*(){const o=null==t?void 0:t.id,i=null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"";if(e.state.isOriginator&&o)try{const n=Y(o,e.state.rpcMethodTracker,200).then((e=>({type:B.RPC_CHECK,result:e}))),s=(()=>l(this,void 0,void 0,(function*(){const t=yield U({instance:e,rpcId:o}),n=yield Y(t,e.state.rpcMethodTracker,200);return{type:B.SKIPPED_RPC,result:n}})))(),a=yield Promise.race([n,s]);if(a.type===B.RPC_CHECK){const e=a.result;f.SocketService(`[SocketService:handleRpcReplies()] id=${t.id} ${i} ( ${e.elapsedTime} ms)`,e.result)}else{if(a.type!==B.SKIPPED_RPC)throw new Error(`Error handling RPC replies for ${o}`);{const{result:t}=a;console.warn(`[SocketService handleRpcReplies()] RPC METHOD HAS BEEN SKIPPED rpcid=${o} method=${i}`,t);const n=Object.assign(Object.assign({},e.state.rpcMethodTracker[o]),{error:new Error(Z)});e.emit($.RPC_UPDATE,n);const s={data:Object.assign(Object.assign({},n),{jsonrpc:"2.0"}),name:"metamask-provider"};e.emit($.MESSAGE,{message:s})}}}catch(e){throw console.warn(`[SocketService handleRpcReplies()] Error rpcId=${t.id} ${i}`,e),e}}))}(e,t).catch((e=>{console.warn("Error handleRpcReplies",e)})))}class q extends s{constructor({otherPublicKey:e,reconnect:t,communicationLayerPreference:n,transports:o,communicationServerUrl:i,context:s,ecies:a,remote:c,logging:l}){super(),this.state={clientsConnected:!1,clientsPaused:!1,manualDisconnect:!1,lastRpcId:void 0,rpcMethodTracker:{},hasPlaintext:!1,communicationServerUrl:""},this.state.resumed=t,this.state.context=s,this.state.communicationLayerPreference=n,this.state.debug=!0===(null==l?void 0:l.serviceLayer),this.remote=c,!0===(null==l?void 0:l.serviceLayer)&&v.enable("SocketService:Layer"),this.state.communicationServerUrl=i,this.state.hasPlaintext=this.state.communicationServerUrl!==O&&!0===(null==l?void 0:l.plaintext);const d={autoConnect:!1,transports:T,withCredentials:!0};o&&(d.transports=o),f.SocketService(`[SocketService: constructor()] Socket IO url: ${this.state.communicationServerUrl}`),this.state.socket=r(i,d);const u={communicationLayer:this,otherPublicKey:e,sendPublicKey:!1,context:this.state.context,ecies:a,logging:l};this.state.keyExchange=new H(u)}resetKeys(){return e=this,f.SocketService("[SocketService: resetKeys()] Resetting keys."),void(null===(t=e.state.keyExchange)||void 0===t||t.resetKeys());var e,t}createChannel(){return function(e){var t,n,o,i;f.SocketService(`[SocketService: createChannel()] context=${e.state.context}`),(null===(t=e.state.socket)||void 0===t?void 0:t.connected)||null===(n=e.state.socket)||void 0===n||n.connect(),e.state.manualDisconnect=!1,e.state.isOriginator=!0;const s=c();return e.state.channelId=s,V(e,s),null===(o=e.state.socket)||void 0===o||o.emit($.JOIN_CHANNEL,s,`${e.state.context}createChannel`),{channelId:s,pubKey:(null===(i=e.state.keyExchange)||void 0===i?void 0:i.getMyPublicKey())||""}}(this)}connectToChannel({channelId:e,isOriginator:t=!1,withKeyExchange:n=!1}){return function({options:e,instance:t}){var n,o,i,s;const{channelId:a,withKeyExchange:c,isOriginator:r}=e;if(f.SocketService(`[SocketService: connectToChannel()] context=${t.state.context} channelId=${a} isOriginator=${r}`,null===(n=t.state.keyExchange)||void 0===n?void 0:n.toString()),null===(o=t.state.socket)||void 0===o?void 0:o.connected)throw new Error("socket already connected");t.state.manualDisconnect=!1,null===(i=t.state.socket)||void 0===i||i.connect(),t.state.withKeyExchange=c,t.state.isOriginator=r,t.state.channelId=a,V(t,a),null===(s=t.state.socket)||void 0===s||s.emit($.JOIN_CHANNEL,a,`${t.state.context}_connectToChannel`)}({options:{channelId:e,isOriginator:t,withKeyExchange:n},instance:this})}getKeyInfo(){return this.state.keyExchange.getKeyInfo()}keyCheck(){var e,t;null===(t=(e=this).state.socket)||void 0===t||t.emit($.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:M.KEY_HANDSHAKE_CHECK,pubkey:e.getKeyInfo().ecies.otherPubKey}})}getKeyExchange(){return this.state.keyExchange}sendMessage(e){return Q(this,e)}ping(){return e=this,f.SocketService(`[SocketService: ping()] context=${e.state.context} originator=${e.state.isOriginator} keysExchanged=${null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged()}`),e.state.isOriginator&&((null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged())?(console.warn(`[SocketService:ping()] context=${e.state.context} sending READY message`),e.sendMessage({type:P.READY})):(console.warn(`[SocketService: ping()] context=${e.state.context} starting key exchange`),null===(o=e.state.keyExchange)||void 0===o||o.start({isOriginator:null!==(i=e.state.isOriginator)&&void 0!==i&&i}))),void(null===(s=e.state.socket)||void 0===s||s.emit($.MESSAGE,{id:e.state.channelId,context:e.state.context,message:{type:P.PING}}));var e,t,n,o,i,s}pause(){return e=this,f.SocketService(`[SocketService: pause()] context=${e.state.context}`),e.state.manualDisconnect=!0,(null===(t=e.state.keyExchange)||void 0===t?void 0:t.areKeysExchanged())&&e.sendMessage({type:P.PAUSE}),void(null===(n=e.state.socket)||void 0===n||n.disconnect());var e,t,n}isConnected(){var e;return null===(e=this.state.socket)||void 0===e?void 0:e.connected}resume(){return e=this,f.SocketService(`[SocketService: resume()] context=${e.state.context} connected=${null===(t=e.state.socket)||void 0===t?void 0:t.connected} manualDisconnect=${e.state.manualDisconnect} resumed=${e.state.resumed} keysExchanged=${null===(n=e.state.keyExchange)||void 0===n?void 0:n.areKeysExchanged()}`),(null===(o=e.state.socket)||void 0===o?void 0:o.connected)?f.SocketService("[SocketService: resume()] already connected."):(null===(i=e.state.socket)||void 0===i||i.connect(),f.SocketService(`[SocketService: resume()] after connecting socket --\x3e connected=${null===(s=e.state.socket)||void 0===s?void 0:s.connected}`),null===(a=e.state.socket)||void 0===a||a.emit($.JOIN_CHANNEL,e.state.channelId,`${e.state.context}_resume`)),(null===(c=e.state.keyExchange)||void 0===c?void 0:c.areKeysExchanged())?e.state.isOriginator||e.sendMessage({type:P.READY}):e.state.isOriginator||null===(r=e.state.keyExchange)||void 0===r||r.start({isOriginator:null!==(l=e.state.isOriginator)&&void 0!==l&&l}),e.state.manualDisconnect=!1,void(e.state.resumed=!0);var e,t,n,o,i,s,a,c,r,l}getRPCMethodTracker(){return this.state.rpcMethodTracker}disconnect(e){return function(e,t){var n,o;f.SocketService(`[SocketService: disconnect()] context=${e.state.context}`,t),(null==t?void 0:t.terminate)&&(e.state.channelId=t.channelId,null===(n=e.state.keyExchange)||void 0===n||n.clean()),e.state.rpcMethodTracker={},e.state.manualDisconnect=!0,null===(o=e.state.socket)||void 0===o||o.disconnect()}(this,e)}}var ee,te,ne;function oe(e){return()=>l(this,void 0,void 0,(function*(){var t,n,o;const{state:i}=e;if(i.authorized)return;yield(()=>l(this,void 0,void 0,(function*(){for(;!i.walletInfo;)yield F(500)})))();const s="7.3".localeCompare((null===(t=i.walletInfo)||void 0===t?void 0:t.version)||"");if(f.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' version=${null===(n=i.walletInfo)||void 0===n?void 0:n.version} compareValue=${s}`),1!==s)return;const a=i.platformType===te.MobileWeb||i.platformType===te.ReactNative||i.platformType===te.MetaMaskMobileWebview;f.RemoteCommunication(`[RemoteCommunication: handleAuthorizedEvent()] HACK 'authorized' platform=${i.platformType} secure=${a} channel=${i.channelId} walletVersion=${null===(o=i.walletInfo)||void 0===o?void 0:o.version}`),a&&(i.authorized=!0,e.emit($.AUTHORIZED))}))}function ie(e){return t=>{const{state:n}=e;f.RemoteCommunication(`[RemoteCommunication: handleChannelCreatedEvent()] context=${n.context} on 'channel_created' channelId=${t}`),e.emit($.CHANNEL_CREATED,t)}}function se(e,t){return()=>{var n,o,i,s;const{state:a}=e;if(f.RemoteCommunication(`[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=${a.channelId} keysExchanged=${null===(o=null===(n=a.communicationLayer)||void 0===n?void 0:n.getKeyInfo())||void 0===o?void 0:o.keysExchanged}`),a.analytics){const e=a.isOriginator?J.REQUEST:J.REQUEST_MOBILE;_(Object.assign(Object.assign({id:null!==(i=a.channelId)&&void 0!==i?i:"",event:a.reconnection?J.RECONNECT:e},a.originatorInfo),{commLayer:t,sdkVersion:a.sdkVersion,walletVersion:null===(s=a.walletInfo)||void 0===s?void 0:s.version,commLayerVersion:A.version}),a.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}a.clientsConnected=!0,a.originatorInfoSent=!1,e.emit($.CLIENTS_CONNECTED)}}function ae(e,t){return n=>{var o;const{state:i}=e;f.RemoteCommunication(`[RemoteCommunication: handleClientsDisconnectedEvent()] context=${i.context} on 'clients_disconnected' channelId=${n}`),i.clientsConnected=!1,e.emit($.CLIENTS_DISCONNECTED,i.channelId),e.setConnectionStatus(D.DISCONNECTED),i.ready=!1,i.authorized=!1,i.analytics&&i.channelId&&_({id:i.channelId,event:J.DISCONNECTED,sdkVersion:i.sdkVersion,commLayer:t,commLayerVersion:A.version,walletVersion:null===(o=i.walletInfo)||void 0===o?void 0:o.version},i.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)}))}}function ce(e){return t=>{var n;const{state:o}=e;if(f.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] context=${o.context} on 'clients_waiting' numberUsers=${t} ready=${o.ready} autoStarted=${o.originatorConnectStarted}`),e.setConnectionStatus(D.WAITING),e.emit($.CLIENTS_WAITING,t),o.originatorConnectStarted){f.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] on 'clients_waiting' watch autoStarted=${o.originatorConnectStarted} timeout`,o.autoConnectOptions);const t=(null===(n=o.autoConnectOptions)||void 0===n?void 0:n.timeout)||3e3,i=setTimeout((()=>{f.RemoteCommunication(`[RemoteCommunication: handleClientsWaitingEvent()] setTimeout(${t}) terminate channelConfig`,o.autoConnectOptions),o.originatorConnectStarted=!1,o.ready||e.setConnectionStatus(D.TIMEOUT),clearTimeout(i)}),t)}}}function re(e,t){return n=>{var o,i,s,a,c;const{state:r}=e;f.RemoteCommunication(`[RemoteCommunication: handleKeysExchangedEvent()] context=${r.context} on commLayer.'keys_exchanged' channel=${r.channelId}`,n),(null===(i=null===(o=r.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.keysExchanged)&&e.setConnectionStatus(D.LINKED),function(e,t){var n,o,i,s;const{state:a}=e;f.RemoteCommunication(`[RemoteCommunication: setLastActiveDate()] channel=${a.channelId}`,t);const c={channelId:null!==(n=a.channelId)&&void 0!==n?n:"",validUntil:null!==(i=null===(o=a.channelConfig)||void 0===o?void 0:o.validUntil)&&void 0!==i?i:0,lastActive:t.getTime()};null===(s=a.storageManager)||void 0===s||s.persistChannelConfig(c)}(e,new Date),r.analytics&&r.channelId&&_({id:r.channelId,event:n.isOriginator?J.CONNECTED:J.CONNECTED_MOBILE,sdkVersion:r.sdkVersion,commLayer:t,commLayerVersion:A.version,walletVersion:null===(s=r.walletInfo)||void 0===s?void 0:s.version},r.communicationServerUrl).catch((e=>{console.error("Cannot send analytics",e)})),r.isOriginator=n.isOriginator,n.isOriginator||(null===(a=r.communicationLayer)||void 0===a||a.sendMessage({type:P.READY}),r.ready=!0,r.paused=!1),n.isOriginator&&!r.originatorInfoSent&&(null===(c=r.communicationLayer)||void 0===c||c.sendMessage({type:P.ORIGINATOR_INFO,originatorInfo:r.originatorInfo,originator:r.originatorInfo}),r.originatorInfoSent=!0)}}function le(e,t){const{state:n}=t;if(f.RemoteCommunication(`[RemoteCommunication: onCommunicationLayerMessage()] context=${n.context} on 'message' typeof=${typeof e}`,e),t.state.ready=!0,n.isOriginator||e.type!==P.ORIGINATOR_INFO)if(n.isOriginator&&e.type===P.WALLET_INFO)!function(e,t){const{state:n}=e;n.walletInfo=t.walletInfo,n.paused=!1}(t,e);else{if(e.type===P.TERMINATE)!function(e){const{state:t}=e;t.isOriginator&&(ge({options:{terminate:!0,sendMessage:!1},instance:e}),console.debug(),e.emit($.TERMINATE))}(t);else if(e.type===P.PAUSE)!function(e){const{state:t}=e;t.paused=!0,e.setConnectionStatus(D.PAUSED)}(t);else if(e.type===P.READY&&n.isOriginator)!function(e){const{state:t}=e;e.setConnectionStatus(D.LINKED);const n=t.paused;t.paused=!1,e.emit($.CLIENTS_READY,{isOriginator:t.isOriginator,walletInfo:t.walletInfo}),n&&(t.authorized=!0,e.emit($.AUTHORIZED))}(t);else{if(e.type===P.OTP&&n.isOriginator)return void function(e,t){var n;const{state:o}=e;e.emit($.OTP,t.otpAnswer),1==="6.6".localeCompare((null===(n=o.walletInfo)||void 0===n?void 0:n.version)||"")&&(console.warn("RemoteCommunication::on 'otp' -- backward compatibility <6.6 -- triger eth_requestAccounts"),e.emit($.SDK_RPC_CALL,{method:b.ETH_REQUESTACCOUNTS,params:[]}))}(t,e);e.type===P.AUTHORIZED&&n.isOriginator&&function(e){const{state:t}=e;t.authorized=!0,e.emit($.AUTHORIZED)}(t)}t.emit($.MESSAGE,e)}else!function(e,t){var n;const{state:o}=e;null===(n=o.communicationLayer)||void 0===n||n.sendMessage({type:P.WALLET_INFO,walletInfo:o.walletInfo}),o.originatorInfo=t.originatorInfo||t.originator,e.emit($.CLIENTS_READY,{isOriginator:o.isOriginator,originatorInfo:o.originatorInfo}),o.paused=!1}(t,e)}function de(e,t){var n,o;return l(this,void 0,void 0,(function*(){const{state:i}=e;f.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} paused=${i.paused} ready=${i.ready} authorized=${i.authorized} socket=${null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected()} clientsConnected=${i.clientsConnected} status=${i._connectionStatus}`,t),!i.paused&&i.ready&&(null===(o=i.communicationLayer)||void 0===o?void 0:o.isConnected())&&i.clientsConnected||(f.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} SKIP message waiting for MM mobile readiness.`),yield new Promise((t=>{e.once($.CLIENTS_READY,t)})),f.RemoteCommunication(`[RemoteCommunication: sendMessage()] context=${i.context} AFTER SKIP / READY -- sending pending message`));try{yield function(e,t){return l(this,void 0,void 0,(function*(){return new Promise((n=>{var o,i,s,a;const{state:c}=e;if(f.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} ready=${c.ready} authorized=${c.authorized} method=${t.method}`),1==="7.3".localeCompare((null===(o=c.walletInfo)||void 0===o?void 0:o.version)||""))return f.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] compatibility hack wallet version > ${null===(i=c.walletInfo)||void 0===i?void 0:i.version}`),null===(s=c.communicationLayer)||void 0===s||s.sendMessage(t),void n();!c.isOriginator||c.authorized?(null===(a=c.communicationLayer)||void 0===a||a.sendMessage(t),n()):e.once($.AUTHORIZED,(()=>{var e;f.RemoteCommunication(`[RemoteCommunication: handleAuthorization()] context=${c.context} AFTER SKIP / AUTHORIZED -- sending pending message`),null===(e=c.communicationLayer)||void 0===e||e.sendMessage(t),n()}))}))}))}(e,t)}catch(e){throw console.error(`[RemoteCommunication: sendMessage()] context=${i.context} ERROR`,e),e}}))}function ue(e){return t=>{let n=t;t.message&&(n=n.message),le(n,e)}}function he(e){return()=>{const{state:t}=e;f.RemoteCommunication("[RemoteCommunication: handleSocketReconnectEvent()] on 'socket_reconnect' -- reset key exchange status / set ready to false"),t.ready=!1,t.authorized=!1,w(t),e.emitServiceStatusEvent()}}function me(e){return()=>{const{state:t}=e;f.RemoteCommunication("[RemoteCommunication: handleSocketDisconnectedEvent()] on 'socket_Disconnected' set ready to false"),t.ready=!1}}function ge({options:e,instance:t}){var n,o,i,s,a,r;const{state:l}=t;f.RemoteCommunication(`[RemoteCommunication: disconnect()] channel=${l.channelId}`,e),l.ready=!1,l.paused=!1,(null==e?void 0:e.terminate)?(null===(n=l.storageManager)||void 0===n||n.terminate(null!==(o=l.channelId)&&void 0!==o?o:""),(null===(i=l.communicationLayer)||void 0===i?void 0:i.getKeyInfo().keysExchanged)&&(null==e?void 0:e.sendMessage)&&(null===(s=l.communicationLayer)||void 0===s||s.sendMessage({type:P.TERMINATE})),l.channelId=c(),e.channelId=l.channelId,l.channelConfig=void 0,l.originatorConnectStarted=!1,null===(a=l.communicationLayer)||void 0===a||a.disconnect(e),t.setConnectionStatus(D.TERMINATED)):(null===(r=l.communicationLayer)||void 0===r||r.disconnect(e),t.setConnectionStatus(D.DISCONNECTED))}!function(e){e.SOCKET="socket"}(ee||(ee={})),function(e){e.NonBrowser="nodejs",e.MetaMaskMobileWebview="in-app-browser",e.DesktopWeb="web-desktop",e.MobileWeb="web-mobile",e.ReactNative="react-native"}(te||(te={}));class Ee extends s{constructor({platformType:e,communicationLayerPreference:t,otherPublicKey:n,reconnect:o,walletInfo:i,dappMetadata:s,transports:a,context:c,ecies:r,analytics:l=!1,storage:d,sdkVersion:u,communicationServerUrl:h=O,logging:m,autoConnect:g={timeout:3e3}}){super(),this.state={ready:!1,authorized:!1,isOriginator:!1,paused:!1,platformType:"metamask-mobile",analytics:!1,reconnection:!1,originatorInfoSent:!1,communicationServerUrl:O,context:"",clientsConnected:!1,sessionDuration:R,originatorConnectStarted:!1,debug:!1,_connectionStatus:D.DISCONNECTED},this.state.otherPublicKey=n,this.state.dappMetadata=s,this.state.walletInfo=i,this.state.transports=a,this.state.platformType=e,this.state.analytics=l,this.state.isOriginator=!n,this.state.communicationServerUrl=h,this.state.context=c,this.state.sdkVersion=u,this.setMaxListeners(50),this.setConnectionStatus(D.DISCONNECTED),(null==d?void 0:d.duration)&&(this.state.sessionDuration=R),this.state.storageOptions=d,this.state.autoConnectOptions=g,this.state.debug=!0===(null==m?void 0:m.remoteLayer),!0===(null==m?void 0:m.remoteLayer)&&v.enable("RemoteCommunication:Layer"),this.state.logging=m,(null==d?void 0:d.storageManager)&&(this.state.storageManager=d.storageManager),this.initCommunicationLayer({communicationLayerPreference:t,otherPublicKey:n,reconnect:o,ecies:r,communicationServerUrl:h}),this.emitServiceStatusEvent()}initCommunicationLayer({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=O}){return function({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i=O,instance:s}){var a,c,r,l,d;const{state:u}=s;if(e!==ee.SOCKET)throw new Error("Invalid communication protocol");u.communicationLayer=new q({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,transports:u.transports,communicationServerUrl:i,context:u.context,ecies:o,logging:u.logging,remote:s});let h="undefined"!=typeof document&&document.URL||"",m="undefined"!=typeof document&&document.title||"";(null===(a=u.dappMetadata)||void 0===a?void 0:a.url)&&(h=u.dappMetadata.url),(null===(c=u.dappMetadata)||void 0===c?void 0:c.name)&&(m=u.dappMetadata.name);const g={url:h,title:m,source:null===(r=u.dappMetadata)||void 0===r?void 0:r.source,icon:(null===(l=u.dappMetadata)||void 0===l?void 0:l.iconUrl)||(null===(d=u.dappMetadata)||void 0===d?void 0:d.base64Icon),platform:u.platformType,apiVersion:A.version};u.originatorInfo=g;const E={[$.AUTHORIZED]:oe(s),[$.MESSAGE]:ue(s),[$.CLIENTS_CONNECTED]:se(s,e),[$.KEYS_EXCHANGED]:re(s,e),[$.SOCKET_DISCONNECTED]:me(s),[$.SOCKET_RECONNECT]:he(s),[$.CLIENTS_DISCONNECTED]:ae(s,e),[$.KEY_INFO]:()=>{s.emitServiceStatusEvent()},[$.CHANNEL_CREATED]:ie(s),[$.CLIENTS_WAITING]:ce(s),[$.RPC_UPDATE]:e=>{s.emit($.RPC_UPDATE,e)}};for(const[e,t]of Object.entries(E))try{u.communicationLayer.on(e,t)}catch(t){console.error(`Error registering handler for ${e}:`,t)}}({communicationLayerPreference:e,otherPublicKey:t,reconnect:n,ecies:o,communicationServerUrl:i,instance:this})}originatorSessionConnect(){return l(this,void 0,void 0,(function*(){return yield function(e){var t,n,o;return l(this,void 0,void 0,(function*(){const{state:i}=e;if(!i.storageManager)return void f.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] no storage manager defined - skip");const s=yield i.storageManager.getPersistedChannelConfig(null!==(t=i.channelId)&&void 0!==t?t:"");if(f.RemoteCommunication(`[RemoteCommunication: originatorSessionConnect()] autoStarted=${i.originatorConnectStarted} channelConfig`,s),null===(n=i.communicationLayer)||void 0===n?void 0:n.isConnected())return f.RemoteCommunication("[RemoteCommunication: originatorSessionConnect()] socket already connected - skip"),s;if(s){if(s.validUntil>Date.now())return i.channelConfig=s,i.originatorConnectStarted=!0,i.channelId=null==s?void 0:s.channelId,i.reconnection=!0,null===(o=i.communicationLayer)||void 0===o||o.connectToChannel({channelId:s.channelId,isOriginator:!0}),s;f.RemoteCommunication("[RemoteCommunication: autoConnect()] Session has expired")}i.originatorConnectStarted=!1}))}(this)}))}generateChannelIdConnect(){return l(this,void 0,void 0,(function*(){return function(e){var t,n,o,i,s;if(!e.communicationLayer)throw new Error("communication layer not initialized");if(e.ready)throw new Error("Channel already connected");if(e.channelId&&(null===(t=e.communicationLayer)||void 0===t?void 0:t.isConnected()))return console.warn("Channel already exists -- interrupt generateChannelId",e.channelConfig),e.channelConfig={channelId:e.channelId,validUntil:Date.now()+e.sessionDuration},null===(n=e.storageManager)||void 0===n||n.persistChannelConfig(e.channelConfig),{channelId:e.channelId,pubKey:null===(i=null===(o=e.communicationLayer)||void 0===o?void 0:o.getKeyInfo())||void 0===i?void 0:i.ecies.public};f.RemoteCommunication("[RemoteCommunication: generateChannelId()]"),w(e);const a=e.communicationLayer.createChannel();f.RemoteCommunication("[RemoteCommunication: generateChannelId()] channel created",a);const c={channelId:a.channelId,validUntil:Date.now()+e.sessionDuration};return e.channelId=a.channelId,e.channelConfig=c,null===(s=e.storageManager)||void 0===s||s.persistChannelConfig(c),{channelId:e.channelId,pubKey:a.pubKey}}(this.state)}))}clean(){return w(this.state)}connectToChannel(e,t){return function({channelId:e,withKeyExchange:t,state:n}){var o,i,s;if(!a(e))throw f.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} invalid channel channelId=${e}`),new Error(`Invalid channel ${e}`);if(f.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} channelId=${e}`),null===(o=n.communicationLayer)||void 0===o?void 0:o.isConnected())return void f.RemoteCommunication(`[RemoteCommunication: connectToChannel()] context=${n.context} already connected - interrupt connection.`);n.channelId=e,null===(i=n.communicationLayer)||void 0===i||i.connectToChannel({channelId:e,withKeyExchange:t});const c={channelId:e,validUntil:Date.now()+n.sessionDuration};n.channelConfig=c,null===(s=n.storageManager)||void 0===s||s.persistChannelConfig(c)}({channelId:e,withKeyExchange:t,state:this.state})}sendMessage(e){return de(this,e)}testStorage(){return l(this,void 0,void 0,(function*(){return function(e){var t,n;return l(this,void 0,void 0,(function*(){const o=yield null===(t=e.storageManager)||void 0===t?void 0:t.getPersistedChannelConfig(null!==(n=e.channelId)&&void 0!==n?n:"");f.RemoteCommunication("[RemoteCommunication: testStorage()] res",o)}))}(this.state)}))}getChannelConfig(){return this.state.channelConfig}isReady(){return this.state.ready}isConnected(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.isConnected()}isAuthorized(){return this.state.authorized}isPaused(){return this.state.paused}getCommunicationLayer(){return this.state.communicationLayer}ping(){var e;f.RemoteCommunication(`[RemoteCommunication: ping()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.ping()}keyCheck(){var e;f.RemoteCommunication(`[RemoteCommunication: keyCheck()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.keyCheck()}setConnectionStatus(e){this.state._connectionStatus!==e&&(this.state._connectionStatus=e,this.emit($.CONNECTION_STATUS,e),this.emitServiceStatusEvent())}emitServiceStatusEvent(){this.emit($.SERVICE_STATUS,this.getServiceStatus())}getConnectionStatus(){return this.state._connectionStatus}getServiceStatus(){return{originatorInfo:this.state.originatorInfo,keyInfo:this.getKeyInfo(),connectionStatus:this.state._connectionStatus,channelConfig:this.state.channelConfig,channelId:this.state.channelId}}getKeyInfo(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getKeyInfo()}resetKeys(){var e;null===(e=this.state.communicationLayer)||void 0===e||e.resetKeys()}setOtherPublicKey(e){var t;const n=null===(t=this.state.communicationLayer)||void 0===t?void 0:t.getKeyExchange();if(!n)throw new Error("KeyExchange is not initialized.");n.getOtherPublicKey()!==e&&n.setOtherPublicKey(e)}pause(){var e;f.RemoteCommunication(`[RemoteCommunication: pause()] channel=${this.state.channelId}`),null===(e=this.state.communicationLayer)||void 0===e||e.pause(),this.setConnectionStatus(D.PAUSED)}getVersion(){return A.version}resume(){return function(e){var t;const{state:n}=e;f.RemoteCommunication(`[RemoteCommunication: resume()] channel=${n.channelId}`),null===(t=n.communicationLayer)||void 0===t||t.resume(),e.setConnectionStatus(D.LINKED)}(this)}getChannelId(){return this.state.channelId}getRPCMethodTracker(){var e;return null===(e=this.state.communicationLayer)||void 0===e?void 0:e.getRPCMethodTracker()}disconnect(e){return ge({options:e,instance:this})}}!function(e){e.RENEW="renew",e.LINK="link"}(ne||(ne={}));export{ne as AutoConnectType,ee as CommunicationLayerPreference,D as ConnectionStatus,O as DEFAULT_SERVER_URL,N as ECIES,$ as EventType,M as KeyExchangeMessageType,P as MessageType,te as PlatformType,Ee as RemoteCommunication,_ as SendAnalytics,q as SocketService,J as TrackingEvents};
//# sourceMappingURL=metamask-sdk-communication-layer.js.map

@@ -1,2 +0,2 @@

export declare const DEFAULT_SERVER_URL = "https://metamask-sdk-socket.metafi.codefi.network/";
export declare const DEFAULT_SERVER_URL = "https://metamask-sdk.api.cx.metamask.io/";
export declare const DEFAULT_SOCKET_TRANSPORTS: string[];

@@ -3,0 +3,0 @@ export declare const MIN_IN_MS: number;

{
"name": "@metamask/sdk-communication-layer",
"version": "0.17.0",
"version": "0.18.0",
"description": "",

@@ -5,0 +5,0 @@ "homepage": "https://github.com/MetaMask/metamask-sdk#readme",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc