LavaPack.loadBundle([[999,{"@firebase/app":997,"@firebase/component":998,"@firebase/util":1003,idb:6871},function(){with(this.scopeTerminator)with(this.globalThis)return function(){"use strict";return function(e,t,a){Object.defineProperty(a,"__esModule",{value:!0}),a.deleteInstallations=
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function(e){const{appConfig:t}=e,a=await K(t,e=>e&&0===e.registrationStatus?undefined:e);if(a){if(1===a.registrationStatus)throw m.create("delete-pending-registration");if(2===a.registrationStatus){if(!navigator.onLine)throw m.create("app-offline");
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
await async function(e,t){const a=function(e,{fid:t}){return`${h(e)}/${t}`}(e,t),n=T(e,t),r={method:"DELETE",headers:n},i=await M(()=>fetch(a,r));if(!i.ok)throw await w("Delete Installation",i)}(t,a),await x(t)}}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */,a.getId=J,a.getInstallations=
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function(e=(0,n.getApp)()){return(0,n._getProvider)(e,"installations").getImmediate()}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */,a.getToken=X,a.onIdChange=function(e,t){const{appConfig:a}=e;return function(e,t){O();const a=A(e);let n=P.get(a);n||(n=new Set,P.set(a,n));n.add(t)}(a,t),()=>{!function(e,t){const a=A(e),n=P.get(a);if(!n)return;n.delete(t),0===n.size&&P.delete(a);R()}(a,t)}};var n=e("@firebase/app"),r=e("@firebase/component"),i=e("@firebase/util"),s=e("idb");const o="@firebase/installations",l="0.6.12",c=1e4,d=`w:${l}`,u="FIS_v2",p="https://firebaseinstallations.googleapis.com/v1",f=36e5,g={"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."},m=new i.ErrorFactory("installations","Installations",g);function b(e){return e instanceof i.FirebaseError&&e.code.includes("request-failed")}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function h({projectId:e}){return`${p}/projects/${e}/installations`}function E(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function w(e,t){const a=(await t.json()).error;return m.create("request-failed",{requestName:e,serverCode:a.code,serverMessage:a.message,serverStatus:a.status})}function S({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function T(e,{refreshToken:t}){const a=S(e);return a.append("Authorization",function(e){return`${u} ${e}`}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(t)),a}async function M(e){const t=await e();return t.status>=500&&t.status<600?e():t}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function y(e){return new Promise(t=>{setTimeout(t,e)})}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const C=/^[cdef][\w-]{21}$/,v="";function I(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function(e){const t=(a=e,btoa(String.fromCharCode(...a)).replace(/\+/g,"-").replace(/\//g,"_"));var a;return t.substr(0,22)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e);return C.test(t)?t:v}catch(e){return v}}function A(e){return`${e.appName}!${e.appId}`}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const P=new Map;function N(e,t){const a=A(e);_(a,t),function(e,t){const a=O();a&&a.postMessage({key:e,fid:t});R()}(a,t)}function _(e,t){const a=P.get(e);if(a)for(const e of a)e(t)}let k=null;function O(){return!k&&"BroadcastChannel"in self&&(k=new BroadcastChannel("[Firebase] FID Change"),k.onmessage=e=>{_(e.data.key,e.data.fid)}),k}function R(){0===P.size&&k&&(k.close(),k=null)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const L="firebase-installations-database",U=1,D="firebase-installations-store";let j=null;function V(){return j||(j=(0,s.openDB)(L,U,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(D)}})),j}async function F(e,t){const a=A(e),n=(await V()).transaction(D,"readwrite"),r=n.objectStore(D),i=await r.get(a);return await r.put(t,a),await n.done,i&&i.fid===t.fid||N(e,t.fid),t}async function x(e){const t=A(e),a=(await V()).transaction(D,"readwrite");await a.objectStore(D).delete(t),await a.done}async function K(e,t){const a=A(e),n=(await V()).transaction(D,"readwrite"),r=n.objectStore(D),i=await r.get(a),s=t(i);return s===undefined?await r.delete(a):await r.put(s,a),await n.done,!s||i&&i.fid===s.fid||N(e,s.fid),s}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function B(e){let t;const a=await K(e.appConfig,a=>{const n=function(e){const t=e||{fid:I(),registrationStatus:0};return Y(t)}(a),r=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(m.create("app-offline"))}}const a={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(e,t){try{const a=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:a}){const n=h(e),r=S(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&r.append("x-firebase-client",e)}const s={fid:a,authVersion:u,appId:e.appId,sdkVersion:d},o={method:"POST",headers:r,body:JSON.stringify(s)},l=await M(()=>fetch(n,o));if(l.ok){const e=await l.json();return{fid:e.fid||a,registrationStatus:2,refreshToken:e.refreshToken,authToken:E(e.authToken)}}throw await w("Create Installation",l)}(e,t);return F(e.appConfig,a)}catch(a){throw b(a)&&409===a.customData.serverCode?await x(e.appConfig):await F(e.appConfig,{fid:t.fid,registrationStatus:0}),a}}(e,a);return{installationEntry:a,registrationPromise:n}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:$(e)}:{installationEntry:t}}(e,n);return t=r.registrationPromise,r.installationEntry});return a.fid===v?{installationEntry:await t}:{installationEntry:a,registrationPromise:t}}async function $(e){let t=await q(e.appConfig);for(;1===t.registrationStatus;)await y(100),t=await q(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:a}=await B(e);return a||t}return t}function q(e){return K(e,e=>{if(!e)throw m.create("installation-not-found");return Y(e)})}function Y(e){return 1===(t=e).registrationStatus&&t.registrationTime+c<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t;
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}async function z({appConfig:e,heartbeatServiceProvider:t},a){const n=function(e,{fid:t}){return`${h(e)}/${t}/authTokens:generate`}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e,a),r=T(e,a),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&r.append("x-firebase-client",e)}const s={installation:{sdkVersion:d,appId:e.appId}},o={method:"POST",headers:r,body:JSON.stringify(s)},l=await M(()=>fetch(n,o));if(l.ok){return E(await l.json())}throw await w("Generate Auth Token",l)}async function H(e,t=!1){let a;const n=await K(e.appConfig,n=>{if(!W(n))throw m.create("not-registered");const r=n.authToken;if(!t&&function(e){return 2===e.requestStatus&&!function(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+f}(e)}(r))return n;if(1===r.requestStatus)return a=async function(e,t){let a=await G(e.appConfig);for(;1===a.authToken.requestStatus;)await y(100),a=await G(e.appConfig);const n=a.authToken;return 0===n.requestStatus?H(e,t):n}(e,t),n;{if(!navigator.onLine)throw m.create("app-offline");const t=function(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(n);return a=async function(e,t){try{const a=await z(e,t),n=Object.assign(Object.assign({},t),{authToken:a});return await F(e.appConfig,n),a}catch(a){if(!b(a)||401!==a.customData.serverCode&&404!==a.customData.serverCode){const a=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await F(e.appConfig,a)}else await x(e.appConfig);throw a}}(e,t),t}});return a?await a:n.authToken}function G(e){return K(e,e=>{if(!W(e))throw m.create("not-registered");const t=e.authToken;return 1===(a=t).requestStatus&&a.requestTime+c<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;var a;
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */})}function W(e){return e!==undefined&&2===e.registrationStatus}async function J(e){const t=e,{installationEntry:a,registrationPromise:n}=await B(t);return n?n.catch(console.error):H(t).catch(console.error),a.fid}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function X(e,t=!1){const a=e;await async function(e){const{registrationPromise:t}=await B(e);t&&await t}(a);return(await H(a,t)).token}function Q(e){return m.create("missing-app-config-values",{valueName:e})}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Z="installations",ee=e=>{const t=e.getProvider("app").getImmediate(),a=function(e){if(!e||!e.options)throw Q("App Configuration");if(!e.name)throw Q("App Name");const t=["projectId","apiKey","appId"];for(const a of t)if(!e.options[a])throw Q(a);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:a,heartbeatServiceProvider:(0,n._getProvider)(t,"heartbeat"),_delete:()=>Promise.resolve()}},te=e=>{const t=e.getProvider("app").getImmediate(),a=(0,n._getProvider)(t,Z).getImmediate();return{getId:()=>J(a),getToken:e=>X(a,e)}};(0,n._registerComponent)(new r.Component(Z,ee,"PUBLIC")),(0,n._registerComponent)(new r.Component("installations-internal",te,"PRIVATE")),(0,n.registerVersion)(o,l),(0,n.registerVersion)(o,l,"esm2017")}}},{package:"@metamask/notification-services-controller>firebase>@firebase/installations",file:"node_modules/@firebase/installations/dist/esm/index.esm2017.js"}],[12,{"../../shared/constants/app":8502,"../../shared/constants/app-state":8501,"../../shared/constants/defi-referrals":8512,"../../shared/constants/errors":8513,"../../shared/constants/infura-project-id":8518,"../../shared/constants/messages":8523,"../../shared/constants/metametrics":8524,"../../shared/constants/offscreen-communication":8530,"../../shared/constants/onboarding":8531,"../../shared/constants/start-up-errors":8544,"../../shared/constants/ui-initialization":8552,"../../shared/lib/active-tab-domain-metrics":8569,"../../shared/lib/browser-runtime.utils":8586,"../../shared/lib/caip-stream":8589,"../../shared/lib/fetch-with-timeout":8642,"../../shared/lib/get-first-preferred-lang-code":8662,"../../shared/lib/install-attribution":8666,"../../shared/lib/manifestFlags":8668,"../../shared/lib/mv3.utils":8680,"../../shared/lib/object.utils":8683,"../../shared/lib/promise-with-resolvers":8693,"../../shared/lib/selectors/networks":8703,"../../shared/lib/sentry":8709,"../../shared/lib/stores/persistence-manager":8723,"./constants/background":13,"./constants/marketing-site-whitelist":14,"./constants/sentry-state":15,"./constants/snaps":16,"./constants/stream":17,"./controllers/analytics":21,"./first-time-state":65,"./lib/CronjobControllerStorageManager":69,"./lib/approval/utils":76,"./lib/critical-error/critical-error-recovery":91,"./lib/critical-error/critical-error-tab-handoff":92,"./lib/deep-links/deep-link-router":96,"./lib/deep-links/metrics":97,"./lib/defi-referrals/createDefiReferralMiddleware":98,"./lib/ens-ipfs/setup":106,"./lib/extension-lazy-listener/extension-lazy-listener":107,"./lib/getIframeProperties":109,"./lib/getObjStructure":110,"./lib/migrator":116,"./lib/notification-manager":119,"./lib/repair":133,"./lib/safe-reload":150,"./lib/setup-initial-state-hooks":154,"./lib/start-up-errors/start-up-errors":167,"./lib/state-corruption/state-corruption-recovery":168,"./lib/stream-utils":171,"./lib/update-remote-feature-flags":208,"./lib/use-split-state-storage":209,"./lib/util":210,"./metamask-controller":433,"./migrations":682,"./offscreen":683,"./on-update":684,"./platforms/extension":685,"@metamask/base-controller":1480,"@metamask/design-tokens":2154,"@metamask/utils":4030,"extension-port-stream":6590,loglevel:7191,"readable-stream":7670,"webextension-polyfill":8489},function(){with(this.scopeTerminator)with(this.globalThis)return function(){"use strict";return function(e,t,a){Object.defineProperty(a,"__esModule",{value:!0}),a.loadStateFromPersistence=it,a.setupController=ut;var n=e("./lib/setup-initial-state-hooks");e("../../shared/constants/infura-project-id");var r=e("@metamask/design-tokens"),i=e("readable-stream"),s=pe(e("loglevel")),o=pe(e("webextension-polyfill")),l=e("@metamask/utils"),c=e("@metamask/base-controller"),d=e("extension-port-stream"),u=e("../../shared/lib/promise-with-resolvers"),p=e("../../shared/constants/onboarding"),f=e("../../shared/constants/app"),g=e("../../shared/constants/app-state"),m=e("../../shared/constants/messages"),b=e("../../shared/constants/ui-initialization"),h=e("../../shared/constants/metametrics"),E=e("../../shared/lib/active-tab-domain-metrics"),w=e("../../shared/lib/browser-runtime.utils"),S=e("../../shared/lib/mv3.utils"),T=e("../../shared/lib/object.utils"),M=(e("../../shared/constants/offscreen-communication"),e("../../shared/lib/sentry")),y=e("../../shared/lib/selectors/networks"),C=e("../../shared/lib/caip-stream"),v=pe(e("../../shared/lib/fetch-with-timeout")),I=e("../../shared/constants/errors"),A=pe(e("../../shared/lib/get-first-preferred-lang-code")),P=(e("../../shared/lib/manifestFlags"),e("../../shared/constants/start-up-errors")),N=e("../../shared/constants/defi-referrals"),_=e("../../shared/lib/install-attribution"),k=e("../../shared/lib/stores/persistence-manager"),O=e("./lib/critical-error/critical-error-recovery"),R=e("./lib/state-corruption/state-corruption-recovery"),L=e("./lib/approval/utils"),U=e("./lib/use-split-state-storage"),D=pe(e("./migrations")),j=pe(e("./lib/migrator")),V=e("./lib/update-remote-feature-flags"),F=pe(e("./platforms/extension")),x=e("./constants/sentry-state"),K=ue(e("./lib/notification-manager")),B=ue(e("./metamask-controller")),$=e("./controllers/analytics"),q=pe(e("./lib/getObjStructure")),Y=pe(e("./lib/ens-ipfs/setup")),z=e("./lib/util"),H=e("./offscreen"),G=e("./lib/stream-utils"),W=pe(e("./first-time-state")),J=e("./on-update"),X=e("./constants/marketing-site-whitelist"),Q=e("./constants/stream"),Z=e("./constants/snaps"),ee=e("./lib/extension-lazy-listener/extension-lazy-listener"),te=e("./lib/deep-links/deep-link-router"),ae=e("./lib/deep-links/metrics"),ne=e("./lib/safe-reload"),re=e("./lib/critical-error/critical-error-tab-handoff"),ie=e("./lib/repair"),se=e("./lib/start-up-errors/start-up-errors"),oe=e("./lib/CronjobControllerStorageManager"),le=e("./lib/defi-referrals/createDefiReferralMiddleware"),ce=e("./lib/getIframeProperties"),de=e("./constants/background");function ue(e,t){if("function"==typeof WeakMap)var a=new WeakMap,n=new WeakMap;return(ue=function(e,t){if(!t&&e&&e.__esModule)return e;var r,i,s={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return s;if(r=t?n:a){if(r.has(e))return r.get(e);r.set(e,s)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(r=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?r(s,t,i):s[t]=e[t]);return s})(e,t)}function pe(e){return e&&e.__esModule?e:{default:e}}const fe=globalThis.stateHooks.lazyListener??new ee.ExtensionLazyListener(o.default),ge="#0376C9",me=r.lightTheme.colors.error.default,be=9,he=99,Ee=!1;const we=null,{safePersist:Se,requestSafeReload:Te,evacuate:Me}=(0,ne.getRequestSafeReload)(n.persistenceManager);global.stateHooks.getMostRecentPersistedState=()=>n.persistenceManager.mostRecentRetrievedState,global.stateHooks.getStorageKind=()=>n.persistenceManager.storageKind,global.logEncryptedVault=()=>{n.persistenceManager.logEncryptedVault()};const{sentry:ye}=global;let Ce={...W.default};const ve={[f.ENVIRONMENT_TYPE_POPUP]:!0,[f.ENVIRONMENT_TYPE_NOTIFICATION]:!0,[f.ENVIRONMENT_TYPE_FULLSCREEN]:!0};s.default.setLevel("info",!1);const Ie=new F.default,Ae=new K.default,Pe=(0,z.getPlatform)()===f.PLATFORM_FIREFOX;function Ne(e){const t=e.name,a=e.sender?.url?new URL(e.sender.url):null;let n;return n=Pe?Boolean(ve[t]):a?.origin===`chrome-extension://${o.default.runtime.id}`,{processName:t,senderUrl:a,isMetaMaskUIPort:n}}let _e=0,ke=!1,Oe=!1,Re=0,Le=0;const Ue=new Set,De={},je={};let Ve;const Fe={},xe={},Ke={};const Be=new URL("https://metamask.github.io/phishing-warning/v5.1.0/"),$e=Be.toString();let qe,Ye,ze;function He(){const e=(0,u.withResolvers)();qe=e.promise,Ye=e.resolve,ze=e.reject}fe.once("runtime","onInstalled").then(e=>{!async function([e]){if("install"===e.reason)await async function(){s.default.debug("First install detected");const e=(0,_.getInstallAttribution)();Ie.openExtensionInBrowser();await qe,await ft(e)}();else if("update"===e.reason){const{previousVersion:t}=e;if(!t||t===Ie.getVersion())return;await qe,(0,J.onUpdate)(Ve,Ie,t,Te)}}(e)}),He(),o.default?.sidePanel?.setPanelBehavior&&o.default.sidePanel.setPanelBehavior({openPanelOnActionClick:!0}).catch(()=>{});let Ge,We,Je,Xe;const Qe=new R.CorruptionHandler,Ze=new O.CriticalErrorHandler,et=async e=>{const{isMetaMaskUIPort:t}=Ne(e);try{e.postMessage({data:{method:b.BACKGROUND_LIVENESS_METHOD},name:"background-liveness"})}catch(e){return void s.default.error("MetaMask - background-liveness check: Failed to message to port",e)}let a;t&&(Ze.registerPortForCriticalError({port:e,repairCallback:()=>(0,ie.requestRepair)(()=>(0,re.openRestoringTabAndReload)(Te))}),a=()=>Ze.removeListenersForPort(e));try{if(await qe,t&&!(0,se.tryPostMessage)(e,b.BACKGROUND_INITIALIZED_METHOD))return;Ee,Ge(e,a)}catch(r){try{if(ye?.captureException(r),t)if((0,I.isStateCorruptionError)(r))await Qe.handleStateCorruptionError({port:e,error:r,database:n.persistenceManager,repairCallback:async e=>{He(),(0,k.hasVault)(e)?(await gt(e),Ve.onboardingController.setFirstTimeFlowType(p.FirstTimeFlowType.restore)):(await n.persistenceManager.reset(),await gt(null))}});else{const t=(0,l.isObject)(r)?{message:r.message??"Unknown error",name:r.name??"UnknownError",stack:r.stack,...r.sentryTags&&{sentryTags:r.sentryTags}}:{message:String(r),name:"UnknownError",stack:""};(0,se.tryPostMessage)(e,P.DISPLAY_GENERAL_STARTUP_ERROR,{error:t,currentLocale:Ve?.preferencesController?.state?.currentLocale})}}finally{a?.()}}},tt=()=>{fe.addListener("runtime","onConnect",et)};function at(){const e=(new Date).toISOString();o.default.storage.session.set({timestamp:e})}async function nt(e){(0,z.initInstallType)();const t=S.isManifestV3?(0,H.createOffscreen)():null;let a=null,r=!1;S.isManifestV3&&(0,H.addOffscreenConnectivityListener)(e=>{if(r&&Ve.connectivityAdapter){const t=e?"online":"offline";Ve.connectivityAdapter.setStatus(t)}else a=e});const i=await it(e),s=i.data,l=await(0,A.default)();let c;if(S.isManifestV3){if(!1!==s.PreferencesController?.enableMV3TimestampSave){const e=2e3;at(),setInterval(at,e)}const e=await o.default.storage.session.get(["isFirstMetaMaskControllerSetup"]);c=e?.isFirstMetaMaskControllerSetup===undefined,await o.default.storage.session.set({isFirstMetaMaskControllerSetup:c})}const d=await async function(){const e=(0,v.default)(),t=Z.PREINSTALLED_SNAPS_URLS.map(async t=>{const a=await e(t);if(t.pathname.endsWith(".json.gz")){const e=new DecompressionStream("gzip"),t=a.body.pipeThrough(e);return await new Response(t).json()}return await a.json()});return Promise.all(t)}(),u=new oe.CronjobControllerStorageManager;if(await u.init(),ut(s,l,c,i.meta,t,d,u),Ve.metaMetricsController.updateTraits({[h.MetaMetricsUserTrait.StorageKind]:n.persistenceManager.storageKind}),function(e){async function t(e,t){try{const a=await o.default.tabs.get(e);return!(a.url&&a.url.startsWith("https://www.google.com/search")||(await o.default.tabs.update(e,{url:t}),0))}catch(e){return ye?.captureException(e),!1}}const a=!S.isManifestV3;o.default.webRequest.onBeforeRequest.addListener(n=>{if(n.tabId===o.default.tabs.TAB_ID_NONE)return{};const{completedOnboarding:r}=e.onboardingController.state;if(!r)return{};if(!e.preferencesController.state.usePhishDetect)return{};if(n.initiator&&"null"!==n.initiator&&new URL(n.initiator).host===Be.host)return{};const{hostname:i,href:s,searchParams:l}=new URL(n.url);e.phishingController.maybeUpdateState();const c=e.phishingController.isBlockedRequest(n.url);let d,u;if("main_frame"!==n.type&&"sub_frame"!==n.type||(d=e.phishingController.test(n.url)),!d?.result&&!c.result)return{};let p,f=s;d?.result&&c.result?u=`${d.type} and ${c.type}`:d?.result?u=d.type:(u=c.type,f=n.initiator);try{p=new URL(f).hostname}catch{p=i,f=s}const g=new URLSearchParams({hostname:p,href:f}),m=new URL($e);m.hash=g.toString();const b=m.toString(),E=()=>{Pe||(0,$.trackEvent)((0,$.createEventBuilder)(h.MetaMetricsEventName.PhishingPageDisplayed).addCategory(h.MetaMetricsEventCategory.Phishing).addProperties({url:f,referrer:{url:f},reason:u,requestDomain:c.result?i:undefined}).build({excludeMetaMetricsId:!0}))};return a?"main_frame"===n.type?(E(),{redirectUrl:b}):(t(n.tabId,b).then(e=>{e&&E()}),{cancel:!0}):(t(n.tabId,b).then(e=>{e&&E()}),{})},{urls:["http://*/*","https://*/*","ws://*/*","wss://*/*"]},a?["blocking"]:[])}(Ve),S.isManifestV3){if(r=!0,null!==a){const e=a?"online":"offline";Ve.connectivityAdapter.setStatus(e)}}else{const e=e=>{const t=e?"online":"offline";Ve.connectivityAdapter.setStatus(t)};e(globalThis.navigator.onLine),globalThis.addEventListener("online",()=>e(!0)),globalThis.addEventListener("offline",()=>e(!1))}S.isManifestV3||await async function(){let e;try{const t=new URL($e);let a,n;t.hash="#extensionStartup",e=window.document.createElement("iframe"),e.setAttribute("src",t.href),e.setAttribute("sandbox","allow-scripts allow-same-origin");const r=new Promise((e,t)=>{a=e,n=t});e.addEventListener("load",a),window.document.body.appendChild(e),setTimeout(()=>n(new rt),1e3),await r}catch(e){e instanceof rt?console.warn("Phishing warning page timeout; page not guaranteed to work offline."):console.error("Failed to initialize phishing warning page",e)}finally{e&&e.remove()}}(),await(async()=>{const e=await o.default.tabs.query({url:"<all_urls>",windowType:"normal"}).then(e=>((0,w.checkForLastErrorAndLog)(),e)).catch(()=>{(0,w.checkForLastErrorAndLog)()});for(const t of e)o.default.tabs.sendMessage(t.id,{name:m.EXTENSION_MESSAGES.READY}).then(()=>{(0,w.checkForLastErrorAndLog)()}).catch(()=>{(0,w.checkForLastErrorAndLog)()})})(),new te.DeepLinkRouter({getExtensionURL:Ie.getExtensionURL,getState:Ve.getState.bind(Ve)}).on("navigate",async({url:e,parsed:t})=>{"redirectTo"in t||(0,$.trackEvent)((0,ae.createEvent)({signature:t.signature,url:e}))}).on("error",e=>ye?.captureException(e)).install()}tt(),o.default.runtime.onConnectExternal.addListener(async(...e)=>{await qe,We(...e)});class rt extends Error{constructor(){super("Timeout failed")}}async function it(e){let t;if(e){t={data:{},meta:{}};for(const a of k.backedUpStateKeys)(0,l.hasProperty)(e,a)&&(t.data[a]=e[a]);(0,l.hasProperty)(e,"meta")&&(0,l.isObject)(e.meta)&&(t.meta=e.meta,"split"===e.meta.storageKind||"data"===e.meta.storageKind?n.persistenceManager.storageKind=e.meta.storageKind:n.persistenceManager.storageKind="data"),"number"!=typeof t.meta.version&&(s.default.error("The `backup`'s `meta.version` property was missing during backup restore."),t.meta.version=155)}else{const e=!0;t=await n.persistenceManager.get({validateVault:e})}const a=new j.default({migrations:D.default,defaultVersion:null});a.on("error",e=>{console.warn(e);const a=(0,q.default)(t);ye?.captureException(e,{extra:{vaultStructure:a}})});let r=!1;t?.data||t?.meta||(r=!0,t=a.generateInitialState(Ce));const{state:i,changedKeys:o}=await a.migrateData(t),c=async a=>{const r=t?.meta?.version,s="number"==typeof r&&r>=157;let o=e?.AppMetadataController?.firstTimeInfo??i?.data?.AppMetadataController?.firstTimeInfo??i?.data?.firstTimeInfo??t?.data?.AppMetadataController?.firstTimeInfo??t?.data?.firstTimeInfo;if(!o)try{const e=await n.persistenceManager.getBackup();o=e?.AppMetadataController?.firstTimeInfo}catch{}const l=new Error(a);return l.sentryTags={"corruption.preMigrationVersion":String(r??"unknown"),"corruption.backupShouldExist":String(s),"corruption.installVersion":String(o?.version??"unknown"),"corruption.installDate":String(o?.date??"unknown")},l};if(!i)throw await c("MetaMask - migrator returned undefined");if(!(0,l.isObject)(i.meta))throw await c(`MetaMask - migrator metadata has invalid type '${typeof i.meta}'`);if("number"!=typeof i.meta.version)throw await c(`MetaMask - migrator metadata version has invalid type '${typeof i.meta.version}'`);if(!["data","split",undefined].includes(i.meta.storageKind))throw await c(`MetaMask - migrator metadata storageKind has invalid value '${i.meta.storageKind}'`);if(!(0,l.isObject)(i.data))throw await c(`MetaMask - migrator data has invalid type '${typeof i.data}'`);if(n.persistenceManager.setMetadata(i.meta),s.default.debug("[Split State]: Loaded data from persistence with storageKind '%s'",n.persistenceManager.storageKind),"data"===n.persistenceManager.storageKind){const e=!0===i.meta.platformSplitStateGradualRolloutAttempted,t=!e&&await(0,U.useSplitStateStorage)(i.data);s.default.debug("[Split State]: shouldUseSplitStateStorage: %s (alreadyTried: %s)",t,e),t&&(i.meta.platformSplitStateGradualRolloutAttempted=!0,n.persistenceManager.setMetadata(i.meta)),s.default.debug("[Split State]: Writing data to persistence with storageKind 'data'"),await n.persistenceManager.set(i.data),t&&(await n.persistenceManager.migrateToSplitState(i.data),i.meta=n.persistenceManager.getMetaData(),i.meta!==undefined&&(delete i.meta.platformSplitStateGradualRolloutAttempted,n.persistenceManager.setMetadata(i.meta)),await n.persistenceManager.persist())}else{if("split"!==n.persistenceManager.storageKind)throw new Error(`MetaMask - persistenceManager has invalid storageKind '${n.persistenceManager.storageKind}'`);if(r)for(const[e,t]of Object.entries(i.data))n.persistenceManager.update(e,t);else for(const e of o)n.persistenceManager.update(e,i.data[e]);await n.persistenceManager.persist()}return s.default.debug("[Split State]: Load complete."),i}function st(e,t,a){const{analyticsId:n}=Ve.getState();if(!(0,z.shouldEmitDappViewedEvent)(n))return;const r=Ve.getPermittedAccounts(e).length;if(0===r)return;const i=Ve.controllerMessenger.call("AccountsController:getState"),s=Object.keys(i.internalAccounts.accounts).length,o=(0,ce.getIframeProperties)({frameId:a,origin:e,mainFrameOrigin:t});(0,$.trackEvent)((0,$.createEventBuilder)(h.MetaMetricsEventName.DappViewed).addCategory(h.MetaMetricsEventCategory.InpageProvider).addProperties({is_first_visit:!1,number_of_accounts:s,number_of_accounts_connected:r,...o}).build({referrer:{url:e},excludeMetaMetricsId:!0}))}function ot(e){if(!e.sender?.tab||!e.sender?.url||!e.sender?.tab?.url)return;const t=e.sender.tab.id,a=new URL(e.sender.url),{origin:n}=a,r=new URL(e.sender.tab.url),{origin:i}=r,{frameId:s}=e.sender;Object.keys(Fe).includes(t)||(Fe[t]=n),t in xe||(xe[t]=i),t in Ke||(Ke[t]=s);const o=Ve.controllerMessenger.call("PermissionController:hasPermissions",n),l="New Tab"!==e.sender.tab.title;o&&l&&st(n,i,s)}function lt(e){const{completedMetaMetricsOnboarding:t,optedIn:a}=Ve.getState();if(!t||!a)return;const n=Ve.appStateController.state.appActiveTab?.origin,r=(0,E.getActiveTabDomainAllowlist)(Ve.remoteFeatureFlagController.state),i=(0,E.getActiveTabDomainForMetrics)(n,r);(0,$.trackEvent)((0,$.createEventBuilder)(h.MetaMetricsEventName.AppOpened).addCategory(h.MetaMetricsEventCategory.App).addProperties(i?{active_tab_domain:i}:{}).build({environmentType:e}))}function ct(e){const t=[f.ENVIRONMENT_TYPE_POPUP,f.ENVIRONMENT_TYPE_NOTIFICATION,f.ENVIRONMENT_TYPE_FULLSCREEN,f.ENVIRONMENT_TYPE_SIDEPANEL];return!(Object.values(De).some(Boolean)||ke||_e>0||Re>0)&&t.includes(e)}const dt=async e=>{if(await qe,Ve)try{const t=e?{active:!0,windowId:e}:{active:!0,currentWindow:!0},a=await o.default.tabs.query(t);if(!a||0===a.length)return;const n=a[0],{id:r,title:i,url:s,favIconUrl:l}=n;if(!s)return void Ve.appStateController.clearAppActiveTab();const{origin:c,protocol:d,host:u,href:p}=new URL(s);if(!(0,z.isWebOrigin)(c))return void Ve.appStateController.clearAppActiveTab();Ve.appStateController.setAppActiveTab({id:r,title:i,origin:c,protocol:d,url:s,host:u,href:p,favIconUrl:l}),Ve.subjectMetadataController.addSubjectMetadata({origin:c,name:i||u||c,iconUrl:l||null,subjectType:"website"})}catch(e){console.log("Error refreshing appActiveTab:",e.message)}};function ut(e,t,a,r,l,u,p){Ve=new B.default({infuraProjectId:globalThis.INFURA_PROJECT_ID,showUserConfirmation:pt,initState:e,initLangCode:t,platform:Ie,notificationManager:Ae,browser:o.default,getRequestAccountTabIds:()=>je,getOpenMetamaskTabsIds:()=>De,isFirstMetaMaskControllerSetup:a,currentMigrationVersion:r.version,featureFlags:{},offscreenPromise:l,preinstalledSnaps:u,requestSafeReload:Te,cronjobControllerStorageManager:p}),n.persistenceManager.setOnSetFailed(e=>{Ve.appStateController.setStorageWriteErrorType(e)});const m=[],b=Ve.store.getState();for(const t of Object.keys(b)){const a=e[t]||{},n=b[t];if(null===n||"object"!=typeof n){(0,M.captureException)(new Error(`Invalid controller state for '${t}' of type '${null===n?"null":typeof n}'`));continue}const r=Object.keys(n);if(r.length===Object.keys(a).length){for(const e of r)if(n[e]!==a[e]){m.push(t);break}}else m.push(t)}var E;"split"===n.persistenceManager.storageKind?(m.length>0&&(s.default.info(`MetaMaskController state changed during configuration for controllers: ${m.join(", ")}. Persisting updated state.`),m.forEach(e=>{n.persistenceManager.update(e,b[e])}),Se().catch(e=>{s.default.error("Error persisting updated state:",e),ye?.captureException(e)})),Ve.store.on("stateChange",async({controllerKey:e,newState:t,_oldState:a,_patches:r})=>{n.persistenceManager.update(e,t),k.backedUpStateKeys.includes(e)&&k.backedUpStateKeys.forEach(t=>{if(t===e)return;const a=Ve.store.config[t];if(!a?.metadata)throw new Error(`Cannot backup ${t}: controller metadata is required but not found. All controllers in backedUpStateKeys must extend BaseController and define metadata.`);const r=Ve.controllerMessenger.call(`${t}:getState`),i=(0,c.deriveStateFromMetadata)(r,a.metadata,"persist");n.persistenceManager.update(t,i)});try{await Se()}catch(e){s.default.error("Error persisting state change:",e),ye?.captureException(e)}})):(m.length>0&&(s.default.info(`MetaMaskController state changed during configuration for controllers: ${m.join(", ")}. Persisting updated state.`),Se(b).catch(e=>{s.default.error("Error persisting updated controller state:",e),ye?.captureException(e)})),Ve.store.on("update",Se)),Ve.store.on("error",e=>{s.default.error("MetaMask controller.store error:",e),ye?.captureException(e)}),(0,Y.default)({getCurrentChainId:()=>(0,y.getCurrentChainId)({metamask:Ve.networkController.state}),getIpfsGateway:Ve.preferencesController.getIpfsGateway.bind(Ve.preferencesController),getUseAddressBarEnsResolution:()=>Ve.preferencesController.state.useAddressBarEnsResolution,provider:Ve.provider}),E=Ve,global.stateHooks.getSentryAppState=function(){const e=E.memStore.getState();return(0,T.maskObject)(e,x.SENTRY_BACKGROUND_STATE)};const w=()=>_e>0||Boolean(Object.keys(De).length)||ke||Re>0||!1,v=()=>_e>0||Re>0,I=()=>ke&&!v(),A=(e,t)=>{if(!1===e)Ve.onClientClosed();else{if(t===f.ENVIRONMENT_TYPE_FULLSCREEN&&Boolean(Object.keys(De).length)||t===f.ENVIRONMENT_TYPE_SIDEPANEL&&Re>0)return;Ve.onEnvironmentTypeClosed(t)}};function P(e){try{Ve.appStateController.setDefaultHomeActiveTabName(e??null)}catch(e){console.error("Error setting landing tab:",e)}}function N(){Ue.clear(),Le=0,O()}function _(e,t){return e>t?`${t}+`:String(e)}function O(){const e=R();let t="",a=ge;Le>0&&!I()?(t=_(Le,be),a=me):e>0&&(t=_(e,be));try{const e={text:t},n={color:a};S.isManifestV3?(o.default.action.setBadgeText(e),o.default.action.setBadgeBackgroundColor(n)):(o.default.browserAction.setBadgeText(e),o.default.browserAction.setBadgeBackgroundColor(n))}catch(e){console.error("Error updating browser badge:",e)}}function R(){try{return(0,L.getAttentionRequiredApprovalCount)({approvalController:Ve.approvalController})}catch(e){return console.error("Failed to get pending approval count:",e),0}}Ge=(e,t)=>{if(de.BLOCKED_PORTS.includes(e.name))return;const{processName:a,senderUrl:n,isMetaMaskUIPort:r}=Ne(e);if(r){const n=new d.ExtensionPortStream(e),r=function({chunkSize:e}){(0,$.trackEvent)((0,$.createEventBuilder)(h.MetaMetricsEventName.PortStreamChunked).addCategory(h.MetaMetricsEventCategory.PortStream).addProperties({chunkSize:e}).build())};e.onDisconnect.addListener(()=>n.off("message-too-large",r)),n.on("message-too-large",r),Ve.isClientOpen=!0,Ve.setupTrustedCommunication(n,e.sender).finally(()=>{t?.()});const o=a===f.ENVIRONMENT_TYPE_SIDEPANEL&&ct(f.ENVIRONMENT_TYPE_SIDEPANEL);if(a!==f.ENVIRONMENT_TYPE_SIDEPANEL&&ct(s=a)&&lt(s),(0,V.updateRemoteFeatureFlags)(Ve),a===f.ENVIRONMENT_TYPE_POPUP&&(N(),_e+=1,(0,i.finished)(n,()=>{_e-=1;const e=w();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_POPUP)})),a===f.ENVIRONMENT_TYPE_SIDEPANEL&&(N(),Re+=1,dt().then(()=>{o&&lt(f.ENVIRONMENT_TYPE_SIDEPANEL)}),(0,i.finished)(n,()=>{Re=Math.max(Re-1,0);const e=w();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_SIDEPANEL)})),a===f.ENVIRONMENT_TYPE_NOTIFICATION&&(ke=!0,(0,i.finished)(n,()=>{ke=!1,Le>0&&P(g.AccountOverviewTabKey.Activity),O();const e=w();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_NOTIFICATION)})),a===f.ENVIRONMENT_TYPE_FULLSCREEN){N();const t=e.sender.tab.id;De[t]=!0,(0,i.finished)(n,()=>{delete De[t];const e=w();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_FULLSCREEN)})}}else if(n&&n.origin===Be.origin&&n.pathname===Be.pathname){const t=new d.ExtensionPortStream(e,{chunkSize:0});Ve.setupPhishingCommunication({connectionStream:t})}else{if(e.sender&&e.sender.tab&&e.sender.url){const t=e.sender.tab.id,a=new URL(e.sender.url),{origin:n}=a;ot(e),e.onMessage.addListener(e=>{e.data&&e.data.method===f.MESSAGE_TYPE.ETH_REQUEST_ACCOUNTS&&(je[n]=t)})}if(n&&X.COOKIE_ID_MARKETING_WHITELIST_ORIGINS.some(e=>e===n.origin)){const t=new d.ExtensionPortStream(e,{chunkSize:0});Ve.setUpCookieHandlerCommunication({connectionStream:t})}const t=new d.ExtensionPortStream(e,{chunkSize:0});if(Je(t,e.sender),Pe||!S.isManifestV3){const a=(0,G.setupMultiplex)(t);a.ignoreStream(Q.METAMASK_EIP_1193_PROVIDER),Xe(a.createStream(Q.METAMASK_CAIP_MULTICHAIN_PROVIDER),e.sender)}}var s},We=e=>{const t=e.sender?.url;if(t){const{hostname:a}=new URL(t);if(de.BLOCKED_HOSTNAMES.includes(a))return void e.disconnect()}const a=new d.ExtensionPortStream(e,{chunkSize:0});if(!e.sender.id){if(de.BLOCKED_PORTS.includes(e.name))return;ot(e),Xe((0,C.createCaipStream)(a),e.sender)}else Je(a,e.sender)},Je=(e,t)=>{Ve.setupUntrustedCommunicationEip1193({connectionStream:e,sender:t})},Xe=(e,t)=>{Ve.setupUntrustedCommunicationCaip({connectionStream:e,sender:t})},O(),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.DECRYPT_MESSAGE_MANAGER_UPDATE_BADGE,O),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.ENCRYPTION_PUBLIC_KEY_MANAGER_UPDATE_BADGE,O),Ve.signatureController.hub.on(B.METAMASK_CONTROLLER_EVENTS.UPDATE_BADGE,O),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.APP_STATE_UNLOCK_CHANGE,O),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.APPROVAL_STATE_CHANGE,O),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_LIST_UPDATED,O),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_MARK_AS_READ,O),Ve.controllerMessenger.subscribe("TransactionController:transactionStatusUpdated",function({transactionMeta:e}){const{status:t,txParams:a,chainId:n}=e??{};if("failed"!==t&&"dropped"!==t)return;const{from:r,nonce:i}=a??{},s=r&&i!==undefined&&n?`${n}:${r.toLowerCase()}:${i}`:undefined;if(s&&Ue.has(s))return;if(v())return;s&&(Ue.size>=he&&Ue.clear(),Ue.add(s));Le+=1,I()||P(g.AccountOverviewTabKey.Activity);O()}),Ae.on(K.NOTIFICATION_MANAGER_EVENTS.POPUP_CLOSED,({automaticallyClosed:e})=>{e?R()>0&&pt():(Ve.signatureController.rejectUnapproved(h.REJECT_NOTIFICATION_CLOSE_SIG),Ve.decryptMessageController.rejectUnapproved(h.REJECT_NOTIFICATION_CLOSE),Ve.encryptionPublicKeyController.rejectUnapproved(h.REJECT_NOTIFICATION_CLOSE),Ve.legacyBackgroundApiService.rejectAllPendingApprovals()),O()})}async function pt(){const e=await Ie.getActiveTabs(),t=Boolean(e.find(e=>De[e.id])),a=e.length>0&&e[0].extData&&e[0].extData.indexOf("vivaldi_tab")>-1;if(!Oe&&(a||0===_e)&&!t&&0===Re){Oe=!0;try{const e=Ve.appStateController.getCurrentPopupId();await Ae.showPopup(e=>Ve.appStateController.setCurrentPopupId(e),e)}finally{Oe=!1}}}const ft=async e=>{const{deferredDeepLink:t,traits:a}=await e;Ve.metaMetricsController.updateTraits({[h.MetaMetricsUserTrait.InstallDateExt]:(new Date).toISOString().split("T")[0],...a});const n={};t&&(Ve.appStateController.setDeferredDeepLink(t),n.install_source="deeplink",n.deeplink_path=t.referringLink);const r={category:h.MetaMetricsEventCategory.App,event:h.MetaMetricsEventName.AppInstalled,properties:n},{completedMetaMetricsOnboarding:i,optedIn:s,analyticsId:o}=Ve.getState();!0===i&&!1===s||(!0===i&&!0===s&&o?(0,$.trackEvent)((0,$.createEventBuilder)(h.MetaMetricsEventName.AppInstalled).addCategory(h.MetaMetricsEventCategory.App).addProperties(n).build()):Ve.metaMetricsController.addEventBeforeMetricsOptIn(r))};o.default.runtime.onUpdateAvailable.addListener(async function(e){await qe,s.default.info("An update is available",e?.version),Ve.appStateController.setPendingExtensionVersion(e?.version??null)});(async()=>{if(o.default?.sidePanel)try{await qe,await async function(){if(!o.default?.sidePanel?.setPanelBehavior)return;const e=Ve?.preferencesController?.state?.preferences?.useSidePanelAsDefault??!0;await o.default.sidePanel.setPanelBehavior({openPanelOnActionClick:e})}(),Ve?.controllerMessenger?.subscribe("PreferencesController:stateChange",e=>{o.default?.sidePanel?.setPanelBehavior&&o.default.sidePanel.setPanelBehavior({openPanelOnActionClick:e}).catch(e=>console.error("Error updating panel behavior:",e))},e=>e?.preferences?.useSidePanelAsDefault??!0)}catch(e){console.error("Error setting side panel toolbar behavior:",e)}})();async function gt(e){o.default.tabs.onActivated.addListener(e=>{if(Ve){const{tabId:t}=e,a=Fe[t],n=xe[t];a&&Ve.permissionController.state.subjects[a]!==undefined&&st(a,n,Ke[t]);const r=(0,N.getPartnerByOrigin)(n);r&&Ve.permissionController.state.subjects[n]!==undefined&&Ve.handleDefiReferral(r,t,le.ReferralTriggerType.OnNavigateConnectedTab).catch(e=>{s.default.error(`Failed to handle ${r.name} referral after navigation to connected tab: `,e)})}});try{await nt(e),n.persistenceManager.cleanUpMostRecentRetrievedState(),s.default.info("MetaMask initialization complete."),Ye()}catch(e){s.default.error(e),ze(e)}}(async()=>{await dt()})(),o.default.tabs.onActivated.addListener(async({tabId:e})=>{if(await qe,!Ve)return{};try{const t=await o.default.tabs.get(e),{id:a,title:n,url:r,favIconUrl:i}=t;if(!r)return Ve.appStateController.clearAppActiveTab(),{};const{origin:s,protocol:l,host:c,href:d}=new URL(r);if(!(0,z.isWebOrigin)(s))return Ve.appStateController.clearAppActiveTab(),{};Ve.appStateController.setAppActiveTab({id:a,title:n,origin:s,protocol:l,url:r,host:c,href:d,favIconUrl:i}),Ve.subjectMetadataController.addSubjectMetadata({origin:s,name:n||c||s,iconUrl:i||null,subjectType:"website"})}catch(e){console.log("Error in tabs.onActivated listener:",e.message)}return{}}),o.default.tabs.onUpdated.addListener(async(e,t,a)=>{if(await qe,!Ve)return{};const n=t.url!==undefined,r="complete"===t.status;if(!n&&!r)return{};try{const t=a||await o.default.tabs.get(e),{id:i,title:s,url:l,favIconUrl:c}=t,d=Ve.appStateController.state.appActiveTab,u=d?.id===i;if(!l)return u&&Ve.appStateController.clearAppActiveTab(),{};const{origin:p,protocol:f,host:g,href:m}=new URL(l);if(!p||"null"===p||p.startsWith("chrome-extension://")||p.startsWith("moz-extension://"))return u&&Ve.appStateController.clearAppActiveTab(),{};let b=!1;try{b=(await o.default.tabs.query({active:!0,currentWindow:!0})).some(e=>e.id===i)}catch(e){b=u}(n||r)&&b&&(Ve.appStateController.setAppActiveTab({id:i,title:s,origin:p,protocol:f,url:l,host:g,href:m,favIconUrl:c}),Ve.subjectMetadataController.addSubjectMetadata({origin:p,name:s||g||p,iconUrl:c||null,subjectType:"website"}))}catch(e){console.log("Error in tabs.onUpdated listener:",e.message)}return{}}),o.default.windows.onFocusChanged.addListener(async e=>{e!==o.default.windows.WINDOW_ID_NONE&&await dt(e)}),async function(){const e=await(0,re.readCriticalErrorRestoreSession)(o.default),t=undefined;let a=null;(e||t?.simulateBackgroundStateSyncHang||t?.simulateBackgroundInitializationHang)&&(a=await n.persistenceManager.getBackup().catch(()=>null));const r=(0,k.hasVault)(a);if((t?.simulateBackgroundStateSyncHang||t?.simulateBackgroundInitializationHang)&&we&&(we.hasVaultAtStartup=r?Date.now():null),e&&(await(0,re.clearCriticalErrorRestoreSession)(o.default),r)){we&&(we.restoreInProgress=!0);const t={tabId:e.tabId,tabUrl:e.tabUrl};gt(a);try{await qe}catch(e){return void s.default.error("critical-error-restore: initialization failed",e)}return Ve.onboardingController.setFirstTimeFlowType(p.FirstTimeFlowType.restore),void await(0,re.handoffRestoringTabToExtension)(Ie,t)}gt(null)}().catch(e=>{s.default.error("initOrRestoreBackground failed",e)})}}},{package:"$root$",file:"app/scripts/background.js"}]],[12],{});