LavaPack.loadBundle([[99,{"../../../../shared/constants/defi-referrals":8571,"../../../../shared/constants/time":8608,"@metamask/json-rpc-engine":2690,loglevel:7255},function(){with(this.scopeTerminator)with(this.globalThis)return function(){"use strict";return function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.ReferralTriggerType=void 0,n.createDefiReferralMiddleware=function(e){return(0,r.createAsyncMiddleware)(async(t,n,a)=>{if(await a(),!function(e){return Boolean(e.origin)&&Boolean(e.tabId)}(t))return;const r=(0,o.getPartnerByOrigin)(t.origin);if(!r)return;const s=`${t.origin}:${t.tabId}`;if(d(t.method)||u(t.method)){let a=!1;if(Array.isArray(n.result)&&n.result.length>0)if(d(t.method)){a=n.result.some(e=>"eth_accounts"===e?.parentCapability)}else a=n.result.every(e=>"string"==typeof e);return void(a&&(f(r.connectionFlow)?(g??(g=function(){const e=new Map,t=setInterval(()=>{const n=Date.now()-c;for(const[t,a]of e.entries())a<=n&&e.delete(t);0===e.size&&(clearInterval(t),e.clear(),g=null)},c);return e}()),g).set(s,Date.now()):e(r,t.tabId,l.NewConnection).catch(e=>{i.default.error(`Failed to handle ${r.name} referral after permissions grant: `,e)})))}f(r.connectionFlow)&&p(t.method)&&"string"==typeof n.result&&g?.has(s)&&(g.delete(s),e(r,t.tabId,l.NewConnection).catch(e=>{i.default.error(`Failed to handle ${r.name} referral after signature grant: `,e)}))})};var a,r=e("@metamask/json-rpc-engine"),i=(a=e("loglevel"))&&a.__esModule?a:{default:a},s=e("../../../../shared/constants/time"),o=e("../../../../shared/constants/defi-referrals");const c=10*s.SECOND;let l=n.ReferralTriggerType=function(e){return e.NewConnection="new_connection",e.OnNavigateConnectedTab="on_navigate_connected_tab",e.PermittedAccountAdded="permitted_account_added",e}({});const d=e=>"wallet_requestPermissions"===e,u=e=>"eth_requestAccounts"===e,p=e=>"eth_signTypedData_v4"===e,f=e=>"permissions_then_signature"===e;let g=null}}},{package:"$root$",file:"app/scripts/lib/defi-referrals/createDefiReferralMiddleware.ts"}],[997,{"@firebase/component":998,"@firebase/logger":1e3,"@firebase/util":1003,idb:6935},function(){with(this.scopeTerminator)with(this.globalThis)return function(){"use strict";return function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"FirebaseError",{enumerable:!0,get:function(){return i.FirebaseError}}),n._DEFAULT_ENTRY_NAME=n.SDK_VERSION=void 0,n._addComponent=V,n._addOrOverwriteComponent=function(e,t){e.container.addOrOverwriteComponent(t)},n._apps=void 0,n._clearComponents=function(){B.clear()}
/**
 * @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._components=void 0,n._getProvider=K,n._isFirebaseApp=H,n._isFirebaseServerApp=function(e){return e.settings!==undefined},n._registerComponent=z,n._removeServiceInstance=function(e,t,n=U){K(e,t).clearInstance(n)},n._serverApps=void 0,n.deleteApp=X,n.getApp=function(e=U){const t=x.get(e);if(!t&&e===U&&(0,i.getDefaultAppConfig)())return J();if(!t)throw Y.create("no-app",{appName:e});return t},n.getApps=function(){return Array.from(x.values())},n.initializeApp=J,n.initializeServerApp=function(e,t){if((0,i.isBrowser)()&&!(0,i.isWebWorker)())throw Y.create("invalid-server-app-environment");t.automaticDataCollectionEnabled===undefined&&(t.automaticDataCollectionEnabled=!1);let n;n=H(e)?e.options:e;const r=Object.assign(Object.assign({},t),n);r.releaseOnDeref!==undefined&&delete r.releaseOnDeref;if(t.releaseOnDeref!==undefined&&"undefined"==typeof FinalizationRegistry)throw Y.create("finalization-registry-not-supported",{});const s=""+(c=JSON.stringify(r),[...c].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0)),o=$.get(s);var c;if(o)return o.incRefCount(t.releaseOnDeref),o;const l=new a.ComponentContainer(s);for(const e of B.values())l.addComponent(e);const d=new W(n,t,s,l);return $.set(s,d),d},n.onLog=function(e,t){if(null!==e&&"function"!=typeof e)throw Y.create("invalid-log-argument");(0,r.setUserLogHandler)(e,t)},n.registerVersion=Z,n.setLogLevel=function(e){(0,r.setLogLevel)(e)}
/**
 * @license
 * Copyright 2021 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.
 */;var a=e("@firebase/component"),r=e("@firebase/logger"),i=e("@firebase/util"),s=e("idb");
/**
 * @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 o{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null}).filter(e=>e).join(" ")}}const c="@firebase/app",l="0.10.18",d=new r.Logger("@firebase/app"),u="@firebase/app-compat",p="@firebase/analytics-compat",f="@firebase/analytics",g="@firebase/app-check-compat",h="@firebase/app-check",m="@firebase/auth",b="@firebase/auth-compat",w="@firebase/database",E="@firebase/data-connect",v="@firebase/database-compat",C="@firebase/functions",y="@firebase/functions-compat",S="@firebase/installations",I="@firebase/installations-compat",_="@firebase/messaging",M="@firebase/messaging-compat",T="@firebase/performance",A="@firebase/performance-compat",P="@firebase/remote-config",O="@firebase/remote-config-compat",N="@firebase/storage",k="@firebase/storage-compat",D="@firebase/firestore",R="@firebase/vertexai",L="@firebase/firestore-compat",j="firebase",U=n._DEFAULT_ENTRY_NAME="[DEFAULT]",F={[c]:"fire-core",[u]:"fire-core-compat",[f]:"fire-analytics",[p]:"fire-analytics-compat",[h]:"fire-app-check",[g]:"fire-app-check-compat",[m]:"fire-auth",[b]:"fire-auth-compat",[w]:"fire-rtdb",[E]:"fire-data-connect",[v]:"fire-rtdb-compat",[C]:"fire-fn",[y]:"fire-fn-compat",[S]:"fire-iid",[I]:"fire-iid-compat",[_]:"fire-fcm",[M]:"fire-fcm-compat",[T]:"fire-perf",[A]:"fire-perf-compat",[P]:"fire-rc",[O]:"fire-rc-compat",[N]:"fire-gcs",[k]:"fire-gcs-compat",[D]:"fire-fst",[L]:"fire-fst-compat",[R]:"fire-vertex","fire-js":"fire-js",[j]:"fire-js-all"},x=n._apps=new Map,$=n._serverApps=new Map,B=n._components=new Map;function V(e,t){try{e.container.addComponent(t)}catch(n){d.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function z(e){const t=e.name;if(B.has(t))return d.debug(`There were multiple attempts to register component ${t}.`),!1;B.set(t,e);for(const t of x.values())V(t,e);for(const t of $.values())V(t,e);return!0}function K(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function H(e){return e.options!==undefined}const q={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},Y=new i.ErrorFactory("app","Firebase",q);
/**
 * @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 G{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new a.Component("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw Y.create("app-deleted",{appName:this._name})}}
/**
 * @license
 * Copyright 2023 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 W extends G{constructor(e,t,n,a){const r=t.automaticDataCollectionEnabled!==undefined&&t.automaticDataCollectionEnabled,i={name:n,automaticDataCollectionEnabled:r};if(e.apiKey!==undefined)super(e,i,a);else{super(e.options,i,a)}this._serverConfig=Object.assign({automaticDataCollectionEnabled:r},t),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry(()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=undefined,t.releaseOnDeref=undefined,Z(c,l,"serverapp")}toJSON(){return undefined}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,e!==undefined&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){X(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw Y.create("server-app-deleted")}}
/**
 * @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.SDK_VERSION="11.2.0";function J(e,t={}){let n=e;if("object"!=typeof t){t={name:t}}const r=Object.assign({name:U,automaticDataCollectionEnabled:!1},t),s=r.name;if("string"!=typeof s||!s)throw Y.create("bad-app-name",{appName:String(s)});if(n||(n=(0,i.getDefaultAppConfig)()),!n)throw Y.create("no-options");const o=x.get(s);if(o){if((0,i.deepEqual)(n,o.options)&&(0,i.deepEqual)(r,o.config))return o;throw Y.create("duplicate-app",{appName:s})}const c=new a.ComponentContainer(s);for(const e of B.values())c.addComponent(e);const l=new G(n,r,c);return x.set(s,l),l}async function X(e){let t=!1;const n=e.name;if(x.has(n))t=!0,x.delete(n);else if($.has(n)){e.decRefCount()<=0&&($.delete(n),t=!0)}t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function Z(e,t,n){var r;let i=null!==(r=F[e])&&void 0!==r?r:e;n&&(i+=`-${n}`);const s=i.match(/\s|\//),o=t.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${t}":`];return s&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void d.warn(e.join(" "))}z(new a.Component(`${i}-version`,()=>({library:i,version:t}),"VERSION"))}const Q="firebase-heartbeat-store";let ee=null;function te(){return ee||(ee=(0,s.openDB)("firebase-heartbeat-database",1,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Q)}catch(e){console.warn(e)}}}).catch(e=>{throw Y.create("idb-open",{originalErrorMessage:e.message})})),ee}async function ne(e,t){try{const n=(await te()).transaction(Q,"readwrite"),a=n.objectStore(Q);await a.put(t,ae(e)),await n.done}catch(e){if(e instanceof i.FirebaseError)d.warn(e.message);else{const t=Y.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});d.warn(t.message)}}}function ae(e){return`${e.name}!${e.options.appId}`}
/**
 * @license
 * Copyright 2021 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 re{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new se(t),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){var e,t;try{const n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),a=ie();if(null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)&&(this._heartbeatsCache=await this._heartbeatsCachePromise,null==(null===(t=this._heartbeatsCache)||void 0===t?void 0:t.heartbeats)))return;if(this._heartbeatsCache.lastSentHeartbeatDate===a||this._heartbeatsCache.heartbeats.some(e=>e.date===a))return;return this._heartbeatsCache.heartbeats.push({date:a,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}catch(e){d.warn(e)}}async getHeartbeatsHeader(){var e;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const t=ie(),{heartbeatsToSend:n,unsentEntries:a}=function(e,t=1024){const n=[];let a=e.slice();for(const r of e){const e=n.find(e=>e.agent===r.agent);if(e){if(e.dates.push(r.date),oe(n)>t){e.dates.pop();break}}else if(n.push({agent:r.agent,dates:[r.date]}),oe(n)>t){n.pop();break}a=a.slice(1)}return{heartbeatsToSend:n,unsentEntries:a}}(this._heartbeatsCache.heartbeats),r=(0,i.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,a.length>0?(this._heartbeatsCache.heartbeats=a,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}catch(e){return d.warn(e),""}}}function ie(){return(new Date).toISOString().substring(0,10)}class se{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!(0,i.isIndexedDBAvailable)()&&(0,i.validateIndexedDBOpenable)().then(()=>!0).catch(()=>!1)}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=(await te()).transaction(Q),n=await t.objectStore(Q).get(ae(e));return await t.done,n}catch(e){if(e instanceof i.FirebaseError)d.warn(e.message);else{const t=Y.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});d.warn(t.message)}}}(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return ne(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return ne(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function oe(e){return(0,i.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:e})).length}
/**
 * @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.
 */var ce;ce="",z(new a.Component("platform-logger",e=>new o(e),"PRIVATE")),z(new a.Component("heartbeat",e=>new re(e),"PRIVATE")),Z(c,l,ce),Z(c,l,"esm2017"),Z("fire-js","")}}},{package:"@metamask/notification-services-controller>firebase>@firebase/app",file:"node_modules/@firebase/app/dist/esm/index.esm2017.js"}],[998,{"@firebase/util":1003},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 a=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 r="[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 a.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),a=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(a)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(a)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:r})}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=r){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=r){return this.instances.has(e)}getOptions(e=r){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 a=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(e)&&t.resolve(a)}return a}onInit(e,t){var n;const a=this.normalizeInstanceIdentifier(t),r=null!==(n=this.onInitCallbacks.get(a))&&void 0!==n?n:new Set;r.add(e),this.onInitCallbacks.set(a,r);const i=this.instances.get(a);return i&&e(i,a),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const a of n)try{a(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:(a=e,a===r?undefined:a),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 a;return n||null}normalizeInstanceIdentifier(e=r){return this.component?this.component.multipleInstances?e:r: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"}],[999,{"@firebase/app":997,"@firebase/component":998,"@firebase/util":1003,idb:6935},function(){with(this.scopeTerminator)with(this.globalThis)return function(){"use strict";return function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.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,n=await B(t,e=>e&&0===e.registrationStatus?undefined:e);if(n){if(1===n.registrationStatus)throw h.create("delete-pending-registration");if(2===n.registrationStatus){if(!navigator.onLine)throw h.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 n=function(e,{fid:t}){return`${b(e)}/${t}`}(e,t),a=C(e,t),r={method:"DELETE",headers:a},i=await y(()=>fetch(n,r));if(!i.ok)throw await E("Delete Installation",i)}(t,n),await $(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.
 */,n.getId=J,n.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,a.getApp)()){return(0,a._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.
 */,n.getToken=X,n.onIdChange=function(e,t){const{appConfig:n}=e;return function(e,t){k();const n=T(e);let a=A.get(n);a||(a=new Set,A.set(n,a));a.add(t)}(n,t),()=>{!function(e,t){const n=T(e),a=A.get(n);if(!a)return;a.delete(t),0===a.size&&A.delete(n);D()}(n,t)}};var a=e("@firebase/app"),r=e("@firebase/component"),i=e("@firebase/util"),s=e("idb");const o="@firebase/installations",c="0.6.12",l=1e4,d=`w:${c}`,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."},h=new i.ErrorFactory("installations","Installations",g);function m(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 b({projectId:e}){return`${p}/projects/${e}/installations`}function w(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function E(e,t){const n=(await t.json()).error;return h.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function v({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function C(e,{refreshToken:t}){const n=v(e);return n.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)),n}async function y(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 S(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 I=/^[cdef][\w-]{21}$/,_="";function M(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function(e){const t=(n=e,btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_"));var n;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 I.test(t)?t:_}catch(e){return _}}function T(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 A=new Map;function P(e,t){const n=T(e);O(n,t),function(e,t){const n=k();n&&n.postMessage({key:e,fid:t});D()}(n,t)}function O(e,t){const n=A.get(e);if(n)for(const e of n)e(t)}let N=null;function k(){return!N&&"BroadcastChannel"in self&&(N=new BroadcastChannel("[Firebase] FID Change"),N.onmessage=e=>{O(e.data.key,e.data.fid)}),N}function D(){0===A.size&&N&&(N.close(),N=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 R="firebase-installations-database",L=1,j="firebase-installations-store";let U=null;function F(){return U||(U=(0,s.openDB)(R,L,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(j)}})),U}async function x(e,t){const n=T(e),a=(await F()).transaction(j,"readwrite"),r=a.objectStore(j),i=await r.get(n);return await r.put(t,n),await a.done,i&&i.fid===t.fid||P(e,t.fid),t}async function $(e){const t=T(e),n=(await F()).transaction(j,"readwrite");await n.objectStore(j).delete(t),await n.done}async function B(e,t){const n=T(e),a=(await F()).transaction(j,"readwrite"),r=a.objectStore(j),i=await r.get(n),s=t(i);return s===undefined?await r.delete(n):await r.put(s,n),await a.done,!s||i&&i.fid===s.fid||P(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 V(e){let t;const n=await B(e.appConfig,n=>{const a=function(e){const t=e||{fid:M(),registrationStatus:0};return H(t)}(n),r=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(h.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},a=async function(e,t){try{const n=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const a=b(e),r=v(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&r.append("x-firebase-client",e)}const s={fid:n,authVersion:u,appId:e.appId,sdkVersion:d},o={method:"POST",headers:r,body:JSON.stringify(s)},c=await y(()=>fetch(a,o));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:w(e.authToken)}}throw await E("Create Installation",c)}(e,t);return x(e.appConfig,n)}catch(n){throw m(n)&&409===n.customData.serverCode?await $(e.appConfig):await x(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:a}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:z(e)}:{installationEntry:t}}(e,a);return t=r.registrationPromise,r.installationEntry});return n.fid===_?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function z(e){let t=await K(e.appConfig);for(;1===t.registrationStatus;)await S(100),t=await K(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await V(e);return n||t}return t}function K(e){return B(e,e=>{if(!e)throw h.create("installation-not-found");return H(e)})}function H(e){return 1===(t=e).registrationStatus&&t.registrationTime+l<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 q({appConfig:e,heartbeatServiceProvider:t},n){const a=function(e,{fid:t}){return`${b(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,n),r=C(e,n),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)},c=await y(()=>fetch(a,o));if(c.ok){return w(await c.json())}throw await E("Generate Auth Token",c)}async function Y(e,t=!1){let n;const a=await B(e.appConfig,a=>{if(!W(a))throw h.create("not-registered");const r=a.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 a;if(1===r.requestStatus)return n=async function(e,t){let n=await G(e.appConfig);for(;1===n.authToken.requestStatus;)await S(100),n=await G(e.appConfig);const a=n.authToken;return 0===a.requestStatus?Y(e,t):a}(e,t),a;{if(!navigator.onLine)throw h.create("app-offline");const t=function(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(a);return n=async function(e,t){try{const n=await q(e,t),a=Object.assign(Object.assign({},t),{authToken:n});return await x(e.appConfig,a),n}catch(n){if(!m(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await x(e.appConfig,n)}else await $(e.appConfig);throw n}}(e,t),t}});return n?await n:a.authToken}function G(e){return B(e,e=>{if(!W(e))throw h.create("not-registered");const t=e.authToken;return 1===(n=t).requestStatus&&n.requestTime+l<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;var n;
/**
 * @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:n,registrationPromise:a}=await V(t);return a?a.catch(console.error):Y(t).catch(console.error),n.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 n=e;await async function(e){const{registrationPromise:t}=await V(e);t&&await t}(n);return(await Y(n,t)).token}function Z(e){return h.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 Q="installations",ee=e=>{const t=e.getProvider("app").getImmediate(),n=function(e){if(!e||!e.options)throw Z("App Configuration");if(!e.name)throw Z("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw Z(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:(0,a._getProvider)(t,"heartbeat"),_delete:()=>Promise.resolve()}},te=e=>{const t=e.getProvider("app").getImmediate(),n=(0,a._getProvider)(t,Q).getImmediate();return{getId:()=>J(n),getToken:e=>X(n,e)}};(0,a._registerComponent)(new r.Component(Q,ee,"PUBLIC")),(0,a._registerComponent)(new r.Component("installations-internal",te,"PRIVATE")),(0,a.registerVersion)(o,c),(0,a.registerVersion)(o,c,"esm2017")}}},{package:"@metamask/notification-services-controller>firebase>@firebase/installations",file:"node_modules/@firebase/installations/dist/esm/index.esm2017.js"}],[12,{"../../shared/constants/app":8561,"../../shared/constants/app-state":8560,"../../shared/constants/defi-referrals":8571,"../../shared/constants/errors":8572,"../../shared/constants/infura-project-id":8577,"../../shared/constants/messages":8582,"../../shared/constants/metametrics":8583,"../../shared/constants/offscreen-communication":8589,"../../shared/constants/onboarding":8590,"../../shared/constants/start-up-errors":8603,"../../shared/constants/ui-initialization":8611,"../../shared/lib/active-tab-domain-metrics":8628,"../../shared/lib/browser-runtime.utils":8645,"../../shared/lib/caip-stream":8648,"../../shared/lib/fetch-with-timeout":8700,"../../shared/lib/get-first-preferred-lang-code":8720,"../../shared/lib/install-attribution":8724,"../../shared/lib/manifestFlags":8726,"../../shared/lib/mv3.utils":8738,"../../shared/lib/object.utils":8741,"../../shared/lib/promise-with-resolvers":8751,"../../shared/lib/selectors/networks":8761,"../../shared/lib/sentry":8767,"../../shared/lib/stores/persistence-manager":8781,"./constants/background":13,"./constants/marketing-site-whitelist":14,"./constants/sentry-state":15,"./constants/snaps":16,"./constants/stream":17,"./controllers/analytics":22,"./first-time-state":66,"./lib/CronjobControllerStorageManager":70,"./lib/approval/utils":77,"./lib/critical-error/critical-error-recovery":92,"./lib/critical-error/critical-error-tab-handoff":93,"./lib/deep-links/deep-link-router":97,"./lib/deep-links/metrics":98,"./lib/defi-referrals/createDefiReferralMiddleware":99,"./lib/ens-ipfs/setup":107,"./lib/extension-lazy-listener/extension-lazy-listener":108,"./lib/getIframeProperties":110,"./lib/getObjStructure":111,"./lib/migrator":117,"./lib/notification-manager":120,"./lib/repair":134,"./lib/safe-reload":151,"./lib/setup-initial-state-hooks":155,"./lib/start-up-errors/start-up-errors":168,"./lib/state-corruption/state-corruption-recovery":169,"./lib/stream-utils":172,"./lib/update-remote-feature-flags":209,"./lib/use-split-state-storage":210,"./lib/util":211,"./metamask-controller":436,"./migrations":684,"./offscreen":685,"./on-update":686,"./platforms/extension":687,"@metamask/base-controller":1515,"@metamask/design-tokens":2181,"@metamask/utils":4072,"extension-port-stream":6654,loglevel:7255,"readable-stream":7732,"webextension-polyfill":8548},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 a=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")),c=e("@metamask/utils"),l=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"),w=e("../../shared/lib/active-tab-domain-metrics"),E=e("../../shared/lib/browser-runtime.utils"),v=e("../../shared/lib/mv3.utils"),C=e("../../shared/lib/object.utils"),y=(e("../../shared/constants/offscreen-communication"),e("../../shared/lib/sentry")),S=e("../../shared/lib/selectors/networks"),I=e("../../shared/lib/caip-stream"),_=pe(e("../../shared/lib/fetch-with-timeout")),M=e("../../shared/constants/errors"),T=pe(e("../../shared/lib/get-first-preferred-lang-code")),A=(e("../../shared/lib/manifestFlags"),e("../../shared/constants/start-up-errors")),P=e("../../shared/constants/defi-referrals"),O=e("../../shared/lib/install-attribution"),N=e("../../shared/lib/stores/persistence-manager"),k=e("./lib/critical-error/critical-error-recovery"),D=e("./lib/state-corruption/state-corruption-recovery"),R=e("./lib/approval/utils"),L=e("./lib/use-split-state-storage"),j=pe(e("./migrations")),U=pe(e("./lib/migrator")),F=e("./lib/update-remote-feature-flags"),x=pe(e("./platforms/extension")),$=e("./constants/sentry-state"),B=ue(e("./lib/notification-manager")),V=ue(e("./metamask-controller")),z=e("./controllers/analytics"),K=pe(e("./lib/getObjStructure")),H=pe(e("./lib/ens-ipfs/setup")),q=e("./lib/util"),Y=e("./offscreen"),G=e("./lib/stream-utils"),W=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"),ae=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"),ce=e("./lib/defi-referrals/createDefiReferralMiddleware"),le=e("./lib/getIframeProperties"),de=e("./constants/background");function ue(e,t){if("function"==typeof WeakMap)var n=new WeakMap,a=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?a:n){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",he=r.lightTheme.colors.error.default,me=9,be=99,we=!1;const Ee=null,{safePersist:ve,requestSafeReload:Ce,evacuate:ye}=(0,ae.getRequestSafeReload)(a.persistenceManager);global.stateHooks.getMostRecentPersistedState=()=>a.persistenceManager.mostRecentRetrievedState,global.stateHooks.getStorageKind=()=>a.persistenceManager.storageKind,global.logEncryptedVault=()=>{a.persistenceManager.logEncryptedVault()};const{sentry:Se}=global;let Ie={...W.default};const _e={[f.ENVIRONMENT_TYPE_POPUP]:!0,[f.ENVIRONMENT_TYPE_NOTIFICATION]:!0,[f.ENVIRONMENT_TYPE_FULLSCREEN]:!0};s.default.setLevel("info",!1);const Me=new x.default,Te=new B.default,Ae=(0,q.getPlatform)()===f.PLATFORM_FIREFOX;function Pe(e){const t=e.name,n=e.sender?.url?new URL(e.sender.url):null;let a;return a=Ae?Boolean(_e[t]):n?.origin===`chrome-extension://${o.default.runtime.id}`,{processName:t,senderUrl:n,isMetaMaskUIPort:a}}let Oe=0,Ne=!1,ke=!1,De=0,Re=0;const Le=new Set,je={},Ue={};let Fe;const xe={},$e={},Be={};const Ve=new URL("https://metamask.github.io/phishing-warning/v5.1.0/"),ze=Ve.toString();let Ke,He,qe;function Ye(){const e=(0,u.withResolvers)();Ke=e.promise,He=e.resolve,qe=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,O.getInstallAttribution)();Me.openExtensionInBrowser();await Ke,await ft(e)}();else if("update"===e.reason){const{previousVersion:t}=e;if(!t||t===Me.getVersion())return;await Ke,(0,J.onUpdate)(Fe,Me,t,Ce)}}(e)}),Ye(),o.default?.sidePanel?.setPanelBehavior&&o.default.sidePanel.setPanelBehavior({openPanelOnActionClick:!0}).catch(()=>{});let Ge,We,Je,Xe;const Ze=new D.CorruptionHandler,Qe=new k.CriticalErrorHandler,et=async e=>{const{isMetaMaskUIPort:t}=Pe(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,re.openRestoringTabAndReload)(Ce))}),n=()=>Qe.removeListenersForPort(e));try{if(await Ke,t&&!(0,se.tryPostMessage)(e,m.BACKGROUND_INITIALIZED_METHOD))return;we,Ge(e,n)}catch(r){try{if(Se?.captureException(r),t)if((0,M.isStateCorruptionError)(r))await Ze.handleStateCorruptionError({port:e,error:r,database:a.persistenceManager,repairCallback:async e=>{Ye(),(0,N.hasVault)(e)?(await gt(e),Fe.onboardingController.setFirstTimeFlowType(p.FirstTimeFlowType.restore)):(await a.persistenceManager.reset(),await gt(null))}});else{const t=(0,c.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,A.DISPLAY_GENERAL_STARTUP_ERROR,{error:t,currentLocale:Fe?.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 at(e){(0,q.initInstallType)();const t=v.isManifestV3?(0,Y.createOffscreen)():null;let n=null,r=!1;v.isManifestV3&&(0,Y.addOffscreenConnectivityListener)(e=>{if(r&&Fe.connectivityAdapter){const t=e?"online":"offline";Fe.connectivityAdapter.setStatus(t)}else n=e});const i=await it(e),s=i.data,c=await(0,T.default)();let l;if(v.isManifestV3){if(!1!==s.PreferencesController?.enableMV3TimestampSave){const e=2e3;nt(),setInterval(nt,e)}const e=await o.default.storage.session.get(["isFirstMetaMaskControllerSetup"]);l=e?.isFirstMetaMaskControllerSetup===undefined,await o.default.storage.session.set({isFirstMetaMaskControllerSetup:l})}const d=await async function(){const e=(0,_.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,c,l,i.meta,t,d,u),Fe.metaMetricsController.updateTraits({[b.MetaMetricsUserTrait.StorageKind]:a.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 Se?.captureException(e),!1}}const n=!v.isManifestV3;o.default.webRequest.onBeforeRequest.addListener(a=>{if(a.tabId===o.default.tabs.TAB_ID_NONE)return{};const{completedOnboarding:r}=e.onboardingController.state;if(!r)return{};if(!e.preferencesController.state.usePhishDetect)return{};if(a.initiator&&"null"!==a.initiator&&new URL(a.initiator).host===Ve.host)return{};const{hostname:i,href:s,searchParams:c}=new URL(a.url);e.phishingController.maybeUpdateState();const l=e.phishingController.isBlockedRequest(a.url);let d,u;if("main_frame"!==a.type&&"sub_frame"!==a.type||(d=e.phishingController.test(a.url)),!d?.result&&!l.result)return{};let p,f=s;d?.result&&l.result?u=`${d.type} and ${l.type}`:d?.result?u=d.type:(u=l.type,f=a.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(),w=()=>{Ae||(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.PhishingPageDisplayed).addCategory(b.MetaMetricsEventCategory.Phishing).addProperties({url:f,referrer:{url:f},reason:u,requestDomain:l.result?i:undefined}).build({excludeMetaMetricsId:!0}))};return n?"main_frame"===a.type?(w(),{redirectUrl:m}):(t(a.tabId,m).then(e=>{e&&w()}),{cancel:!0}):(t(a.tabId,m).then(e=>{e&&w()}),{})},{urls:["http://*/*","https://*/*","ws://*/*","wss://*/*"]},n?["blocking"]:[])}(Fe),v.isManifestV3){if(r=!0,null!==n){const e=n?"online":"offline";Fe.connectivityAdapter.setStatus(e)}}else{const e=e=>{const t=e?"online":"offline";Fe.connectivityAdapter.setStatus(t)};e(globalThis.navigator.onLine),globalThis.addEventListener("online",()=>e(!0)),globalThis.addEventListener("offline",()=>e(!1))}v.isManifestV3||await async function(){let e;try{const t=new URL(ze);let n,a;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)=>{n=e,a=t});e.addEventListener("load",n),window.document.body.appendChild(e),setTimeout(()=>a(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,E.checkForLastErrorAndLog)(),e)).catch(()=>{(0,E.checkForLastErrorAndLog)()});for(const t of e)o.default.tabs.sendMessage(t.id,{name:h.EXTENSION_MESSAGES.READY}).then(()=>{(0,E.checkForLastErrorAndLog)()}).catch(()=>{(0,E.checkForLastErrorAndLog)()})})(),new te.DeepLinkRouter({getExtensionURL:Me.getExtensionURL,getState:Fe.getState.bind(Fe)}).on("navigate",async({url:e,parsed:t})=>{"redirectTo"in t||(0,z.trackEvent)((0,ne.createEvent)({signature:t.signature,url:e}))}).on("error",e=>Se?.captureException(e)).install()}tt(),o.default.runtime.onConnectExternal.addListener(async(...e)=>{await Ke,We(...e)});class rt extends Error{constructor(){super("Timeout failed")}}async function it(e){let t;if(e){t={data:{},meta:{}};for(const n of N.backedUpStateKeys)(0,c.hasProperty)(e,n)&&(t.data[n]=e[n]);(0,c.hasProperty)(e,"meta")&&(0,c.isObject)(e.meta)&&(t.meta=e.meta,"split"===e.meta.storageKind||"data"===e.meta.storageKind?a.persistenceManager.storageKind=e.meta.storageKind:a.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 a.persistenceManager.get({validateVault:e})}const n=new U.default({migrations:j.default,defaultVersion:null});n.on("error",e=>{console.warn(e);const n=(0,K.default)(t);Se?.captureException(e,{extra:{vaultStructure:n}})});let r=!1;t?.data||t?.meta||(r=!0,t=n.generateInitialState(Ie));const{state:i,changedKeys:o}=await n.migrateData(t),l=async n=>{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 a.persistenceManager.getBackup();o=e?.AppMetadataController?.firstTimeInfo}catch{}const c=new Error(n);return c.sentryTags={"corruption.preMigrationVersion":String(r??"unknown"),"corruption.backupShouldExist":String(s),"corruption.installVersion":String(o?.version??"unknown"),"corruption.installDate":String(o?.date??"unknown")},c};if(!i)throw await l("MetaMask - migrator returned undefined");if(!(0,c.isObject)(i.meta))throw await l(`MetaMask - migrator metadata has invalid type '${typeof i.meta}'`);if("number"!=typeof i.meta.version)throw await l(`MetaMask - migrator metadata version has invalid type '${typeof i.meta.version}'`);if(!["data","split",undefined].includes(i.meta.storageKind))throw await l(`MetaMask - migrator metadata storageKind has invalid value '${i.meta.storageKind}'`);if(!(0,c.isObject)(i.data))throw await l(`MetaMask - migrator data has invalid type '${typeof i.data}'`);if(a.persistenceManager.setMetadata(i.meta),s.default.debug("[Split State]: Loaded data from persistence with storageKind '%s'",a.persistenceManager.storageKind),"data"===a.persistenceManager.storageKind){const e=!0===i.meta.platformSplitStateGradualRolloutAttempted,t=!e&&await(0,L.useSplitStateStorage)(i.data);s.default.debug("[Split State]: shouldUseSplitStateStorage: %s (alreadyTried: %s)",t,e),t&&(i.meta.platformSplitStateGradualRolloutAttempted=!0,a.persistenceManager.setMetadata(i.meta)),s.default.debug("[Split State]: Writing data to persistence with storageKind 'data'"),await a.persistenceManager.set(i.data),t&&(await a.persistenceManager.migrateToSplitState(i.data),i.meta=a.persistenceManager.getMetaData(),i.meta!==undefined&&(delete i.meta.platformSplitStateGradualRolloutAttempted,a.persistenceManager.setMetadata(i.meta)),await a.persistenceManager.persist())}else{if("split"!==a.persistenceManager.storageKind)throw new Error(`MetaMask - persistenceManager has invalid storageKind '${a.persistenceManager.storageKind}'`);if(r)for(const[e,t]of Object.entries(i.data))a.persistenceManager.update(e,t);else for(const e of o)a.persistenceManager.update(e,i.data[e]);await a.persistenceManager.persist()}return s.default.debug("[Split State]: Load complete."),i}function st(e,t,n){const{analyticsId:a}=Fe.getState();if(!(0,q.shouldEmitDappViewedEvent)(a))return;const r=Fe.getPermittedAccounts(e).length;if(0===r)return;const i=Fe.controllerMessenger.call("AccountsController:getState"),s=Object.keys(i.internalAccounts.accounts).length,o=(0,le.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: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,n=new URL(e.sender.url),{origin:a}=n,r=new URL(e.sender.tab.url),{origin:i}=r,{frameId:s}=e.sender;Object.keys(xe).includes(t)||(xe[t]=a),t in $e||($e[t]=i),t in Be||(Be[t]=s);const o=Fe.controllerMessenger.call("PermissionController:hasPermissions",a),c="New Tab"!==e.sender.tab.title;o&&c&&st(a,i,s)}function ct(e){const{completedMetaMetricsOnboarding:t,optedIn:n}=Fe.getState();if(!t||!n)return;const a=Fe.appStateController.state.appActiveTab?.origin,r=(0,w.getActiveTabDomainAllowlist)(Fe.remoteFeatureFlagController.state),i=(0,w.getActiveTabDomainForMetrics)(a,r);(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.AppOpened).addCategory(b.MetaMetricsEventCategory.App).addProperties(i?{active_tab_domain:i}:{}).build({environmentType:e}))}function lt(e){const t=[f.ENVIRONMENT_TYPE_POPUP,f.ENVIRONMENT_TYPE_NOTIFICATION,f.ENVIRONMENT_TYPE_FULLSCREEN,f.ENVIRONMENT_TYPE_SIDEPANEL];return!(Object.values(je).some(Boolean)||Ne||Oe>0||De>0)&&t.includes(e)}const dt=async e=>{if(await Ke,Fe)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 a=n[0],{id:r,title:i,url:s,favIconUrl:c}=a;if(!s)return void Fe.appStateController.clearAppActiveTab();const{origin:l,protocol:d,host:u,href:p}=new URL(s);if(!(0,q.isWebOrigin)(l))return void Fe.appStateController.clearAppActiveTab();Fe.appStateController.setAppActiveTab({id:r,title:i,origin:l,protocol:d,url:s,host:u,href:p,favIconUrl:c}),Fe.subjectMetadataController.addSubjectMetadata({origin:l,name:i||u||l,iconUrl:c||null,subjectType:"website"})}catch(e){console.log("Error refreshing appActiveTab:",e.message)}};function ut(e,t,n,r,c,u,p){Fe=new V.default({infuraProjectId:globalThis.INFURA_PROJECT_ID,showUserConfirmation:pt,initState:e,initLangCode:t,platform:Me,notificationManager:Te,browser:o.default,getRequestAccountTabIds:()=>Ue,getOpenMetamaskTabsIds:()=>je,isFirstMetaMaskControllerSetup:n,currentMigrationVersion:r.version,featureFlags:{},offscreenPromise:c,preinstalledSnaps:u,requestSafeReload:Ce,cronjobControllerStorageManager:p}),a.persistenceManager.setOnSetFailed(e=>{Fe.appStateController.setStorageWriteErrorType(e)});const h=[],m=Fe.store.getState();for(const t of Object.keys(m)){const n=e[t]||{},a=m[t];if(null===a||"object"!=typeof a){(0,y.captureException)(new Error(`Invalid controller state for '${t}' of type '${null===a?"null":typeof a}'`));continue}const r=Object.keys(a);if(r.length===Object.keys(n).length){for(const e of r)if(a[e]!==n[e]){h.push(t);break}}else h.push(t)}var w;"split"===a.persistenceManager.storageKind?(h.length>0&&(s.default.info(`MetaMaskController state changed during configuration for controllers: ${h.join(", ")}. Persisting updated state.`),h.forEach(e=>{a.persistenceManager.update(e,m[e])}),ve().catch(e=>{s.default.error("Error persisting updated state:",e),Se?.captureException(e)})),Fe.store.on("stateChange",async({controllerKey:e,newState:t,_oldState:n,_patches:r})=>{a.persistenceManager.update(e,t),N.backedUpStateKeys.includes(e)&&N.backedUpStateKeys.forEach(t=>{if(t===e)return;const n=Fe.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 r=Fe.controllerMessenger.call(`${t}:getState`),i=(0,l.deriveStateFromMetadata)(r,n.metadata,"persist");a.persistenceManager.update(t,i)});try{await ve()}catch(e){s.default.error("Error persisting state change:",e),Se?.captureException(e)}})):(h.length>0&&(s.default.info(`MetaMaskController state changed during configuration for controllers: ${h.join(", ")}. Persisting updated state.`),ve(m).catch(e=>{s.default.error("Error persisting updated controller state:",e),Se?.captureException(e)})),Fe.store.on("update",ve)),Fe.store.on("error",e=>{s.default.error("MetaMask controller.store error:",e),Se?.captureException(e)}),(0,H.default)({getCurrentChainId:()=>(0,S.getCurrentChainId)({metamask:Fe.networkController.state}),getIpfsGateway:Fe.preferencesController.getIpfsGateway.bind(Fe.preferencesController),getUseAddressBarEnsResolution:()=>Fe.preferencesController.state.useAddressBarEnsResolution,provider:Fe.provider}),w=Fe,global.stateHooks.getSentryAppState=function(){const e=w.memStore.getState();return(0,C.maskObject)(e,$.SENTRY_BACKGROUND_STATE)};const E=()=>Oe>0||Boolean(Object.keys(je).length)||Ne||De>0||!1,_=()=>Oe>0||De>0,M=()=>Ne&&!_(),T=(e,t)=>{if(!1===e)Fe.onClientClosed();else{if(t===f.ENVIRONMENT_TYPE_FULLSCREEN&&Boolean(Object.keys(je).length)||t===f.ENVIRONMENT_TYPE_SIDEPANEL&&De>0)return;Fe.onEnvironmentTypeClosed(t)}};function A(e){try{Fe.appStateController.setDefaultHomeActiveTabName(e??null)}catch(e){console.error("Error setting landing tab:",e)}}function P(){Le.clear(),Re=0,k()}function O(e,t){return e>t?`${t}+`:String(e)}function k(){const e=D();let t="",n=ge;Re>0&&!M()?(t=O(Re,me),n=he):e>0&&(t=O(e,me));try{const e={text:t},a={color:n};v.isManifestV3?(o.default.action.setBadgeText(e),o.default.action.setBadgeBackgroundColor(a)):(o.default.browserAction.setBadgeText(e),o.default.browserAction.setBadgeBackgroundColor(a))}catch(e){console.error("Error updating browser badge:",e)}}function D(){try{return(0,R.getAttentionRequiredApprovalCount)({approvalController:Fe.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:n,senderUrl:a,isMetaMaskUIPort:r}=Pe(e);if(r){const a=new d.ExtensionPortStream(e),r=function({chunkSize:e}){(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.PortStreamChunked).addCategory(b.MetaMetricsEventCategory.PortStream).addProperties({chunkSize:e}).build())};e.onDisconnect.addListener(()=>a.off("message-too-large",r)),a.on("message-too-large",r),Fe.isClientOpen=!0,Fe.setupTrustedCommunication(a,e.sender).finally(()=>{t?.()});const o=n===f.ENVIRONMENT_TYPE_SIDEPANEL&&lt(f.ENVIRONMENT_TYPE_SIDEPANEL);if(n!==f.ENVIRONMENT_TYPE_SIDEPANEL&&lt(s=n)&&ct(s),(0,F.updateRemoteFeatureFlags)(Fe),n===f.ENVIRONMENT_TYPE_POPUP&&(P(),Oe+=1,(0,i.finished)(a,()=>{Oe-=1;const e=E();Fe.isClientOpen=e,T(e,f.ENVIRONMENT_TYPE_POPUP)})),n===f.ENVIRONMENT_TYPE_SIDEPANEL&&(P(),De+=1,dt().then(()=>{o&&ct(f.ENVIRONMENT_TYPE_SIDEPANEL)}),(0,i.finished)(a,()=>{De=Math.max(De-1,0);const e=E();Fe.isClientOpen=e,T(e,f.ENVIRONMENT_TYPE_SIDEPANEL)})),n===f.ENVIRONMENT_TYPE_NOTIFICATION&&(Ne=!0,(0,i.finished)(a,()=>{Ne=!1,Re>0&&A(g.AccountOverviewTabKey.Activity),k();const e=E();Fe.isClientOpen=e,T(e,f.ENVIRONMENT_TYPE_NOTIFICATION)})),n===f.ENVIRONMENT_TYPE_FULLSCREEN){P();const t=e.sender.tab.id;je[t]=!0,(0,i.finished)(a,()=>{delete je[t];const e=E();Fe.isClientOpen=e,T(e,f.ENVIRONMENT_TYPE_FULLSCREEN)})}}else if(a&&a.origin===Ve.origin&&a.pathname===Ve.pathname){const t=new d.ExtensionPortStream(e,{chunkSize:0});Fe.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:a}=n;ot(e),e.onMessage.addListener(e=>{e.data&&e.data.method===f.MESSAGE_TYPE.ETH_REQUEST_ACCOUNTS&&(Ue[a]=t)})}if(a&&X.COOKIE_ID_MARKETING_WHITELIST_ORIGINS.some(e=>e===a.origin)){const t=new d.ExtensionPortStream(e,{chunkSize:0});Fe.setUpCookieHandlerCommunication({connectionStream:t})}const t=new d.ExtensionPortStream(e,{chunkSize:0});if(Je(t,e.sender),Ae||!v.isManifestV3){const n=(0,G.setupMultiplex)(t);n.ignoreStream(Z.METAMASK_EIP_1193_PROVIDER),Xe(n.createStream(Z.METAMASK_CAIP_MULTICHAIN_PROVIDER),e.sender)}}var s},We=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,I.createCaipStream)(n),e.sender)}else Je(n,e.sender)},Je=(e,t)=>{Fe.setupUntrustedCommunicationEip1193({connectionStream:e,sender:t})},Xe=(e,t)=>{Fe.setupUntrustedCommunicationCaip({connectionStream:e,sender:t})},k(),Fe.controllerMessenger.subscribe(V.METAMASK_CONTROLLER_EVENTS.DECRYPT_MESSAGE_MANAGER_UPDATE_BADGE,k),Fe.controllerMessenger.subscribe(V.METAMASK_CONTROLLER_EVENTS.ENCRYPTION_PUBLIC_KEY_MANAGER_UPDATE_BADGE,k),Fe.signatureController.hub.on(V.METAMASK_CONTROLLER_EVENTS.UPDATE_BADGE,k),Fe.controllerMessenger.subscribe(V.METAMASK_CONTROLLER_EVENTS.APP_STATE_UNLOCK_CHANGE,k),Fe.controllerMessenger.subscribe(V.METAMASK_CONTROLLER_EVENTS.APPROVAL_STATE_CHANGE,k),Fe.controllerMessenger.subscribe(V.METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_LIST_UPDATED,k),Fe.controllerMessenger.subscribe(V.METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_MARK_AS_READ,k),Fe.controllerMessenger.subscribe("TransactionController:transactionStatusUpdated",function({transactionMeta:e}){const{status:t,txParams:n,chainId:a}=e??{};if("failed"!==t&&"dropped"!==t)return;const{from:r,nonce:i}=n??{},s=r&&i!==undefined&&a?`${a}:${r.toLowerCase()}:${i}`:undefined;if(s&&Le.has(s))return;if(_())return;s&&(Le.size>=be&&Le.clear(),Le.add(s));Re+=1,M()||A(g.AccountOverviewTabKey.Activity);k()}),Te.on(B.NOTIFICATION_MANAGER_EVENTS.POPUP_CLOSED,({automaticallyClosed:e})=>{e?D()>0&&pt():(Fe.signatureController.rejectUnapproved(b.REJECT_NOTIFICATION_CLOSE_SIG),Fe.decryptMessageController.rejectUnapproved(b.REJECT_NOTIFICATION_CLOSE),Fe.encryptionPublicKeyController.rejectUnapproved(b.REJECT_NOTIFICATION_CLOSE),Fe.legacyBackgroundApiService.rejectAllPendingApprovals()),k()})}async function pt(){const e=await Me.getActiveTabs(),t=Boolean(e.find(e=>je[e.id])),n=e.length>0&&e[0].extData&&e[0].extData.indexOf("vivaldi_tab")>-1;if(!ke&&(n||0===Oe)&&!t&&0===De){ke=!0;try{const e=Fe.appStateController.getCurrentPopupId();await Te.showPopup(e=>Fe.appStateController.setCurrentPopupId(e),e)}finally{ke=!1}}}const ft=async e=>{const{deferredDeepLink:t,traits:n}=await e;Fe.metaMetricsController.updateTraits({[b.MetaMetricsUserTrait.InstallDateExt]:(new Date).toISOString().split("T")[0],...n});const a={};t&&(Fe.appStateController.setDeferredDeepLink(t),a.install_source="deeplink",a.deeplink_path=t.referringLink);const r={category:b.MetaMetricsEventCategory.App,event:b.MetaMetricsEventName.AppInstalled,properties:a},{completedMetaMetricsOnboarding:i,optedIn:s,analyticsId:o}=Fe.getState();!0===i&&!1===s||(!0===i&&!0===s&&o?(0,z.trackEvent)((0,z.createEventBuilder)(b.MetaMetricsEventName.AppInstalled).addCategory(b.MetaMetricsEventCategory.App).addProperties(a).build()):Fe.metaMetricsController.addEventBeforeMetricsOptIn(r))};o.default.runtime.onUpdateAvailable.addListener(async function(e){await Ke,s.default.info("An update is available",e?.version),Fe.appStateController.setPendingExtensionVersion(e?.version??null)});(async()=>{if(o.default?.sidePanel)try{await Ke,await async function(){if(!o.default?.sidePanel?.setPanelBehavior)return;const e=Fe?.preferencesController?.state?.preferences?.useSidePanelAsDefault??!0;await o.default.sidePanel.setPanelBehavior({openPanelOnActionClick:e})}(),Fe?.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(Fe){const{tabId:t}=e,n=xe[t],a=$e[t];n&&Fe.permissionController.state.subjects[n]!==undefined&&st(n,a,Be[t]);const r=(0,P.getPartnerByOrigin)(a);r&&Fe.permissionController.state.subjects[a]!==undefined&&Fe.handleDefiReferral(r,t,ce.ReferralTriggerType.OnNavigateConnectedTab).catch(e=>{s.default.error(`Failed to handle ${r.name} referral after navigation to connected tab: `,e)})}});try{await at(e),a.persistenceManager.cleanUpMostRecentRetrievedState(),s.default.info("MetaMask initialization complete."),He()}catch(e){s.default.error(e),qe(e)}}(async()=>{await dt()})(),o.default.tabs.onActivated.addListener(async({tabId:e})=>{if(await Ke,!Fe)return{};try{const t=await o.default.tabs.get(e),{id:n,title:a,url:r,favIconUrl:i}=t;if(!r)return Fe.appStateController.clearAppActiveTab(),{};const{origin:s,protocol:c,host:l,href:d}=new URL(r);if(!(0,q.isWebOrigin)(s))return Fe.appStateController.clearAppActiveTab(),{};Fe.appStateController.setAppActiveTab({id:n,title:a,origin:s,protocol:c,url:r,host:l,href:d,favIconUrl:i}),Fe.subjectMetadataController.addSubjectMetadata({origin:s,name:a||l||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 Ke,!Fe)return{};const a=t.url!==undefined,r="complete"===t.status;if(!a&&!r)return{};try{const t=n||await o.default.tabs.get(e),{id:i,title:s,url:c,favIconUrl:l}=t,d=Fe.appStateController.state.appActiveTab,u=d?.id===i;if(!c)return u&&Fe.appStateController.clearAppActiveTab(),{};const{origin:p,protocol:f,host:g,href:h}=new URL(c);if(!p||"null"===p||p.startsWith("chrome-extension://")||p.startsWith("moz-extension://"))return u&&Fe.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}(a||r)&&m&&(Fe.appStateController.setAppActiveTab({id:i,title:s,origin:p,protocol:f,url:c,host:g,href:h,favIconUrl:l}),Fe.subjectMetadataController.addSubjectMetadata({origin:p,name:s||g||p,iconUrl:l||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 n=null;(e||t?.simulateBackgroundStateSyncHang||t?.simulateBackgroundInitializationHang)&&(n=await a.persistenceManager.getBackup().catch(()=>null));const r=(0,N.hasVault)(n);if((t?.simulateBackgroundStateSyncHang||t?.simulateBackgroundInitializationHang)&&Ee&&(Ee.hasVaultAtStartup=r?Date.now():null),e&&(await(0,re.clearCriticalErrorRestoreSession)(o.default),r)){Ee&&(Ee.restoreInProgress=!0);const t={tabId:e.tabId,tabUrl:e.tabUrl};gt(n);try{await Ke}catch(e){return void s.default.error("critical-error-restore: initialization failed",e)}return Fe.onboardingController.setFirstTimeFlowType(p.FirstTimeFlowType.restore),void await(0,re.handoffRestoringTabToExtension)(Me,t)}gt(null)}().catch(e=>{s.default.error("initOrRestoreBackground failed",e)})}}},{package:"$root$",file:"app/scripts/background.js"}]],[12],{});