LavaPack.loadBundle([[999,{"@firebase/util":1004},function(){with(this.scopeTerminator)with(this.globalThis)return function(){"use strict";return function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.Provider=n.ComponentContainer=n.Component=void 0;var r=e("@firebase/util");
/**
 * @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.
 */
n.Component=class{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};const a="[DEFAULT]";
/**
 * @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.
 */class i{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new r.Deferred;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}
/**
 * @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))try{this.getOrInitializeService({instanceIdentifier:a})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=a){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=a){return this.instances.has(e)}getOptions(e=a){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(e)&&t.resolve(r)}return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),a=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;a.add(e),this.onInitCallbacks.set(r,a);const i=this.instances.get(r);return i&&e(i,r),()=>{a.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===a?undefined:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=a){return this.component?this.component.multipleInstances?e:a:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}n.Provider=i;n.ComponentContainer=class{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new i(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}}}},{package:"@metamask/notification-services-controller>firebase>@firebase/app>@firebase/component",file:"node_modules/@firebase/component/dist/esm/index.esm2017.js"}],[13,{"../../shared/constants/app":8458,"../../shared/constants/app-state":8457,"../../shared/constants/defi-referrals":8468,"../../shared/constants/errors":8469,"../../shared/constants/infura-project-id":8474,"../../shared/constants/messages":8479,"../../shared/constants/metametrics":8480,"../../shared/constants/offscreen-communication":8486,"../../shared/constants/onboarding":8487,"../../shared/constants/start-up-errors":8500,"../../shared/constants/ui-initialization":8508,"../../shared/lib/active-tab-domain-metrics":8525,"../../shared/lib/browser-runtime.utils":8542,"../../shared/lib/caip-stream":8545,"../../shared/lib/fetch-with-timeout":8597,"../../shared/lib/get-first-preferred-lang-code":8617,"../../shared/lib/install-attribution":8621,"../../shared/lib/manifestFlags":8623,"../../shared/lib/mv3.utils":8635,"../../shared/lib/object.utils":8638,"../../shared/lib/promise-with-resolvers":8648,"../../shared/lib/selectors/networks":8658,"../../shared/lib/sentry":8664,"../../shared/lib/stores/persistence-manager":8678,"./constants/background":14,"./constants/marketing-site-whitelist":15,"./constants/sentry-state":16,"./constants/snaps":17,"./constants/stream":18,"./controllers/analytics":23,"./first-time-state":67,"./lib/CronjobControllerStorageManager":71,"./lib/approval/utils":78,"./lib/critical-error/critical-error-recovery":93,"./lib/critical-error/critical-error-tab-handoff":94,"./lib/deep-links/deep-link-router":98,"./lib/deep-links/metrics":99,"./lib/defi-referrals/createDefiReferralMiddleware":100,"./lib/ens-ipfs/setup":108,"./lib/extension-lazy-listener/extension-lazy-listener":109,"./lib/getIframeProperties":111,"./lib/getObjStructure":112,"./lib/migrator":118,"./lib/notification-manager":121,"./lib/repair":135,"./lib/safe-reload":152,"./lib/setup-initial-state-hooks":156,"./lib/start-up-errors/start-up-errors":169,"./lib/state-corruption/state-corruption-recovery":170,"./lib/stream-utils":173,"./lib/update-remote-feature-flags":210,"./lib/use-split-state-storage":211,"./lib/util":212,"./metamask-controller":437,"./migrations":685,"./offscreen":686,"./on-update":687,"./platforms/extension":688,"@metamask/base-controller":1452,"@metamask/design-tokens":2121,"@metamask/utils":3992,"extension-port-stream":6551,loglevel:7152,"readable-stream":7629,"webextension-polyfill":8445},function(){with(this.scopeTerminator)with(this.globalThis)return function(){"use strict";return function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.loadStateFromPersistence=it,n.setupController=ut;var r=e("./lib/setup-initial-state-hooks");e("../../shared/constants/infura-project-id");var a=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"),h=e("../../shared/constants/messages"),m=e("../../shared/constants/ui-initialization"),b=e("../../shared/constants/metametrics"),E=e("../../shared/lib/active-tab-domain-metrics"),M=e("../../shared/lib/browser-runtime.utils"),S=e("../../shared/lib/mv3.utils"),w=e("../../shared/lib/object.utils"),C=(e("../../shared/constants/offscreen-communication"),e("../../shared/lib/sentry")),I=e("../../shared/lib/selectors/networks"),T=e("../../shared/lib/caip-stream"),v=pe(e("../../shared/lib/fetch-with-timeout")),y=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")),O=e("../../shared/constants/defi-referrals"),N=e("../../shared/lib/install-attribution"),_=e("../../shared/lib/stores/persistence-manager"),k=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")),F=pe(e("./lib/migrator")),V=e("./lib/update-remote-feature-flags"),j=pe(e("./platforms/extension")),x=e("./constants/sentry-state"),K=ue(e("./lib/notification-manager")),B=ue(e("./metamask-controller")),z=e("./controllers/analytics"),$=pe(e("./lib/getObjStructure")),Y=pe(e("./lib/ens-ipfs/setup")),G=e("./lib/util"),H=e("./offscreen"),W=e("./lib/stream-utils"),q=pe(e("./first-time-state")),J=e("./on-update"),X=e("./constants/marketing-site-whitelist"),Z=e("./constants/stream"),Q=e("./constants/snaps"),ee=e("./lib/extension-lazy-listener/extension-lazy-listener"),te=e("./lib/deep-links/deep-link-router"),ne=e("./lib/deep-links/metrics"),re=e("./lib/safe-reload"),ae=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 n=new WeakMap,r=new WeakMap;return(ue=function(e,t){if(!t&&e&&e.__esModule)return e;var a,i,s={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return s;if(a=t?r:n){if(a.has(e))return a.get(e);a.set(e,s)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(a=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?a(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",he=a.lightTheme.colors.error.default,me=9,be=99,Ee=!1;const Me=null,{safePersist:Se,requestSafeReload:we,evacuate:Ce}=(0,re.getRequestSafeReload)(r.persistenceManager);global.stateHooks.getMostRecentPersistedState=()=>r.persistenceManager.mostRecentRetrievedState,global.stateHooks.getStorageKind=()=>r.persistenceManager.storageKind,global.logEncryptedVault=()=>{r.persistenceManager.logEncryptedVault()};const{sentry:Ie}=global;let Te={...q.default};const ve={[f.ENVIRONMENT_TYPE_POPUP]:!0,[f.ENVIRONMENT_TYPE_NOTIFICATION]:!0,[f.ENVIRONMENT_TYPE_FULLSCREEN]:!0};s.default.setLevel("info",!1);const ye=new j.default,Ae=new K.default,Pe=(0,G.getPlatform)()===f.PLATFORM_FIREFOX;function Oe(e){const t=e.name,n=e.sender?.url?new URL(e.sender.url):null;let r;return r=Pe?Boolean(ve[t]):n?.origin===`chrome-extension://${o.default.runtime.id}`,{processName:t,senderUrl:n,isMetaMaskUIPort:r}}let Ne=0,_e=!1,ke=!1,Re=0,Le=0;const Ue=new Set,De={},Fe={};let Ve;const je={},xe={},Ke={};const Be=new URL("https://metamask.github.io/phishing-warning/v5.1.0/"),ze=Be.toString();let $e,Ye,Ge;function He(){const e=(0,u.withResolvers)();$e=e.promise,Ye=e.resolve,Ge=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,N.getInstallAttribution)();ye.openExtensionInBrowser();await $e,await ft(e)}();else if("update"===e.reason){const{previousVersion:t}=e;if(!t||t===ye.getVersion())return;await $e,(0,J.onUpdate)(Ve,ye,t,we)}}(e)}),He(),o.default?.sidePanel?.setPanelBehavior&&o.default.sidePanel.setPanelBehavior({openPanelOnActionClick:!0}).catch(()=>{});let We,qe,Je,Xe;const Ze=new R.CorruptionHandler,Qe=new k.CriticalErrorHandler,et=async e=>{const{isMetaMaskUIPort:t}=Oe(e);try{e.postMessage({data:{method:m.BACKGROUND_LIVENESS_METHOD},name:"background-liveness"})}catch(e){return void s.default.error("MetaMask - background-liveness check: Failed to message to port",e)}let n;t&&(Qe.registerPortForCriticalError({port:e,repairCallback:()=>(0,ie.requestRepair)(()=>(0,ae.openRestoringTabAndReload)(we))}),n=()=>Qe.removeListenersForPort(e));try{if(await $e,t&&!(0,se.tryPostMessage)(e,m.BACKGROUND_INITIALIZED_METHOD))return;Ee,We(e,n)}catch(a){try{if(Ie?.captureException(a),t)if((0,y.isStateCorruptionError)(a))await Ze.handleStateCorruptionError({port:e,error:a,database:r.persistenceManager,repairCallback:async e=>{He(),(0,_.hasVault)(e)?(await gt(e),Ve.onboardingController.setFirstTimeFlowType(p.FirstTimeFlowType.restore)):(await r.persistenceManager.reset(),await gt(null))}});else{const t=(0,l.isObject)(a)?{message:a.message??"Unknown error",name:a.name??"UnknownError",stack:a.stack,...a.sentryTags&&{sentryTags:a.sentryTags}}:{message:String(a),name:"UnknownError",stack:""};(0,se.tryPostMessage)(e,P.DISPLAY_GENERAL_STARTUP_ERROR,{error:t,currentLocale:Ve?.preferencesController?.state?.currentLocale})}}finally{n?.()}}},tt=()=>{fe.addListener("runtime","onConnect",et)};function nt(){const e=(new Date).toISOString();o.default.storage.session.set({timestamp:e})}async function rt(e){(0,G.initInstallType)();const t=S.isManifestV3?(0,H.createOffscreen)():null;let n=null,a=!1;S.isManifestV3&&(0,H.addOffscreenConnectivityListener)(e=>{if(a&&Ve.connectivityAdapter){const t=e?"online":"offline";Ve.connectivityAdapter.setStatus(t)}else n=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;nt(),setInterval(nt,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=Q.PREINSTALLED_SNAPS_URLS.map(async t=>{const n=await e(t);if(t.pathname.endsWith(".json.gz")){const e=new DecompressionStream("gzip"),t=n.body.pipeThrough(e);return await new Response(t).json()}return await n.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({[b.MetaMetricsUserTrait.StorageKind]:r.persistenceManager.storageKind}),function(e){async function t(e,t){try{const n=await o.default.tabs.get(e);return!(n.url&&n.url.startsWith("https://www.google.com/search")||(await o.default.tabs.update(e,{url:t}),0))}catch(e){return Ie?.captureException(e),!1}}const n=!S.isManifestV3;o.default.webRequest.onBeforeRequest.addListener(r=>{if(r.tabId===o.default.tabs.TAB_ID_NONE)return{};const{completedOnboarding:a}=e.onboardingController.state;if(!a)return{};if(!e.preferencesController.state.usePhishDetect)return{};if(r.initiator&&"null"!==r.initiator&&new URL(r.initiator).host===Be.host)return{};const{hostname:i,href:s,searchParams:l}=new URL(r.url);e.phishingController.maybeUpdateState();const c=e.phishingController.isBlockedRequest(r.url);let d,u;if("main_frame"!==r.type&&"sub_frame"!==r.type||(d=e.phishingController.test(r.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=r.initiator);try{p=new URL(f).hostname}catch{p=i,f=s}const g=new URLSearchParams({hostname:p,href:f}),h=new URL(ze);h.hash=g.toString();const m=h.toString(),E=()=>{Pe||(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.PhishingPageDisplayed).addCategory(b.MetaMetricsEventCategory.Phishing).addProperties({url:f,referrer:{url:f},reason:u,requestDomain:c.result?i:undefined}).build({excludeMetaMetricsId:!0}))};return n?"main_frame"===r.type?(E(),{redirectUrl:m}):(t(r.tabId,m).then(e=>{e&&E()}),{cancel:!0}):(t(r.tabId,m).then(e=>{e&&E()}),{})},{urls:["http://*/*","https://*/*","ws://*/*","wss://*/*"]},n?["blocking"]:[])}(Ve),S.isManifestV3){if(a=!0,null!==n){const e=n?"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(ze);let n,r;t.hash="#extensionStartup",e=window.document.createElement("iframe"),e.setAttribute("src",t.href),e.setAttribute("sandbox","allow-scripts allow-same-origin");const a=new Promise((e,t)=>{n=e,r=t});e.addEventListener("load",n),window.document.body.appendChild(e),setTimeout(()=>r(new at),1e3),await a}catch(e){e instanceof at?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,M.checkForLastErrorAndLog)(),e)).catch(()=>{(0,M.checkForLastErrorAndLog)()});for(const t of e)o.default.tabs.sendMessage(t.id,{name:h.EXTENSION_MESSAGES.READY}).then(()=>{(0,M.checkForLastErrorAndLog)()}).catch(()=>{(0,M.checkForLastErrorAndLog)()})})(),new te.DeepLinkRouter({getExtensionURL:ye.getExtensionURL,getState:Ve.getState.bind(Ve)}).on("navigate",async({url:e,parsed:t})=>{"redirectTo"in t||(0,z.trackEvent)((0,ne.createEvent)({signature:t.signature,url:e}))}).on("error",e=>Ie?.captureException(e)).install()}tt(),o.default.runtime.onConnectExternal.addListener(async(...e)=>{await $e,qe(...e)});class at extends Error{constructor(){super("Timeout failed")}}async function it(e){let t;if(e){t={data:{},meta:{}};for(const n of _.backedUpStateKeys)(0,l.hasProperty)(e,n)&&(t.data[n]=e[n]);(0,l.hasProperty)(e,"meta")&&(0,l.isObject)(e.meta)&&(t.meta=e.meta,"split"===e.meta.storageKind||"data"===e.meta.storageKind?r.persistenceManager.storageKind=e.meta.storageKind:r.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 r.persistenceManager.get({validateVault:e})}const n=new F.default({migrations:D.default,defaultVersion:null});n.on("error",e=>{console.warn(e);const n=(0,$.default)(t);Ie?.captureException(e,{extra:{vaultStructure:n}})});let a=!1;t?.data||t?.meta||(a=!0,t=n.generateInitialState(Te));const{state:i,changedKeys:o}=await n.migrateData(t),c=async n=>{const a=t?.meta?.version,s="number"==typeof a&&a>=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 r.persistenceManager.getBackup();o=e?.AppMetadataController?.firstTimeInfo}catch{}const l=new Error(n);return l.sentryTags={"corruption.preMigrationVersion":String(a??"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(r.persistenceManager.setMetadata(i.meta),s.default.debug("[Split State]: Loaded data from persistence with storageKind '%s'",r.persistenceManager.storageKind),"data"===r.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,r.persistenceManager.setMetadata(i.meta)),s.default.debug("[Split State]: Writing data to persistence with storageKind 'data'"),await r.persistenceManager.set(i.data),t&&(await r.persistenceManager.migrateToSplitState(i.data),i.meta=r.persistenceManager.getMetaData(),i.meta!==undefined&&(delete i.meta.platformSplitStateGradualRolloutAttempted,r.persistenceManager.setMetadata(i.meta)),await r.persistenceManager.persist())}else{if("split"!==r.persistenceManager.storageKind)throw new Error(`MetaMask - persistenceManager has invalid storageKind '${r.persistenceManager.storageKind}'`);if(a)for(const[e,t]of Object.entries(i.data))r.persistenceManager.update(e,t);else for(const e of o)r.persistenceManager.update(e,i.data[e]);await r.persistenceManager.persist()}return s.default.debug("[Split State]: Load complete."),i}function st(e,t,n){const{analyticsId:r}=Ve.getState();if(!(0,G.shouldEmitDappViewedEvent)(r))return;const a=Ve.getPermittedAccounts(e).length;if(0===a)return;const i=Ve.controllerMessenger.call("AccountsController:getState"),s=Object.keys(i.internalAccounts.accounts).length,o=(0,ce.getIframeProperties)({frameId:n,origin:e,mainFrameOrigin:t});(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.DappViewed).addCategory(b.MetaMetricsEventCategory.InpageProvider).addProperties({is_first_visit:!1,number_of_accounts:s,number_of_accounts_connected:a,...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,n=new URL(e.sender.url),{origin:r}=n,a=new URL(e.sender.tab.url),{origin:i}=a,{frameId:s}=e.sender;Object.keys(je).includes(t)||(je[t]=r),t in xe||(xe[t]=i),t in Ke||(Ke[t]=s);const o=Ve.controllerMessenger.call("PermissionController:hasPermissions",r),l="New Tab"!==e.sender.tab.title;o&&l&&st(r,i,s)}function lt(e){const{completedMetaMetricsOnboarding:t,optedIn:n}=Ve.getState();if(!t||!n)return;const r=Ve.appStateController.state.appActiveTab?.origin,a=(0,E.getActiveTabDomainAllowlist)(Ve.remoteFeatureFlagController.state),i=(0,E.getActiveTabDomainForMetrics)(r,a);(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.AppOpened).addCategory(b.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)||_e||Ne>0||Re>0)&&t.includes(e)}const dt=async e=>{if(await $e,Ve)try{const t=e?{active:!0,windowId:e}:{active:!0,currentWindow:!0},n=await o.default.tabs.query(t);if(!n||0===n.length)return;const r=n[0],{id:a,title:i,url:s,favIconUrl:l}=r;if(!s)return void Ve.appStateController.clearAppActiveTab();const{origin:c,protocol:d,host:u,href:p}=new URL(s);if(!(0,G.isWebOrigin)(c))return void Ve.appStateController.clearAppActiveTab();Ve.appStateController.setAppActiveTab({id:a,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,n,a,l,u,p){Ve=new B.default({infuraProjectId:globalThis.INFURA_PROJECT_ID,showUserConfirmation:pt,initState:e,initLangCode:t,platform:ye,notificationManager:Ae,browser:o.default,getRequestAccountTabIds:()=>Fe,getOpenMetamaskTabsIds:()=>De,isFirstMetaMaskControllerSetup:n,currentMigrationVersion:a.version,featureFlags:{},offscreenPromise:l,preinstalledSnaps:u,requestSafeReload:we,cronjobControllerStorageManager:p}),r.persistenceManager.setOnSetFailed(e=>{Ve.appStateController.setStorageWriteErrorType(e)});const h=[],m=Ve.store.getState();for(const t of Object.keys(m)){const n=e[t]||{},r=m[t];if(null===r||"object"!=typeof r){(0,C.captureException)(new Error(`Invalid controller state for '${t}' of type '${null===r?"null":typeof r}'`));continue}const a=Object.keys(r);if(a.length===Object.keys(n).length){for(const e of a)if(r[e]!==n[e]){h.push(t);break}}else h.push(t)}var E;"split"===r.persistenceManager.storageKind?(h.length>0&&(s.default.info(`MetaMaskController state changed during configuration for controllers: ${h.join(", ")}. Persisting updated state.`),h.forEach(e=>{r.persistenceManager.update(e,m[e])}),Se().catch(e=>{s.default.error("Error persisting updated state:",e),Ie?.captureException(e)})),Ve.store.on("stateChange",async({controllerKey:e,newState:t,_oldState:n,_patches:a})=>{r.persistenceManager.update(e,t),_.backedUpStateKeys.includes(e)&&_.backedUpStateKeys.forEach(t=>{if(t===e)return;const n=Ve.store.config[t];if(!n?.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 a=Ve.controllerMessenger.call(`${t}:getState`),i=(0,c.deriveStateFromMetadata)(a,n.metadata,"persist");r.persistenceManager.update(t,i)});try{await Se()}catch(e){s.default.error("Error persisting state change:",e),Ie?.captureException(e)}})):(h.length>0&&(s.default.info(`MetaMaskController state changed during configuration for controllers: ${h.join(", ")}. Persisting updated state.`),Se(m).catch(e=>{s.default.error("Error persisting updated controller state:",e),Ie?.captureException(e)})),Ve.store.on("update",Se)),Ve.store.on("error",e=>{s.default.error("MetaMask controller.store error:",e),Ie?.captureException(e)}),(0,Y.default)({getCurrentChainId:()=>(0,I.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,w.maskObject)(e,x.SENTRY_BACKGROUND_STATE)};const M=()=>Ne>0||Boolean(Object.keys(De).length)||_e||Re>0||!1,v=()=>Ne>0||Re>0,y=()=>_e&&!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 O(){Ue.clear(),Le=0,k()}function N(e,t){return e>t?`${t}+`:String(e)}function k(){const e=R();let t="",n=ge;Le>0&&!y()?(t=N(Le,me),n=he):e>0&&(t=N(e,me));try{const e={text:t},r={color:n};S.isManifestV3?(o.default.action.setBadgeText(e),o.default.action.setBadgeBackgroundColor(r)):(o.default.browserAction.setBadgeText(e),o.default.browserAction.setBadgeBackgroundColor(r))}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}}We=(e,t)=>{if(de.BLOCKED_PORTS.includes(e.name))return;const{processName:n,senderUrl:r,isMetaMaskUIPort:a}=Oe(e);if(a){const r=new d.ExtensionPortStream(e),a=function({chunkSize:e}){(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.PortStreamChunked).addCategory(b.MetaMetricsEventCategory.PortStream).addProperties({chunkSize:e}).build())};e.onDisconnect.addListener(()=>r.off("message-too-large",a)),r.on("message-too-large",a),Ve.isClientOpen=!0,Ve.setupTrustedCommunication(r,e.sender).finally(()=>{t?.()});const o=n===f.ENVIRONMENT_TYPE_SIDEPANEL&&ct(f.ENVIRONMENT_TYPE_SIDEPANEL);if(n!==f.ENVIRONMENT_TYPE_SIDEPANEL&&ct(s=n)&&lt(s),(0,V.updateRemoteFeatureFlags)(Ve),n===f.ENVIRONMENT_TYPE_POPUP&&(O(),Ne+=1,(0,i.finished)(r,()=>{Ne-=1;const e=M();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_POPUP)})),n===f.ENVIRONMENT_TYPE_SIDEPANEL&&(O(),Re+=1,dt().then(()=>{o&&lt(f.ENVIRONMENT_TYPE_SIDEPANEL)}),(0,i.finished)(r,()=>{Re=Math.max(Re-1,0);const e=M();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_SIDEPANEL)})),n===f.ENVIRONMENT_TYPE_NOTIFICATION&&(_e=!0,(0,i.finished)(r,()=>{_e=!1,Le>0&&P(g.AccountOverviewTabKey.Activity),k();const e=M();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_NOTIFICATION)})),n===f.ENVIRONMENT_TYPE_FULLSCREEN){O();const t=e.sender.tab.id;De[t]=!0,(0,i.finished)(r,()=>{delete De[t];const e=M();Ve.isClientOpen=e,A(e,f.ENVIRONMENT_TYPE_FULLSCREEN)})}}else if(r&&r.origin===Be.origin&&r.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,n=new URL(e.sender.url),{origin:r}=n;ot(e),e.onMessage.addListener(e=>{e.data&&e.data.method===f.MESSAGE_TYPE.ETH_REQUEST_ACCOUNTS&&(Fe[r]=t)})}if(r&&X.COOKIE_ID_MARKETING_WHITELIST_ORIGINS.some(e=>e===r.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 n=(0,W.setupMultiplex)(t);n.ignoreStream(Z.METAMASK_EIP_1193_PROVIDER),Xe(n.createStream(Z.METAMASK_CAIP_MULTICHAIN_PROVIDER),e.sender)}}var s},qe=e=>{const t=e.sender?.url;if(t){const{hostname:n}=new URL(t);if(de.BLOCKED_HOSTNAMES.includes(n))return void e.disconnect()}const n=new d.ExtensionPortStream(e,{chunkSize:0});if(!e.sender.id){if(de.BLOCKED_PORTS.includes(e.name))return;ot(e),Xe((0,T.createCaipStream)(n),e.sender)}else Je(n,e.sender)},Je=(e,t)=>{Ve.setupUntrustedCommunicationEip1193({connectionStream:e,sender:t})},Xe=(e,t)=>{Ve.setupUntrustedCommunicationCaip({connectionStream:e,sender:t})},k(),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.DECRYPT_MESSAGE_MANAGER_UPDATE_BADGE,k),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.ENCRYPTION_PUBLIC_KEY_MANAGER_UPDATE_BADGE,k),Ve.signatureController.hub.on(B.METAMASK_CONTROLLER_EVENTS.UPDATE_BADGE,k),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.APP_STATE_UNLOCK_CHANGE,k),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.APPROVAL_STATE_CHANGE,k),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_LIST_UPDATED,k),Ve.controllerMessenger.subscribe(B.METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_MARK_AS_READ,k),Ve.controllerMessenger.subscribe("TransactionController:transactionStatusUpdated",function({transactionMeta:e}){const{status:t,txParams:n,chainId:r}=e??{};if("failed"!==t&&"dropped"!==t)return;const{from:a,nonce:i}=n??{},s=a&&i!==undefined&&r?`${r}:${a.toLowerCase()}:${i}`:undefined;if(s&&Ue.has(s))return;if(v())return;s&&(Ue.size>=be&&Ue.clear(),Ue.add(s));Le+=1,y()||P(g.AccountOverviewTabKey.Activity);k()}),Ae.on(K.NOTIFICATION_MANAGER_EVENTS.POPUP_CLOSED,({automaticallyClosed:e})=>{e?R()>0&&pt():(Ve.signatureController.rejectUnapproved(b.REJECT_NOTIFICATION_CLOSE_SIG),Ve.decryptMessageController.rejectUnapproved(b.REJECT_NOTIFICATION_CLOSE),Ve.encryptionPublicKeyController.rejectUnapproved(b.REJECT_NOTIFICATION_CLOSE),Ve.legacyBackgroundApiService.rejectAllPendingApprovals()),k()})}async function pt(){const e=await ye.getActiveTabs(),t=Boolean(e.find(e=>De[e.id])),n=e.length>0&&e[0].extData&&e[0].extData.indexOf("vivaldi_tab")>-1;if(!ke&&(n||0===Ne)&&!t&&0===Re){ke=!0;try{const e=Ve.appStateController.getCurrentPopupId();await Ae.showPopup(e=>Ve.appStateController.setCurrentPopupId(e),e)}finally{ke=!1}}}const ft=async e=>{const{deferredDeepLink:t,traits:n}=await e;Ve.metaMetricsController.updateTraits({[b.MetaMetricsUserTrait.InstallDateExt]:(new Date).toISOString().split("T")[0],...n});const r={};t&&(Ve.appStateController.setDeferredDeepLink(t),r.install_source="deeplink",r.deeplink_path=t.referringLink);const a={category:b.MetaMetricsEventCategory.App,event:b.MetaMetricsEventName.AppInstalled,properties:r},{completedMetaMetricsOnboarding:i,optedIn:s,analyticsId:o}=Ve.getState();!0===i&&!1===s||(!0===i&&!0===s&&o?(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.AppInstalled).addCategory(b.MetaMetricsEventCategory.App).addProperties(r).build()):Ve.metaMetricsController.addEventBeforeMetricsOptIn(a))};o.default.runtime.onUpdateAvailable.addListener(async function(e){await $e,s.default.info("An update is available",e?.version),Ve.appStateController.setPendingExtensionVersion(e?.version??null)});(async()=>{if(o.default?.sidePanel)try{await $e,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,n=je[t],r=xe[t];n&&Ve.permissionController.state.subjects[n]!==undefined&&st(n,r,Ke[t]);const a=(0,O.getPartnerByOrigin)(r);a&&Ve.permissionController.state.subjects[r]!==undefined&&Ve.handleDefiReferral(a,t,le.ReferralTriggerType.OnNavigateConnectedTab).catch(e=>{s.default.error(`Failed to handle ${a.name} referral after navigation to connected tab: `,e)})}});try{await rt(e),r.persistenceManager.cleanUpMostRecentRetrievedState(),s.default.info("MetaMask initialization complete."),Ye()}catch(e){s.default.error(e),Ge(e)}}(async()=>{await dt()})(),o.default.tabs.onActivated.addListener(async({tabId:e})=>{if(await $e,!Ve)return{};try{const t=await o.default.tabs.get(e),{id:n,title:r,url:a,favIconUrl:i}=t;if(!a)return Ve.appStateController.clearAppActiveTab(),{};const{origin:s,protocol:l,host:c,href:d}=new URL(a);if(!(0,G.isWebOrigin)(s))return Ve.appStateController.clearAppActiveTab(),{};Ve.appStateController.setAppActiveTab({id:n,title:r,origin:s,protocol:l,url:a,host:c,href:d,favIconUrl:i}),Ve.subjectMetadataController.addSubjectMetadata({origin:s,name:r||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,n)=>{if(await $e,!Ve)return{};const r=t.url!==undefined,a="complete"===t.status;if(!r&&!a)return{};try{const t=n||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:h}=new URL(l);if(!p||"null"===p||p.startsWith("chrome-extension://")||p.startsWith("moz-extension://"))return u&&Ve.appStateController.clearAppActiveTab(),{};let m=!1;try{m=(await o.default.tabs.query({active:!0,currentWindow:!0})).some(e=>e.id===i)}catch(e){m=u}(r||a)&&m&&(Ve.appStateController.setAppActiveTab({id:i,title:s,origin:p,protocol:f,url:l,host:g,href:h,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,ae.readCriticalErrorRestoreSession)(o.default),t=undefined;let n=null;(e||t?.simulateBackgroundStateSyncHang||t?.simulateBackgroundInitializationHang)&&(n=await r.persistenceManager.getBackup().catch(()=>null));const a=(0,_.hasVault)(n);if((t?.simulateBackgroundStateSyncHang||t?.simulateBackgroundInitializationHang)&&Me&&(Me.hasVaultAtStartup=a?Date.now():null),e&&(await(0,ae.clearCriticalErrorRestoreSession)(o.default),a)){Me&&(Me.restoreInProgress=!0);const t={tabId:e.tabId,tabUrl:e.tabUrl};gt(n);try{await $e}catch(e){return void s.default.error("critical-error-restore: initialization failed",e)}return Ve.onboardingController.setFirstTimeFlowType(p.FirstTimeFlowType.restore),void await(0,ae.handoffRestoringTabToExtension)(ye,t)}gt(null)}().catch(e=>{s.default.error("initOrRestoreBackground failed",e)})}}},{package:"$root$",file:"app/scripts/background.js"}]],[13],{});