>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(g[e])return g[e];var t;if("k256"===e)t=new y;else if("p224"===e)t=new w;else if("p192"===e)t=new b;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new P}return g[e]=t,t},E.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},E.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new s(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var a=new s(1).toRed(this),c=a.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new s(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var d=this.pow(l,i),h=this.pow(e,i.addn(1).iushrn(1)),f=this.pow(e,i),p=o;0!==f.cmp(a);){for(var m=f,g=0;0!==m.cmp(a);g++)m=m.redSqr();n(g=0;n--){for(var u=t.words[n],l=c-1;l>=0;l--){var d=u>>l&1;i!==r[0]&&(i=this.sqr(i)),0!==d||0!==o?(o<<=1,o|=d,(4===++a||0===n&&0===l)&&(i=this.mul(i,r[o]),a=0,o=0)):a=0}c=26}return i},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new k(e)},i(k,E),k.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},k.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},k.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},k.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},k.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>bn.js"}],[1385,{},function(){with(this)return function(){"use strict";return function(e,t,r){t.exports=[{constant:!1,inputs:[{name:"_new",type:"address"}],name:"setOwner",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[],name:"totalSignatures",outputs:[{name:"",type:"uint256"}],payable:!1,type:"function"},{constant:!0,inputs:[],name:"owner",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[],name:"drain",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"",type:"bytes4"}],name:"entries",outputs:[{name:"",type:"string"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"_method",type:"string"}],name:"register",outputs:[{name:"",type:"bool"}],payable:!1,type:"function"},{inputs:[],type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,name:"creator",type:"address"},{indexed:!0,name:"signature",type:"bytes4"},{indexed:!1,name:"method",type:"string"}],name:"Registered",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"old",type:"address"},{indexed:!0,name:"current",type:"address"}],name:"NewOwner",type:"event"}]}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry"}],[1386,{"./abi":1385,"./registry-map.json":1387,ethjs:1402},function(){with(this)return function(){"use strict";return function(e,t,r){const n=e("ethjs"),i=e("./registry-map.json"),s=e("./abi");t.exports=class{constructor(e={}){this.provider=e.provider||new n.HttpProvider("https://mainnet.infura.io/eth-contract-registry"),this.eth=new n(this.provider);const t=i[e.network||"1"];if(!t)throw new Error("No method registry found on the requested network.");this.registry=this.eth.contract(s).at(t)}async lookup(e){return(await this.registry.entries(e))[0]}parse(e){let t=e.match(/^.+(?=\()/);t=t?t[0].charAt(0).toUpperCase()+t[0].slice(1).split(/(?=[A-Z])/).join(" "):"";const r=e.match(/\(.+\)/);let n=[];return r&&(n=r[0].slice(1,-1).split(",").map((e=>({type:e})))),{name:t,args:n}}}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry"}],[1387,{},function(){with(this)return function(){"use strict";return function(e,t,r){t.exports={1:"0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86"}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry"}],[1388,{"./index":1389,"ethereum-cryptography/hdkey":2582},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});var n=e("./index"),i=e("ethereum-cryptography/hdkey"),s=function(){function e(e){this._hdkey=e}return e.fromMasterSeed=function(t){return new e(i.HDKey.fromMasterSeed(t))},e.fromExtendedKey=function(t){return new e(i.HDKey.fromExtendedKey(t))},e.prototype.privateExtendedKey=function(){if(!this._hdkey.privateExtendedKey)throw new Error("This is a public key only wallet");return this._hdkey.privateExtendedKey},e.prototype.publicExtendedKey=function(){return this._hdkey.publicExtendedKey},e.prototype.derivePath=function(t){return new e(this._hdkey.derive(t))},e.prototype.deriveChild=function(t){return new e(this._hdkey.deriveChild(t))},e.prototype.getWallet=function(){return this._hdkey._privateKey?n.default.fromPrivateKey(this._hdkey._privateKey):n.default.fromPublicKey(this._hdkey._publicKey,!0)},e}();r.default=s}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>ethereumjs-wallet"}],[1389,{"./hdkey":1388,"./thirdparty":1390,bs58check:2184,buffer:2175,crypto:2285,"ethereumjs-util":2612,randombytes:5634,"scrypt-js":5827,"uuid/v4":1393},function(){with(this)return function(){"use strict";return function(e,t,r){(function(t){(function(){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]@metamask/controllers>ethereumjs-wallet"}],[139,{lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash");var i={version:56,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=56;const{PreferencesController:r}=t.data;return Array.isArray(null==r?void 0:r.tokens)&&(r.tokens=r.tokens.filter((({address:e})=>e))),null!=r&&r.accountTokens&&"object"==typeof r.accountTokens&&Object.keys(r.accountTokens).forEach((e=>{Object.keys(r.accountTokens[e]).forEach((t=>{r.accountTokens[e][t]=r.accountTokens[e][t].filter((({address:e})=>e))}))})),null!=r&&r.assetImages&&"undefined"in r.assetImages&&delete r.assetImages.undefined,t}};r.default=i}}},{package:"$root$"}],[1390,{"./index":1389,"aes-js":1778,buffer:2175,crypto:2285,"ethereumjs-util":2612,"scrypt-js":5827,utf8:6094},function(){with(this)return function(){"use strict";return function(e,t,r){(function(t){(function(){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]0&&d!==o.sha256(o.sha256(s)).slice(0,8).toString("hex"))throw new Error("Failed to decrypt input - possibly invalid passphrase");return[3,4];case 3:throw new Error("Unsupported or invalid entropy type");case 4:return[2,new c.default(s)]}}))}))}function g(e,t){if(e.length<10)throw new Error("Passphrase must be at least 10 characters");if(t.length<10)throw new Error("User id must be at least 10 characters");var r=e+t,n=s.pbkdf2Sync(r,r,2e3,32,"sha256");return new c.default(n)}r.fromEtherWallet=f,r.fromEtherCamp=p,r.fromKryptoKit=m,r.fromQuorumWallet=g;var v={fromEtherWallet:f,fromEtherCamp:p,fromKryptoKit:m,fromQuorumWallet:g};r.default=v}).call(this)}).call(this,e("buffer").Buffer)}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>ethereumjs-wallet"}],[1391,{},function(){with(this)return function(){"use strict";return function(e,t,r){for(var n=[],i=0;i<256;++i)n[i]=(i+256).toString(16).substr(1);t.exports=function(e,t){var r=t||0,i=n;return[i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]]].join("")}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>ethereumjs-wallet>uuid"}],[1392,{},function(){with(this)return function(){"use strict";return function(e,t,r){var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(n){var i=new Uint8Array(16);t.exports=function(){return n(i),i}}else{var s=new Array(16);t.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),s[t]=e>>>((3&t)<<3)&255;return s}}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>ethereumjs-wallet>uuid"}],[1393,{"./lib/bytesToUuid":1391,"./lib/rng":1392},function(){with(this)return function(){"use strict";return function(e,t,r){var n=e("./lib/rng"),i=e("./lib/bytesToUuid");t.exports=function(e,t,r){var s=t&&r||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var o=(e=e||{}).random||(e.rng||n)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var a=0;a<16;++a)t[s+a]=o[a];return t||i(o)}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>ethereumjs-wallet>uuid"}],[1394,{"./utils/index.js":1395,buffer:2175},function(){with(this)return function(){"use strict";return function(e,t,r){(function(r){(function(){var n=e("./utils/index.js"),i=n.uint256Coder,s=(n.coderBoolean,n.coderFixedBytes,n.coderAddress,n.coderDynamicBytes,n.coderString,n.coderArray,n.paramTypePart,n.getParamCoder);function o(){}function a(e,t){if(e.length!==t.length)throw new Error("[ethjs-abi] while encoding params, types/values mismatch, Your contract requires "+e.length+" types (arguments), and you passed in "+t.length);var n=[];function o(e){return parseInt(32*Math.ceil(e/32))}e.forEach((function(e,r){var i=s(e);n.push({dynamic:i.dynamic,value:i.encode(t[r])})}));var a=0,c=0;n.forEach((function(e){e.dynamic?(a+=32,c+=o(e.value.length)):a+=o(e.value.length)}));var u=0,l=a,d=new r(a+c);return n.forEach((function(e,t){e.dynamic?(i.encode(l).copy(d,u),u+=32,e.value.copy(d,l),l+=o(e.value.length)):(e.value.copy(d,u),u+=o(e.value.length))})),"0x"+d.toString("hex")}function c(e,t,r){var a=!(arguments.length>3&&arguments[3]!==undefined)||arguments[3];arguments.length<3&&(r=t,t=e,e=[]),r=n.hexOrBuffer(r);var c=new o,u=0;return t.forEach((function(t,n){var o=s(t);if(o.dynamic){var l=i.decode(r,u),d=o.decode(r,l.value.toNumber());u+=l.consumed}else{d=o.decode(r,u);u+=d.consumed}a&&(c[n]=d.value),e[n]&&(c[e[n]]=d.value)})),c}function u(e){var t=e.name+"("+n.getKeys(e.inputs,"type").join(",")+")";return"0x"+new r(n.keccak256(t),"hex").slice(0,4).toString("hex")}function l(e,t){var r=a(n.getKeys(e.inputs,"type"),t).substring(2);return""+u(e)+r}function d(e){var t=e.name+"("+n.getKeys(e.inputs,"type").join(",")+")";return"0x"+n.keccak256(t)}function h(e,t,i){var o=!(arguments.length>3&&arguments[3]!==undefined)||arguments[3],a=e.inputs.filter((function(e){return!e.indexed})),u=n.getKeys(a,"name",!0),l=n.getKeys(a,"type"),d=c(u,l,n.hexOrBuffer(t),o),h=e.anonymous?0:1;return e.inputs.filter((function(e){return e.indexed})).map((function(e,t){var n=new r(i[t+h].slice(2),"hex"),o=s(e.type);d[e.name]=o.decode(n,0).value})),d._eventName=e.name,d}function f(e,t){var r=!(arguments.length>2&&arguments[2]!==undefined)||arguments[2];if(e&&t.topics[0]===d(e))return h(e,t.data,t.topics,r)}t.exports={encodeParams:a,decodeParams:c,encodeMethod:l,decodeMethod:function(e,t){return c(n.getKeys(e.outputs,"name",!0),n.getKeys(e.outputs,"type"),n.hexOrBuffer(t))},encodeEvent:function(e,t){return l(e,t)},decodeEvent:h,decodeLogItem:f,logDecoder:function(e){var t=!(arguments.length>1&&arguments[1]!==undefined)||arguments[1],r={};return e.filter((function(e){return"event"===e.type})).map((function(e){r[d(e)]=e})),function(e){return e.map((function(e){return f(r[e.topics[0]],e,t)})).filter((function(e){return e}))}},eventSignature:d,encodeSignature:u}}).call(this)}).call(this,e("buffer").Buffer)}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-abi"}],[1395,{"bn.js":1384,buffer:2175,"js-sha3":1408,"number-to-bn":5384},function(){with(this)return function(){"use strict";return function(e,t,r){(function(r){(function(){var n=e("bn.js"),i=e("number-to-bn"),s=e("js-sha3").keccak_256;function o(e){for(var t=e,r=t[0];t.length>0&&"0"===r.toString();)r=(t=t.slice(1))[0];return t}function a(e){var t=e.toString(16);return t.length%2&&(t="0"+t),o(new r(t,"hex"))}function c(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))&&(!t||e.length===2+2*t)}function u(e,t){var n=e;if(!r.isBuffer(n)){if(!c(n)){var i=new Error(t?"[ethjs-abi] invalid "+t:"[ethjs-abi] invalid hex or buffer, must be a prefixed alphanumeric even length hex string");throw i.reason="[ethjs-abi] invalid hex string, hex must be prefixed and alphanumeric (e.g. 0x023..)",i.value=n,i}(n=n.substring(2)).length%2&&(n="0"+n),n=new r(n,"hex")}return n}function l(e,t){return{encode:function(n){var s=n;return"object"==typeof s&&s.toString&&(s.toTwos||s.dividedToIntegerBy)&&(s=s.toString(10).split(".")[0]),"string"!=typeof s&&"number"!=typeof s||(s=String(s).split(".")[0]),s=(s=i(s)).toTwos(8*e).maskn(8*e),t&&(s=s.fromTwos(8*e).toTwos(256)),s.toArrayLike(r,"be",32)},decode:function(r,i){var s=32-e,o=new n(r.slice(i+s,i+32));return o=t?o.fromTwos(8*e):o.maskn(8*e),{consumed:32,value:new n(o.toString(10))}}}}var d=l(32,!1),h={encode:function(e){return d.encode(e?1:0)},decode:function(e,t){var r=d.decode(e,t);return{consumed:r.consumed,value:!r.value.isZero()}}};function f(e){return{encode:function(e){var t=e;if(32===(t=u(t)).length)return t;var n=new r(32);return n.fill(0),t.copy(n),n},decode:function(t,r){if(0!==t.length&&t.length256||o%8!=0)throw new Error("[ethjs-abi] while getting param coder for type "+t+", invalid "+s+" width: "+t);r=l(o/8,"int"===s);break;case"bool":if(r)throw new Error(n);r=h;break;case"string":if(r)throw new Error(n);r=y;break;case"bytes":if(r)throw new Error(n);if(i[3]){var a=parseInt(i[3]);if(0===a||a>32)throw new Error("[ethjs-abi] while getting param coder for prefix bytes, invalid type "+t+", size "+a+" should be 0 or greater than 32");r=f(a)}else r=v;break;case"address":if(r)throw new Error(n);r=p;break;case"[]":if(!r||r.dynamic)throw new Error(n);r=w(r,-1);break;default:if(!r||r.dynamic)throw new Error(n);r=w(r,parseInt(i[6]))}}if(!r)throw new Error(n);return r}}}).call(this)}).call(this,e("buffer").Buffer)}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-abi"}],[1396,{"./has-tx-object":1397,"babel-runtime/core-js/json/stringify":1919,"babel-runtime/core-js/object/assign":1920,"babel-runtime/helpers/asyncToGenerator":1928,"babel-runtime/regenerator":2045,"ethjs-abi":1399,"ethjs-filter":2658,"ethjs-util":2666,"js-sha3":1408,"promise-to-callback":5502},function(){with(this)return function(){"use strict";return function(e,t,r){var n=a(e("babel-runtime/regenerator")),i=a(e("babel-runtime/core-js/json/stringify")),s=a(e("babel-runtime/helpers/asyncToGenerator")),o=a(e("babel-runtime/core-js/object/assign"));function a(e){return e&&e.__esModule?e:{default:e}}var c=e("ethjs-abi"),u=e("ethjs-filter"),l=e("ethjs-util").getKeys,d=e("js-sha3").keccak_256,h=e("./has-tx-object"),f=e("promise-to-callback");function p(e){return e.filter((function(e){return("function"===e.type||"event"===e.type)&&e.name.length>0}))}t.exports=function(){var e=(a=(0,s.default)(n.default.mark((function e(t){var s,a,u,l,d,f=t.methodObject,p=t.methodArgs;return n.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return s="call",a={},h(p)&&(a=p.pop()),(u=(0,o.default)({},r.defaultTxObject,a,{to:r.address})).data=c.encodeMethod(f,p),!1===f.constant&&(s="sendTransaction"),e.next=8,r.query[s](u);case 8:if(l=e.sent,"call"!==s){e.next=19;break}return e.prev=10,d=c.decodeMethod(f,l),e.abrupt("return",d);case 15:throw e.prev=15,e.t0=e.catch(10),new Error("[ethjs-contract] while formatting incoming raw call data "+(0,i.default)(l)+" "+e.t0);case 19:return e.abrupt("return",l);case 20:case"end":return e.stop()}}),e,this,[[10,15]])}))),function(e){return a.apply(this,arguments)}),t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},r=this;var a;function m(e){return function(){var t=[].slice.call(arguments),n=l(e.inputs,"type",!1),i="0x"+d(e.name+"("+n.join(",")+")"),s=[i],a=(0,o.default)({},t[0])||{},u=(0,o.default)({},t[0]||{},{to:r.address,topics:s}),h=(0,o.default)({},a,{decoder:function(t){return c.decodeEvent(e,t,s)},defaultFilterObject:u});return new r.filters.Filter(h)}}function g(t){return function(){var r=void 0,n=[].slice.call(arguments);"function"==typeof n[n.length-1]&&(r=n.pop());var i=e({methodObject:t,methodArgs:n});return r?f(i)(r):i}}r.abi=t.contractABI||[],r.query=t.query,r.address=t.address||"0x",r.bytecode=t.contractBytecode||"0x",r.defaultTxObject=t.contractDefaultTxObject||{},r.filters=new u(r.query),p(r.abi).forEach((function(e){"function"===e.type?r[e.name]=g(e):"event"===e.type&&(r[e.name]=m(e))}))}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-contract"}],[1397,{"babel-runtime/core-js/object/keys":1923},function(){with(this)return function(){"use strict";return function(e,t,r){var n,i=e("babel-runtime/core-js/object/keys"),s=(n=i)&&n.__esModule?n:{default:n};var o=["from","to","data","value","gasPrice","gas"];t.exports=function(e){if(!Array.isArray(e)||0===e.length)return!1;var t=e[e.length-1];if(!t)return!1;if("object"!=typeof t)return!1;if(0===(0,s.default)(t).length)return!0;var r=(0,s.default)(t);if(o.some((function(e){return r.includes(e)})))return!0;return!1}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-contract"}],[1398,{"./contract":1396,"./has-tx-object":1397,"babel-runtime/core-js/object/assign":1920,"ethjs-abi":1399,"ethjs-filter":2658,"ethjs-util":2666,"js-sha3":1408},function(){with(this)return function(){"use strict";return function(e,t,r){var n,i=e("babel-runtime/core-js/object/assign"),s=(n=i)&&n.__esModule?n:{default:n};var o=e("ethjs-abi"),a=(e("js-sha3").keccak_256,e("ethjs-filter"),e("ethjs-util").getKeys),c=e("./contract"),u=e("./has-tx-object");function l(e){return e.filter((function(e){return"constructor"===e.type}))[0]}t.exports=function(e){return function(t,r,n){if(!Array.isArray(t))throw new Error("[ethjs-contract] Contract ABI must be type Array, got type "+typeof t);if(void 0!==r&&"string"!=typeof r)throw new Error("[ethjs-contract] Contract bytecode must be type String, got type "+typeof r);if(void 0!==n&&"object"!=typeof n)throw new Error("[ethjs-contract] Contract default tx object must be type Object, got type "+typeof t);var i={at:function(i){return new c({address:i,query:e,contractBytecode:r,contractDefaultTxObject:n,contractABI:t})},new:function(){var i={},c=null,d=[].slice.call(arguments);"function"==typeof d[d.length-1]&&(c=d.pop()),u(d)&&(i=d.pop());var h=l(t),f=(0,s.default)({},n,i);if(r&&(f.data=r),h){var p=o.encodeParams(a(h.inputs,"type"),d).substring(2);f.data=""+f.data+p}return c?e.sendTransaction(f,c):e.sendTransaction(f)}};return i}}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-contract"}],[1399,{"./utils/index.js":1400,buffer:2175},function(){with(this)return function(){"use strict";return function(e,t,r){(function(r){(function(){var n=e("./utils/index.js"),i=n.uint256Coder,s=(n.coderBoolean,n.coderFixedBytes,n.coderAddress,n.coderDynamicBytes,n.coderString,n.coderArray,n.paramTypePart,n.getParamCoder);function o(){}function a(e,t){if(e.length!==t.length)throw new Error("[ethjs-abi] while encoding params, types/values mismatch, Your contract requires "+e.length+" types (arguments), and you passed in "+t.length);var n=[];function o(e){return parseInt(32*Math.ceil(e/32))}e.forEach((function(e,r){var i=s(e);n.push({dynamic:i.dynamic,value:i.encode(t[r])})}));var a=0,c=0;n.forEach((function(e){e.dynamic?(a+=32,c+=o(e.value.length)):a+=o(e.value.length)}));var u=0,l=a,d=new r(a+c);return n.forEach((function(e,t){e.dynamic?(i.encode(l).copy(d,u),u+=32,e.value.copy(d,l),l+=o(e.value.length)):(e.value.copy(d,u),u+=o(e.value.length))})),"0x"+d.toString("hex")}function c(e,t,r){var a=!(arguments.length>3&&arguments[3]!==undefined)||arguments[3];arguments.length<3&&(r=t,t=e,e=[]),r=n.hexOrBuffer(r);var c=new o,u=0;return t.forEach((function(t,n){var o=s(t);if(o.dynamic){var l=i.decode(r,u),d=o.decode(r,l.value.toNumber());u+=l.consumed}else{d=o.decode(r,u);u+=d.consumed}a&&(c[n]=d.value),e[n]&&(c[e[n]]=d.value)})),c}function u(e,t){var i=e.name+"("+n.getKeys(e.inputs,"type").join(",")+")";return""+("0x"+new r(n.keccak256(i),"hex").slice(0,4).toString("hex"))+a(n.getKeys(e.inputs,"type"),t).substring(2)}function l(e){var t=e.name+"("+n.getKeys(e.inputs,"type").join(",")+")";return"0x"+n.keccak256(t)}function d(e,t,i){var o=!(arguments.length>3&&arguments[3]!==undefined)||arguments[3],a=e.inputs.filter((function(e){return!e.indexed})),u=n.getKeys(a,"name",!0),l=n.getKeys(a,"type"),d=c(u,l,n.hexOrBuffer(t),o),h=e.anonymous?0:1;return e.inputs.filter((function(e){return e.indexed})).map((function(e,t){var n=new r(i[t+h].slice(2),"hex"),o=s(e.type);d[e.name]=o.decode(n,0).value})),d._eventName=e.name,d}function h(e,t){var r=!(arguments.length>2&&arguments[2]!==undefined)||arguments[2];if(e&&t.topics[0]===l(e))return d(e,t.data,t.topics,r)}t.exports={encodeParams:a,decodeParams:c,encodeMethod:u,decodeMethod:function(e,t){return c(n.getKeys(e.outputs,"name",!0),n.getKeys(e.outputs,"type"),n.hexOrBuffer(t))},encodeEvent:function(e,t){return u(e,t)},decodeEvent:d,decodeLogItem:h,logDecoder:function(e){var t=!(arguments.length>1&&arguments[1]!==undefined)||arguments[1],r={};return e.filter((function(e){return"event"===e.type})).map((function(e){r[l(e)]=e})),function(e){return e.map((function(e){return h(r[e.topics[0]],e,t)})).filter((function(e){return e}))}},eventSignature:l}}).call(this)}).call(this,e("buffer").Buffer)}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-contract>ethjs-abi"}],[14,{"../../../../shared/constants/network":6267,"@babel/runtime/helpers/interopRequireDefault":200,"eth-block-tracker":2455,"eth-json-rpc-infura":2487,"eth-json-rpc-middleware":2493,"json-rpc-engine":4837},function(){with(this)return function(){"use strict";return function(e,t,r){var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.default=function({network:e,projectId:t}){const r=(0,o.default)({network:e,projectId:t,maxAttempts:5,source:"metamask"}),n=(0,s.providerFromMiddleware)(r),c=new a.PollingBlockTracker({provider:n});return{networkMiddleware:(0,i.mergeMiddleware)([u({network:e}),(0,s.createBlockCacheMiddleware)({blockTracker:c}),(0,s.createInflightCacheMiddleware)(),(0,s.createBlockRefMiddleware)({blockTracker:c,provider:n}),(0,s.createRetryOnEmptyMiddleware)({blockTracker:c,provider:n}),(0,s.createBlockTrackerInspectorMiddleware)({blockTracker:c}),r]),blockTracker:c}};var i=e("json-rpc-engine"),s=e("eth-json-rpc-middleware"),o=n(e("eth-json-rpc-infura")),a=e("eth-block-tracker"),c=e("../../../../shared/constants/network");function u({network:e}){if(!c.NETWORK_TYPE_TO_ID_MAP[e])throw new Error(`createInfuraClient - unknown network "${e}"`);const{chainId:t,networkId:r}=c.NETWORK_TYPE_TO_ID_MAP[e];return(0,i.createScaffoldMiddleware)({eth_chainId:t,net_version:r})}}}},{package:"$root$"}],[140,{"../../../shared/modules/random-id":6281,"@babel/runtime/helpers/interopRequireDefault":200,lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var i=e("lodash"),s=n(e("../../../shared/modules/random-id"));var o={version:57,async migrate(e){const t=(0,i.cloneDeep)(e);t.meta.version=57;const r=t.data;return t.data=function(e){var t;null!=e&&null!==(t=e.TransactionController)&&void 0!==t&&t.transactions&&Array.isArray(e.TransactionController.transactions)&&!e.TransactionController.transactions.some((e=>"object"!=typeof e||void 0===e.txParams))&&(e.TransactionController.transactions=(0,i.keyBy)(e.TransactionController.transactions,(e=>(void 0!==e.id&&null!==e.id||(e.id=(0,s.default)()),e.id))));return e}(r),t}};r.default=o}}},{package:"$root$"}],[1400,{"bn.js":1384,buffer:2175,"js-sha3":1408,"number-to-bn":5384},function(){with(this)return function(){"use strict";return function(e,t,r){(function(r){(function(){var n=e("bn.js"),i=e("number-to-bn"),s=e("js-sha3").keccak_256;function o(e){for(var t=e,r=t[0];t.length>0&&"0"===r.toString();)r=(t=t.slice(1))[0];return t}function a(e){var t=e.toString(16);return t.length%2&&(t="0"+t),o(new r(t,"hex"))}function c(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))&&(!t||e.length===2+2*t)}function u(e,t){var n=e;if(!r.isBuffer(n)){if(!c(n)){var i=new Error(t?"[ethjs-abi] invalid "+t:"[ethjs-abi] invalid hex or buffer, must be a prefixed alphanumeric even length hex string");throw i.reason="[ethjs-abi] invalid hex string, hex must be prefixed and alphanumeric (e.g. 0x023..)",i.value=n,i}(n=n.substring(2)).length%2&&(n="0"+n),n=new r(n,"hex")}return n}function l(e,t){return{encode:function(n){var s=n;return"object"==typeof s&&s.toString&&(s.toTwos||s.dividedToIntegerBy)&&(s=s.toString(10).split(".")[0]),"string"!=typeof s&&"number"!=typeof s||(s=String(s).split(".")[0]),s=(s=i(s)).toTwos(8*e).maskn(8*e),t&&(s=s.fromTwos(8*e).toTwos(256)),s.toArrayLike(r,"be",32)},decode:function(r,i){var s=32-e,o=new n(r.slice(i+s,i+32));return o=t?o.fromTwos(8*e):o.maskn(8*e),{consumed:32,value:new n(o.toString(10))}}}}var d=l(32,!1),h={encode:function(e){return d.encode(e?1:0)},decode:function(e,t){var r=d.decode(e,t);return{consumed:r.consumed,value:!r.value.isZero()}}};function f(e){return{encode:function(e){var t=e;if(32===(t=u(t)).length)return t;var n=new r(32);return n.fill(0),t.copy(n),n},decode:function(t,r){if(0!==t.length&&t.length256||o%8!=0)throw new Error("[ethjs-abi] while getting param coder for type "+t+", invalid "+s+" width: "+t);r=l(o/8,"int"===s);break;case"bool":if(r)throw new Error(n);r=h;break;case"string":if(r)throw new Error(n);r=y;break;case"bytes":if(r)throw new Error(n);if(i[3]){var a=parseInt(i[3]);if(0===a||a>32)throw new Error("[ethjs-abi] while getting param coder for prefix bytes, invalid type "+t+", size "+a+" should be 0 or greater than 32");r=f(a)}else r=v;break;case"address":if(r)throw new Error(n);r=p;break;case"[]":if(!r||r.dynamic)throw new Error(n);r=w(r,-1);break;default:if(!r||r.dynamic)throw new Error(n);r=w(r,parseInt(i[6]))}}if(!r)throw new Error(n);return r}}}).call(this)}).call(this,e("buffer").Buffer)}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-contract>ethjs-abi"}],[1401,{"babel-runtime/core-js/json/stringify":1919,"babel-runtime/core-js/object/assign":1920,"babel-runtime/core-js/object/define-property":1922,"babel-runtime/core-js/object/keys":1923,"babel-runtime/helpers/asyncToGenerator":1928,"babel-runtime/regenerator":2045,"ethjs-format":2659,"ethjs-rpc":2662,"promise-to-callback":5502},function(){with(this)return function(){"use strict";return function(e,t,r){var n=u(e("babel-runtime/regenerator")),i=u(e("babel-runtime/core-js/json/stringify")),s=u(e("babel-runtime/helpers/asyncToGenerator")),o=u(e("babel-runtime/core-js/object/define-property")),a=u(e("babel-runtime/core-js/object/keys")),c=u(e("babel-runtime/core-js/object/assign"));function u(e){return e&&e.__esModule?e:{default:e}}var l=e("ethjs-format"),d=e("ethjs-rpc"),h=e("promise-to-callback");function f(e,t){var r=this,n=t||{};if(!(this instanceof f))throw new Error('[ethjs-query] the Eth object requires the "new" flag in order to function normally (i.e. `const eth = new Eth(provider);`).');if("object"!=typeof e)throw new Error("[ethjs-query] the Eth object requires that the first input 'provider' must be an object, got '"+typeof e+"' (i.e. 'const eth = new Eth(provider);')");r.options=(0,c.default)({debug:n.debug||!1,logger:n.logger||console,jsonSpace:n.jsonSpace||0}),r.rpc=new d(e),r.setProvider=r.rpc.setProvider}function p(e,t){return function(){var r,o=(r=(0,s.default)(n.default.mark((function r(){var s,o;return n.default.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!(d.lengtht[0].length)){r.next=4;break}throw new Error("[ethjs-query] method '"+f+"' requires at most "+t[0].length+" params, "+d.length+" provided '"+(0,i.default)(d,null,u.options.jsonSpace)+"'. For more information visit: https://github.com/ethereum/wiki/wiki/JSON-RPC#"+e.toLowerCase());case 4:t[3]&&d.length0&&"function"==typeof d[d.length-1]&&(a=d.pop());var p=o.call(this);return a?h(p)(a):p}}t.exports=f,f.prototype.log=function(e){this.options.debug&&this.options.logger.log("[ethjs-query log] "+e)},(0,a.default)(l.schema.methods).forEach((function(e){(0,o.default)(f.prototype,e.replace("eth_",""),{enumerable:!0,value:p(e,l.schema.methods[e])})}))}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>ethjs-query"}],[1402,{"./lib/getTransactionSuccess.js":1403,"bn.js":1384,buffer:2175,"ethjs-abi":1394,"ethjs-contract":1398,"ethjs-filter":2658,"ethjs-provider-http":2660,"ethjs-query":1401,"ethjs-unit":2664,"ethjs-util":2666,"js-sha3":1408,"number-to-bn":5384},function(){with(this)return function(){"use strict";return function(e,t,r){(function(r){(function(){var n=e("ethjs-query"),i=e("ethjs-filter"),s=e("ethjs-contract"),o=e("ethjs-provider-http"),a=e("ethjs-abi"),c=e("ethjs-unit"),u=e("js-sha3").keccak_256,l=e("number-to-bn"),d=e("bn.js"),h=e("ethjs-util"),f=e("./lib/getTransactionSuccess.js");function p(e,t){if(!(this instanceof p))throw new Error('[ethjs] the Eth object requires you construct it with the "new" flag (i.e. `const eth = new Eth(...);`).');var r=this;r.options=t||{};var o=new n(e,r.options.query);Object.keys(Object.getPrototypeOf(o)).forEach((function(e){r[e]=function(){for(var t=arguments.length,r=Array(t),n=0;n@metamask/controllers>eth-method-registry>ethjs"}],[1403,{},function(){with(this)return function(){"use strict";return function(e,t,r){t.exports=function(e){return function(t,r){var n=0,i=e.options.timeout||8e5,s=e.options.interval||7e3,o=new Promise((function(r,o){var a=setInterval((function(){(e.getTransactionReceipt(t,(function(e,t){e&&(clearInterval(a),o(e)),!e&&t&&(clearInterval(a),r(t))})),n>=i)&&(clearInterval(a),o("Receipt timeout waiting for tx hash: "+t));n+=s}),s)}));return r&&o.then((function(e){return r(null,e)})).catch((function(e){return r(e,null)})),r?null:o}}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs"}],[1404,{"./helpers.js":1406},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});var n=e("./helpers.js");r.JsonPatchError=n.PatchError,r.deepClone=n._deepClone;var i={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){var i=o(r,this.path);i&&(i=n._deepClone(i));var s=a(r,{op:"remove",path:this.from}).removed;return a(r,{op:"add",path:this.path,value:s}),{newDocument:r,removed:i}},copy:function(e,t,r){var i=o(r,this.from);return a(r,{op:"add",path:this.path,value:n._deepClone(i)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:d(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}},s={add:function(e,t,r){return n.isInteger(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:i.move,copy:i.copy,test:i.test,_get:i._get};function o(e,t){if(""==t)return e;var r={op:"_get",path:t};return a(e,r),r.value}function a(e,t,a,c,l,h){if(void 0===a&&(a=!1),void 0===c&&(c=!0),void 0===l&&(l=!0),void 0===h&&(h=0),a&&("function"==typeof a?a(t,0,e,t.path):u(t,0)),""===t.path){var f={newDocument:e};if("add"===t.op)return f.newDocument=t.value,f;if("replace"===t.op)return f.newDocument=t.value,f.removed=e,f;if("move"===t.op||"copy"===t.op)return f.newDocument=o(e,t.from),"move"===t.op&&(f.removed=e),f;if("test"===t.op){if(f.test=d(e,t.value),!1===f.test)throw new r.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",h,t,e);return f.newDocument=e,f}if("remove"===t.op)return f.removed=e,f.newDocument=null,f;if("_get"===t.op)return t.value=e,f;if(a)throw new r.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",h,t,e);return f}c||(e=n._deepClone(e));var p=(t.path||"").split("/"),m=e,g=1,v=p.length,y=undefined,w=void 0,b=void 0;for(b="function"==typeof a?a:u;;){if((w=p[g])&&-1!=w.indexOf("~")&&(w=n.unescapePathComponent(w)),l&&"__proto__"==w)throw new TypeError("JSON-Patch: modifying `__proto__` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(a&&y===undefined&&(m[w]===undefined?y=p.slice(0,g).join("/"):g==v-1&&(y=t.path),y!==undefined&&b(t,0,e,y)),g++,Array.isArray(m)){if("-"===w)w=m.length;else{if(a&&!n.isInteger(w))throw new r.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",h,t,e);n.isInteger(w)&&(w=~~w)}if(g>=v){if(a&&"add"===t.op&&w>m.length)throw new r.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",h,t,e);if(!1===(f=s[t.op].call(t,m,w,e)).test)throw new r.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",h,t,e);return f}}else if(g>=v){if(!1===(f=i[t.op].call(t,m,w,e)).test)throw new r.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",h,t,e);return f}if(m=m[w],a&&g0)throw new r.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,s);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new r.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,s);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&e.value===undefined)throw new r.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,s);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&n.hasUndefined(e.value))throw new r.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,s);if(s)if("add"==e.op){var a=e.path.split("/").length,c=o.split("/").length;if(a!==c+1&&a!==c)throw new r.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,s)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==o)throw new r.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,s)}else if("move"===e.op||"copy"===e.op){var u=l([{op:"_get",path:e.from,value:undefined}],s);if(u&&"OPERATION_PATH_UNRESOLVABLE"===u.name)throw new r.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,s)}}function l(e,t,i){try{if(!Array.isArray(e))throw new r.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)c(n._deepClone(t),n._deepClone(e),i||!0);else{i=i||u;for(var s=0;sfast-json-patch"}],[1405,{"./core.js":1404,"./helpers.js":1406},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});
+/*!
+ * https://github.com/Starcounter-Jack/JSON-Patch
+ * (c) 2017 Joachim Wester
+ * MIT license
+ */
+var n=e("./helpers.js"),i=e("./core.js"),s=new WeakMap,o=function(e){this.observers=new Map,this.obj=e},a=function(e,t){this.callback=e,this.observer=t};function c(e,t){void 0===t&&(t=!1);var r=s.get(e.object);u(r.value,e.object,e.patches,"",t),e.patches.length&&i.applyPatch(r.value,e.patches);var n=e.patches;return n.length>0&&(e.patches=[],e.callback&&e.callback(n)),n}function u(e,t,r,i,s){if(t!==e){"function"==typeof t.toJSON&&(t=t.toJSON());for(var o=n._objectKeys(t),a=n._objectKeys(e),c=!1,l=a.length-1;l>=0;l--){var d=e[f=a[l]];if(!n.hasOwnProperty(t,f)||t[f]===undefined&&d!==undefined&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(s&&r.push({op:"test",path:i+"/"+n.escapePathComponent(f),value:n._deepClone(d)}),r.push({op:"remove",path:i+"/"+n.escapePathComponent(f)}),c=!0):(s&&r.push({op:"test",path:i,value:e}),r.push({op:"replace",path:i,value:t}),!0);else{var h=t[f];"object"==typeof d&&null!=d&&"object"==typeof h&&null!=h&&Array.isArray(d)===Array.isArray(h)?u(d,h,r,i+"/"+n.escapePathComponent(f),s):d!==h&&(!0,s&&r.push({op:"test",path:i+"/"+n.escapePathComponent(f),value:n._deepClone(d)}),r.push({op:"replace",path:i+"/"+n.escapePathComponent(f),value:n._deepClone(h)}))}}if(c||o.length!=a.length)for(l=0;lfast-json-patch"}],[1406,{},function(){with(this)return function(){"use strict";return function(e,t,r){
+/*!
+ * https://github.com/Starcounter-Jack/JSON-Patch
+ * (c) 2017 Joachim Wester
+ * MIT license
+ */
+var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},n(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(r,"__esModule",{value:!0});var s=Object.prototype.hasOwnProperty;function o(e,t){return s.call(e,t)}function a(e){if(Array.isArray(e)){for(var t=new Array(e.length),r=0;r=48&&t<=57))return!1;r++}return!0},r.escapePathComponent=c,r.unescapePathComponent=function(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")},r._getPathRecursive=u,r.getPath=function(e,t){if(e===t)return"/";var r=u(e,t);if(""===r)throw new Error("Object not found in root");return"/"+r},r.hasUndefined=function e(t){if(t===undefined)return!0;if(t)if(Array.isArray(t)){for(var r=0,n=t.length;rfast-json-patch"}],[1407,{"./commonjs/core.js":1404,"./commonjs/duplex.js":1405,"./commonjs/helpers.js":1406},function(){with(this)return function(){"use strict";return function(e,t,r){var n=e("./commonjs/core.js");Object.assign(r,n);var i=e("./commonjs/duplex.js");Object.assign(r,i);var s=e("./commonjs/helpers.js");r.JsonPatchError=s.PatchError,r.deepClone=s._deepClone,r.escapePathComponent=s.escapePathComponent,r.unescapePathComponent=s.unescapePathComponent}}},{package:"@metamask/smart-transactions-controller>fast-json-patch"}],[1408,{_process:5500},function(){with(this)return function(){"use strict";return function(e,t,r){(function(e){(function(){
+/**
+ * [js-sha3]{@link https://github.com/emn178/js-sha3}
+ *
+ * @version 0.5.5
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
+ * @copyright Chen, Yi-Cyuan 2015-2016
+ * @license MIT
+ */
+!function(r){"object"==typeof e&&e.versions&&e.versions.node&&(r=global);for(var n=!r.JS_SHA3_TEST&&"object"==typeof t&&t.exports,i="0123456789abcdef".split(""),s=[0,8,16,24],o=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],a=[224,256,384,512],c=["hex","buffer","arrayBuffer","array"],u=function(e,t,r){return function(n){return new y(e,t,e).update(n)[r]()}},l=function(e,t,r){return function(n,i){return new y(e,t,i).update(n)[r]()}},d=function(e,t){var r=u(e,t,"hex");r.create=function(){return new y(e,t,e)},r.update=function(e){return r.create().update(e)};for(var n=0;n>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}y.prototype.update=function(e){var t="string"!=typeof e;t&&e.constructor==r.ArrayBuffer&&(e=new Uint8Array(e));for(var n,i,o=e.length,a=this.blocks,c=this.byteCount,u=this.blockCount,l=0,d=this.s;l>2]|=e[l]<>2]|=i<>2]|=(192|i>>6)<>2]|=(128|63&i)<=57344?(a[n>>2]|=(224|i>>12)<>2]|=(128|i>>6&63)<>2]|=(128|63&i)<>2]|=(240|i>>18)<>2]|=(128|i>>12&63)<>2]|=(128|i>>6&63)<>2]|=(128|63&i)<=c){for(this.start=n-c,this.block=a[u],n=0;n>2]|=this.padding[3&t],this.lastByteIndex==this.byteCount)for(e[0]=e[r],t=1;t>4&15]+i[15&e]+i[e>>12&15]+i[e>>8&15]+i[e>>20&15]+i[e>>16&15]+i[e>>28&15]+i[e>>24&15];a%t==0&&(w(r),o=0)}return s&&(e=r[o],s>0&&(c+=i[e>>4&15]+i[15&e]),s>1&&(c+=i[e>>12&15]+i[e>>8&15]),s>2&&(c+=i[e>>20&15]+i[e>>16&15])),c},y.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&w(n)}return s&&(e=a<<2,t=n[o],s>0&&(c[e]=255&t),s>1&&(c[e+1]=t>>8&255),s>2&&(c[e+2]=t>>16&255)),c};var w=function(e){var t,r,n,i,s,a,c,u,l,d,h,f,p,m,g,v,y,w,b,P,E,k,_,M,S,C,T,A,j,x,O,I,R,N,D,B,F,L,$,q,U,H,G,z,V,K,W,Z,Q,J,Y,X,ee,te,re,ne,ie,se,oe,ae,ce,ue,le;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],a=e[2]^e[12]^e[22]^e[32]^e[42],c=e[3]^e[13]^e[23]^e[33]^e[43],u=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],d=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(f=e[8]^e[18]^e[28]^e[38]^e[48])^(a<<1|c>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(c<<1|a>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(u<<1|l>>>31),r=s^(l<<1|u>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=a^(d<<1|h>>>31),r=c^(h<<1|d>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=u^(f<<1|p>>>31),r=l^(p<<1|f>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=d^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,m=e[0],g=e[1],K=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,A=e[20]<<3|e[21]>>>29,j=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,H=e[40]<<18|e[41]>>>14,G=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,D=e[3]<<1|e[2]>>>31,v=e[13]<<12|e[12]>>>20,y=e[12]<<12|e[13]>>>20,Z=e[22]<<10|e[23]>>>22,Q=e[23]<<10|e[22]>>>22,x=e[33]<<13|e[32]>>>19,O=e[32]<<13|e[33]>>>19,ue=e[42]<<2|e[43]>>>30,le=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,B=e[14]<<6|e[15]>>>26,F=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,b=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,Y=e[35]<<15|e[34]>>>17,I=e[45]<<29|e[44]>>>3,R=e[44]<<29|e[45]>>>3,M=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,L=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,P=e[36]<<21|e[37]>>>11,E=e[37]<<21|e[36]>>>11,X=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,z=e[8]<<27|e[9]>>>5,V=e[9]<<27|e[8]>>>5,C=e[18]<<20|e[19]>>>12,T=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,U=e[39]<<8|e[38]>>>24,k=e[48]<<14|e[49]>>>18,_=e[49]<<14|e[48]>>>18,e[0]=m^~v&w,e[1]=g^~y&b,e[10]=M^~C&A,e[11]=S^~T&j,e[20]=N^~B&L,e[21]=D^~F&$,e[30]=z^~K&Z,e[31]=V^~W&Q,e[40]=te^~ne&se,e[41]=re^~ie&oe,e[2]=v^~w&P,e[3]=y^~b&E,e[12]=C^~A&x,e[13]=T^~j&O,e[22]=B^~L&q,e[23]=F^~$&U,e[32]=K^~Z&J,e[33]=W^~Q&Y,e[42]=ne^~se&ae,e[43]=ie^~oe&ce,e[4]=w^~P&k,e[5]=b^~E&_,e[14]=A^~x&I,e[15]=j^~O&R,e[24]=L^~q&H,e[25]=$^~U&G,e[34]=Z^~J&X,e[35]=Q^~Y&ee,e[44]=se^~ae&ue,e[45]=oe^~ce&le,e[6]=P^~k&m,e[7]=E^~_&g,e[16]=x^~I&M,e[17]=O^~R&S,e[26]=q^~H&N,e[27]=U^~G&D,e[36]=J^~X&z,e[37]=Y^~ee&V,e[46]=ae^~ue&te,e[47]=ce^~le&re,e[8]=k^~m&v,e[9]=_^~g&y,e[18]=I^~M&C,e[19]=R^~S&T,e[28]=H^~N&B,e[29]=G^~D&F,e[38]=X^~z&K,e[39]=ee^~V&W,e[48]=ue^~te&ne,e[49]=le^~re&ie,e[0]^=o[n],e[1]^=o[n+1]};if(n)t.exports=f;else if(r)for(var b in f)r[b]=f[b]}(this)}).call(this)}).call(this,e("_process"))}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>eth-method-registry>ethjs>js-sha3"}],[1409,{"./url-alphabet/index.cjs":1410},function(){with(this)return function(){"use strict";return function(e,t,r){let{urlAlphabet:n}=e("./url-alphabet/index.cjs"),i=e=>crypto.getRandomValues(new Uint8Array(e)),s=(e,t,r)=>{let n=(2<{let o="";for(;;){let t=r(i),a=i;for(;a--;)if(o+=e[t[a]&n]||"",o.length===s)return o}}};t.exports={nanoid:(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),customAlphabet:(e,t=21)=>s(e,t,i),customRandom:s,urlAlphabet:n,random:i}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>nanoid"}],[141,{lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash");var i={version:58,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=58;const r=t.data;return t.data=function(e){var t;return null===(t=e.AppStateController)||void 0===t||delete t.swapsWelcomeMessageHasBeenShown,e}(r),t}};r.default=i}}},{package:"$root$"}],[1410,{},function(){with(this)return function(){"use strict";return function(e,t,r){t.exports={urlAlphabet:"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"}}}},{package:"@metamask/smart-transactions-controller>@metamask/controllers>nanoid"}],[1411,{"./resource":1413,"./services":1419,"./snaps":1427,"./utils":1432},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e("./resource"),r),i(e("./services"),r),i(e("./snaps"),r),i(e("./utils"),r)}}},{package:"@metamask/snap-controllers"}],[1412,{"@metamask/obs-store":1494,"@metamask/safe-event-emitter":1319,"eth-rpc-errors":2537,nanoid:1538},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.ExternalResourceController=void 0;const i=e("@metamask/obs-store"),s=n(e("@metamask/safe-event-emitter")),o=e("eth-rpc-errors"),a=e("nanoid"),c=e=>`Not authorized to access resource with id "${e}".`;class u extends s.default{constructor({storageKey:e,requiredFields:t,initialResources:r}){super(),this.requiredFields=t,this.storageKey=e,this.store=new i.ObservableStore(((e,t)=>({[e]:t}))(e,r))}getResources(){return{...this.store.getState()[this.storageKey]}}setResources(e){this.store.updateState({[this.storageKey]:e})}clearResources(){this.setResources({})}deleteResourcesFor(e){const t=this.getResources(),r=Object.entries(t).reduce(((t,[r,n])=>(n.fromDomain!==e&&(t[r]=n),t)),{});this.setResources(r)}get(e,t){const r=this.getResources()[t];if(r&&r.fromDomain!==e)throw o.ethErrors.provider.unauthorized({message:c(t)});return r?{...r}:null}getAllResources(e){return Object.values(this.getResources()).filter((t=>t.fromDomain===e))}add(e,t){const r=this.processNewResource(e,t),{id:n}=r,i=this.getResources();if(i[n])throw new Error(`Resource with id "${n}" already exists.`);return i[n]=r,this.setResources(i),r.id}update(e,t){const{id:r}=t,n=this.getResources(),i=n[r];if(!i)throw o.ethErrors.rpc.resourceNotFound({message:`Resource with id "${r}" not found.`});if(i.fromDomain!==e)throw o.ethErrors.provider.unauthorized({message:c(r)});return n[r]=this.processNewResource(e,{...n[r],...t}),this.setResources(n),r}processNewResource(e,t){return this.requiredFields.forEach((r=>{if(!(r in t))throw o.ethErrors.rpc.invalidParams(`Resource from "${e}" missing required field: ${r}`)})),{...t,fromDomain:e,id:t.id||(0,a.nanoid)()}}delete(e,t){const r=this.getResources(),n=r[t];if(!n)throw o.ethErrors.rpc.invalidParams({message:`Resource with id "${t}" not found.`});if(n.fromDomain!==e)throw o.ethErrors.provider.unauthorized({message:c(t)});return delete r[t],this.setResources(r),null}handleRpcRequest(e,t,r){if(!e||"string"!=typeof e)throw new Error("Invalid fromDomain.");switch(t){case"get":return this.get(e,r);case"getAll":return this.getAllResources(e);case"add":return this.add(e,r);case"update":return this.update(e,r);case"delete":return this.delete(e,r);default:throw o.ethErrors.rpc.methodNotFound({message:`Not an asset method: ${t}`})}}}r.ExternalResourceController=u}}},{package:"@metamask/snap-controllers"}],[1413,{"./ExternalResourceController":1412},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e("./ExternalResourceController"),r)}}},{package:"@metamask/snap-controllers"}],[1414,{"../utils":1432,"@metamask/object-multiplex":1198,"@metamask/utils":1541,nanoid:1538,pump:5599},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.setupMultiplex=r.AbstractExecutionService=void 0;const i=n(e("@metamask/object-multiplex")),s=e("@metamask/utils"),o=e("nanoid"),a=n(e("pump")),c=e("../utils");r.AbstractExecutionService=class{constructor({setupSnapProvider:e,messenger:t,terminationTimeout:r=s.Duration.Second}){this._snapRpcHooks=new Map,this.jobs=new Map,this.setupSnapProvider=e,this.snapToJobMap=new Map,this.jobToSnapMap=new Map,this._messenger=t,this._terminationTimeout=r}async terminate(e){const t=this.jobs.get(e);if(!t)throw new Error(`Job with id "${e}" not found.`);const r=await(0,c.withTimeout)(this._command(e,{jsonrpc:"2.0",method:"terminate",params:[],id:(0,o.nanoid)()}),this._terminationTimeout);r!==c.hasTimedOut&&"OK"===r||console.error(`Job "${e}" failed to terminate gracefully.`,r),Object.values(t.streams).forEach((e=>{try{!e.destroyed&&e.destroy(),e.removeAllListeners()}catch(e){console.error("Error while destroying stream",e)}})),this._terminate(t),this._removeSnapAndJobMapping(e),this.jobs.delete(e),console.log(`Job "${e}" terminated.`)}async terminateSnap(e){const t=this.snapToJobMap.get(e);t&&await this.terminate(t)}async terminateAllSnaps(){await Promise.all([...this.jobs.keys()].map((e=>this.terminate(e)))),this._snapRpcHooks.clear()}async getRpcMessageHandler(e){return this._snapRpcHooks.get(e)}async executeSnap(e){if(this.snapToJobMap.has(e.snapId))throw new Error(`Snap "${e.snapId}" is already being executed.`);const t=await this._initJob();this._mapSnapAndJob(e.snapId,t.id),await this._command(t.id,{jsonrpc:"2.0",method:"ping",id:(0,o.nanoid)()}),this.setupSnapProvider(e.snapId,t.streams.rpc);const r=await this._command(t.id,{jsonrpc:"2.0",method:"executeSnap",params:e,id:(0,o.nanoid)()});return this._createSnapHooks(e.snapId,t.id),r}async _command(e,t){if("object"!=typeof t)throw new Error("Must send object.");const r=this.jobs.get(e);if(!r)throw new Error(`Job with id "${e}" not found.`);console.log("Parent: Sending Command",t);const n=await r.rpcEngine.handle(t);if(n.error)throw new Error(n.error.message);return n.result}_removeSnapHooks(e){this._snapRpcHooks.delete(e)}_createSnapHooks(e,t){this._snapRpcHooks.set(e,(async(r,n)=>await this._command(t,{id:(0,o.nanoid)(),jsonrpc:"2.0",method:"snapRpc",params:{origin:r,request:n,target:e}})))}_getJobForSnap(e){return this.snapToJobMap.get(e)}_getSnapForJob(e){return this.jobToSnapMap.get(e)}_mapSnapAndJob(e,t){this.snapToJobMap.set(e,t),this.jobToSnapMap.set(t,e)}_removeSnapAndJobMapping(e){const t=this.jobToSnapMap.get(e);if(!t)throw new Error(`job: "${e}" has no mapped snap.`);this.jobToSnapMap.delete(e),this.snapToJobMap.delete(t),this._removeSnapHooks(t)}},r.setupMultiplex=function(e,t){const r=new i.default;return(0,a.default)(e,r,e,(e=>{e&&(t?console.error(`"${t}" stream failure.`,e):console.error(e))})),r}}}},{package:"@metamask/snap-controllers"}],[1415,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0})}}},{package:"@metamask/snap-controllers"}],[1416,{"./AbstractExecutionService":1414,"@metamask/execution-environments":1170,"@metamask/obs-store":1494,"@metamask/post-message-stream":1212,"json-rpc-engine":4837,"json-rpc-middleware-stream":1537,nanoid:1538,pump:5599},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.WebWorkerExecutionService=void 0;const i=e("@metamask/obs-store"),s=e("@metamask/post-message-stream"),o=e("@metamask/execution-environments"),a=e("json-rpc-engine"),c=e("json-rpc-middleware-stream"),u=e("nanoid"),l=n(e("pump")),d=e("./AbstractExecutionService");class h extends d.AbstractExecutionService{constructor({setupSnapProvider:e,workerUrl:t,messenger:r}){super({setupSnapProvider:e,messenger:r}),this.workerUrl=t,this.store=new i.ObservableStore({workers:{}})}_setWorker(e,t){this.jobs.set(e,t);const r={...this.store.getState().workers,[e]:t};this.store.updateState({workers:r})}_deleteWorker(e){const t={...this.store.getState().workers};delete t[e],this.store.updateState({workers:t})}_terminate(e){e.worker.terminate(),this._deleteWorker(e.id)}async _initJob(){const e=(0,u.nanoid)(),t=new Worker(this.workerUrl,{name:e});t.addEventListener("error",(t=>{if(this._messenger){const r=this.jobToSnapMap.get(e);r&&this._messenger.publish("ExecutionService:unhandledError",r,{code:t.error.code,message:t.error.message,data:t.error.data})}}),{once:!0});const r=this._initWorkerStreams(t,e),n=new a.JsonRpcEngine,i=(0,c.createStreamMiddleware)();(0,l.default)(i.stream,r.command,i.stream),n.push(i.middleware);const s={id:e,streams:r,rpcEngine:n,worker:t};return this._setWorker(e,s),await this._command(e,{jsonrpc:"2.0",method:"ping",id:(0,u.nanoid)()}),s}_initWorkerStreams(e,t){const r=new s.WorkerParentPostMessageStream({worker:e}),n=(0,d.setupMultiplex)(r,`Worker:${t}`);return{command:n.createStream(o.SNAP_STREAM_NAMES.COMMAND),rpc:n.createStream(o.SNAP_STREAM_NAMES.JSON_RPC),_connection:r}}}r.WebWorkerExecutionService=h}}},{package:"@metamask/snap-controllers"}],[1417,{"../AbstractExecutionService":1414,"@metamask/execution-environments":1170,"@metamask/post-message-stream":1212,"json-rpc-engine":4837,"json-rpc-middleware-stream":1537,nanoid:1538,pump:5599},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.IframeExecutionService=void 0;const i=e("@metamask/post-message-stream"),s=e("@metamask/execution-environments"),o=e("json-rpc-engine"),a=e("json-rpc-middleware-stream"),c=e("nanoid"),u=n(e("pump")),l=e("../AbstractExecutionService");class d extends l.AbstractExecutionService{constructor({setupSnapProvider:e,iframeUrl:t,messenger:r}){super({setupSnapProvider:e,messenger:r}),this.iframeUrl=t}_terminate(e){document.getElementById(e.id)?.remove()}async _initJob(){const e=(0,c.nanoid)(),t=await this._initStreams(e),r=new o.JsonRpcEngine,n=(0,a.createStreamMiddleware)();(0,u.default)(n.stream,t.command,n.stream),r.push(n.middleware);const i={id:e,streams:t,rpcEngine:r};return this.jobs.set(e,i),i}async _initStreams(e){this._iframeWindow=await this._createWindow(this.iframeUrl.toString(),e);const t=new i.WindowPostMessageStream({name:"parent",target:"child",targetWindow:this._iframeWindow}),r=(0,l.setupMultiplex)(t,`Job: "${e}"`),n=r.createStream(s.SNAP_STREAM_NAMES.COMMAND),o=t=>{if(t.error&&(null===t.id||t.id===undefined)){const r=this.jobToSnapMap.get(e);r&&this._messenger.publish("ExecutionService:unhandledError",r,t.error),n.removeListener("data",o)}};n.on("data",o);const a=r.createStream(s.SNAP_STREAM_NAMES.JSON_RPC);return{command:n,rpc:a,_connection:t}}_createWindow(e,t){return new Promise(((r,n)=>{const i=document.createElement("iframe");i.setAttribute("id",t),i.setAttribute("src",e),document.body.appendChild(i),i.addEventListener("load",(()=>{i.contentWindow?r(i.contentWindow):n(new Error(`iframe.contentWindow not present on load for job "${t}".`))})),i.setAttribute("sandbox","allow-scripts")}))}}r.IframeExecutionService=d}}},{package:"@metamask/snap-controllers"}],[1418,{"./IframeExecutionService":1417},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e("./IframeExecutionService"),r)}}},{package:"@metamask/snap-controllers"}],[1419,{"./AbstractExecutionService":1414,"./ExecutionService":1415,"./WebWorkerExecutionService":1416,"./iframe":1418},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e("./AbstractExecutionService"),r),i(e("./ExecutionService"),r),i(e("./WebWorkerExecutionService"),r),i(e("./iframe"),r)}}},{package:"@metamask/snap-controllers"}],[142,{"../../../shared/constants/transaction":6272,lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash"),i=e("../../../shared/constants/transaction");var s={version:59,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=59;const r=t.data;return t.data=function(e){var t;const r=null==e||null===(t=e.TransactionController)||void 0===t?void 0:t.transactions;if((0,n.isPlainObject)(r)){const t=(0,n.groupBy)(Object.values(r),(e=>{var t,r;return`${null===(t=e.txParams)||void 0===t?void 0:t.nonce}-${null!==(r=e.chainId)&&void 0!==r?r:e.metamaskNetworkId}`})),s=(0,n.pickBy)(t,(e=>e.some((e=>e.type!==i.TRANSACTION_TYPES.CANCEL&&e.type!==i.TRANSACTION_TYPES.RETRY))));e.TransactionController.transactions=(0,n.keyBy)((0,n.concat)(...Object.values(s)),(e=>e.id))}return e}(r),t}};r.default=s}}},{package:"$root$"}],[1420,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.RequestQueue=void 0;r.RequestQueue=class{constructor(e){this.maxQueueSize=e,this.queueSizes=new Map}increment(e){const t=this.queueSizes.get(e)??0;if(t>=this.maxQueueSize)throw new Error("Maximum number of requests reached. Try again later.");this.queueSizes.set(e,t+1)}decrement(e){const t=this.queueSizes.get(e)??0;if(0===t)throw new Error(`Cannot decrement, ${e} does not have any outstanding requests.`);this.queueSizes.set(e,t-1)}get(e){return this.queueSizes.get(e)??0}}}}},{package:"@metamask/snap-controllers"}],[1421,{"..":1411,"../utils":1432,"./RequestQueue":1420,"./default-endowments":1422,"./endowments":1424,"./json-schemas":1428,"./utils":1431,"@metamask/browser-passworder":1027,"@metamask/controllers":1464,"@metamask/utils":1541,"eth-rpc-errors":2537,nanoid:1538},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.SnapController=r.SnapStatusEvent=r.SnapStatus=r.AppKeyType=r.SNAP_APPROVAL_UPDATE=r.SNAP_PREFIX_REGEX=r.controllerName=void 0;const i=e("@metamask/controllers"),s=e("@metamask/utils"),o=n(e("@metamask/browser-passworder")),a=e("eth-rpc-errors"),c=e("nanoid"),u=e(".."),l=e("../utils"),d=e("./default-endowments"),h=e("./endowments"),f=e("./json-schemas"),p=e("./RequestQueue"),m=e("./utils");r.controllerName="SnapController",r.SNAP_PREFIX_REGEX=new RegExp(`^${m.SNAP_PREFIX}`,"u"),r.SNAP_APPROVAL_UPDATE="wallet_updateSnap";const g=new Set(["initialPermissions","id","permissionName","version"]);var v;!function(e){e.stateEncryption="stateEncryption"}(v=r.AppKeyType||(r.AppKeyType={}));const y={snapErrors:{},snaps:{},snapStates:{}};var w,b;!function(e){e.installing="installing",e.running="running",e.stopped="stopped",e.crashed="crashed"}(w=r.SnapStatus||(r.SnapStatus={})),function(e){e.start="start",e.stop="stop",e.crash="crash",e.update="update"}(b=r.SnapStatusEvent||(r.SnapStatusEvent={}));const P=e=>e.enabled,E={initial:w.installing,states:{[w.installing]:{on:{[b.start]:{target:w.running,cond:P}}},[w.running]:{on:{[b.stop]:w.stopped,[b.crash]:w.crashed}},[w.stopped]:{on:{[b.start]:{target:w.running,cond:P},[b.update]:w.installing}},[w.crashed]:{on:{[b.start]:{target:w.running,cond:P}}}}};class k extends i.BaseControllerV2{constructor({closeAllConnections:e,executeSnap:t,getRpcMessageHandler:r,messenger:n,state:i,terminateAllSnaps:o,terminateSnap:a,getAppKey:c,environmentEndowmentPermissions:u=[],npmRegistryUrl:l,idleTimeCheckInterval:d=(0,s.inMilliseconds)(5,s.Duration.Second),maxIdleTime:h=(0,s.inMilliseconds)(30,s.Duration.Second),maxRequestTime:f=(0,s.inMilliseconds)(60,s.Duration.Second),fetchFunction:p=globalThis.fetch.bind(globalThis),featureFlags:m={}}){super({messenger:n,metadata:{snapErrors:{persist:!1,anonymous:!1},snapStates:{persist:!0,anonymous:!1},snaps:{persist:e=>Object.values(e).map((e=>({...e,status:w.stopped}))).reduce(((e,t)=>(e[t.id]=t,e)),{}),anonymous:!1}},name:"SnapController",state:{...y,...i}}),this._closeAllConnections=e,this._environmentEndowmentPermissions=u,this._executeSnap=t,this._getRpcMessageHandler=r,this._onUnhandledSnapError=this._onUnhandledSnapError.bind(this),this._terminateSnap=a,this._terminateAllSnaps=o,this._getAppKey=c,this._idleTimeCheckInterval=d,this._maxIdleTime=h,this._maxRequestTime=f,this._pollForLastRequestStatus(),this._snapsRuntimeData=new Map,this._npmRegistryUrl=l,this._fetchFunction=p,this._featureFlags=m,this.messagingSystem.subscribe("ExecutionService:unhandledError",this._onUnhandledSnapError),this.registerMessageHandlers()}registerMessageHandlers(){this.messagingSystem.registerActionHandler(`${r.controllerName}:add`,((...e)=>this.add(...e))),this.messagingSystem.registerActionHandler(`${r.controllerName}:get`,((...e)=>this.get(...e))),this.messagingSystem.registerActionHandler(`${r.controllerName}:getRpcMessageHandler`,((...e)=>this.getRpcMessageHandler(...e))),this.messagingSystem.registerActionHandler(`${r.controllerName}:getSnapState`,((...e)=>this.getSnapState(...e))),this.messagingSystem.registerActionHandler(`${r.controllerName}:has`,((...e)=>this.has(...e))),this.messagingSystem.registerActionHandler(`${r.controllerName}:updateSnapState`,((...e)=>this.updateSnapState(...e))),this.messagingSystem.registerActionHandler(`${r.controllerName}:clearSnapState`,((...e)=>this.clearSnapState(...e)))}_pollForLastRequestStatus(){this._timeoutForLastRequestStatus=setTimeout((async()=>{await this._stopSnapsLastRequestPastMax(),this._pollForLastRequestStatus()}),this._idleTimeCheckInterval)}async _stopSnapsLastRequestPastMax(){const e=[...this._snapsRuntimeData.entries()];return Promise.all(e.filter((([e,t])=>0===t.pendingRequests&&t.lastRequest&&this._maxIdleTime&&(0,s.timeSince)(t.lastRequest)>this._maxIdleTime)).map((([e])=>this.stopSnap(e,b.stop))))}async _onUnhandledSnapError(e,t){await this.stopSnap(e,b.crash),this.addSnapError(t)}_transitionSnapState(e,t){const r=this.state.snaps[e].status;let n=E.states[r].on[t]??r;if(n.cond){if(!1===n.cond(this.state.snaps[e]))throw new Error(`Condition failed for state transition "${e}" with event "${t}".`)}n.target&&(n=n.target),n!==r&&this.update((t=>{t.snaps[e].status=n}))}async startSnap(e){const t=this.get(e);if(!t)throw new Error(`Snap "${e}" not found.`);if(!1===this.state.snaps[e].enabled)throw new Error(`Snap "${e}" is disabled.`);await this._startSnap({snapId:e,sourceCode:t.sourceCode})}enableSnap(e){this.update((t=>{t.snaps[e].enabled=!0}))}disableSnap(e){return this.update((t=>{if(!t.snaps[e])throw new Error(`Snap "${e}" not found.`);t.snaps[e].enabled=!1})),this.isRunning(e)?this.stopSnap(e,b.stop):Promise.resolve()}async stopSnap(e,t=b.stop){const r=this._getSnapRuntimeData(e);if(r){r.lastRequest=null,r.pendingRequests=0;try{this.isRunning(e)&&(this._closeAllConnections(e),await this.terminateSnap(e))}finally{this.isRunning(e)&&this._transitionSnapState(e,t)}}}async terminateSnap(e){await this._terminateSnap(e),this.messagingSystem.publish("SnapController:snapTerminated",e)}isRunning(e){const t=this.get(e);if(!t)throw new Error(`Snap "${e}" not found.`);return t.status===w.running}has(e){return Boolean(this.get(e))}get(e){return this.state.snaps[e]}getTruncated(e){const t=this.get(e);return t?Object.keys(t).reduce(((e,r)=>(g.has(r)&&(e[r]=t[r]),e)),{}):null}async updateSnapState(e,t){const r=await this.encryptSnapState(e,t);this.update((t=>{t.snapStates[e]=r}))}async clearSnapState(e){this.update((t=>{delete t.snapStates[e]}))}addSnapError(e){this.update((t=>{const r=(0,c.nanoid)();t.snapErrors[r]={...e,internalID:r}}))}async removeSnapError(e){this.update((t=>{delete t.snapErrors[e]}))}async clearSnapErrors(){this.update((e=>{e.snapErrors={}}))}async getSnapState(e){const t=this.state.snapStates[e];return t?this.decryptSnapState(e,t):null}async getEncryptionKey(e){return this._getAppKey(e,v.stateEncryption)}async encryptSnapState(e,t){const r=await this.getEncryptionKey(e);return o.default.encrypt(r,t)}async decryptSnapState(e,t){const r=await this.getEncryptionKey(e);try{return await o.default.decrypt(r,t)}catch(e){throw new Error("Failed to decrypt snap state, the state must be corrupted.")}}clearState(){const e=Object.keys(this.state.snaps);e.forEach((e=>{this._closeAllConnections(e)})),this._terminateAllSnaps(),e.forEach(this.revokeAllSnapPermissions),this.update((e=>{e.snaps={},e.snapStates={}}))}async removeSnap(e){return this.removeSnaps([e])}async removeSnaps(e){if(!Array.isArray(e))throw new Error("Expected array of snap ids.");await Promise.all(e.map((async e=>{await this.disableSnap(e),this.revokeAllSnapPermissions(e);const t=(0,m.getSnapPermissionName)(e);this.messagingSystem.call("PermissionController:revokePermissionForAllSubjects",t),this._snapsRuntimeData.delete(e),this.update((t=>{delete t.snaps[e],delete t.snapStates[e]})),this.messagingSystem.publish("SnapController:snapRemoved",e)})))}revokeAllSnapPermissions(e){this.messagingSystem.call("PermissionController:hasPermissions",e)&&this.messagingSystem.call("PermissionController:revokeAllPermissions",e)}getPermittedSnaps(e){return Object.values(this.messagingSystem.call("PermissionController:getPermissions",e)??{}).reduce(((e,t)=>{if(t.parentCapability.startsWith(m.SNAP_PREFIX)){const n=t.parentCapability.replace(r.SNAP_PREFIX_REGEX,""),i=this.getTruncated(n);e[n]=i||{error:(0,a.serializeError)(new Error("Snap permitted but not installed."))}}return e}),{})}async installSnaps(e,t){const r={};return await Promise.all(Object.entries(t).map((async([t,{version:n}])=>{const i=(0,m.resolveVersion)(n),s=(0,m.getSnapPermissionName)(t);(0,m.isValidSnapVersionRange)(i)?this.messagingSystem.call("PermissionController:hasPermission",e,s)?r[t]={...await this.processRequestedSnap(e,t,i)}:r[t]={error:a.ethErrors.provider.unauthorized(`Not authorized to install snap "${t}". Request the permission for the snap before attempting to install it.`)}:r[t]={error:a.ethErrors.rpc.invalidParams(`The "version" field must be a valid SemVer version range if specified. Received: "${i}".`)}}))),r}async processRequestedSnap(e,t,r){try{this.validateSnapId(t)}catch(e){return{error:a.ethErrors.rpc.invalidParams(`"${t}" is not a valid snap id.`)}}const n=t,i=this.getTruncated(n);if(i&&(0,m.getSnapPrefix)(n)!==m.SnapIdPrefixes.local){if((0,m.satifiesVersionRange)(i.version,r))return i;if(!0!==this._featureFlags.dappsCanUpdateSnaps)return{error:a.ethErrors.rpc.invalidParams(`Version mismatch with already installed snap. ${n}@${i.version} doesn't satisfy requested version ${r}`)};try{const t=await this.updateSnap(e,n,r);return null===t?{error:a.ethErrors.rpc.invalidParams(`Snap "${n}@${i.version}" is already installed, couldn't update to a version inside requested "${r}" range.`)}:t}catch(e){return{error:(0,a.serializeError)(e)}}}i&&this.isRunning(n)&&await this.stopSnap(n,b.stop);try{const{sourceCode:t}=await this.add({origin:e,id:n,versionRange:r});return await this.authorize(n),await this._startSnap({snapId:n,sourceCode:t}),this.messagingSystem.publish("SnapController:snapInstalled",n),this.getTruncated(n)}catch(e){return console.error("Error when adding snap.",e),this.has(n)&&this.removeSnap(n),{error:(0,a.serializeError)(e)}}}async updateSnap(e,t,n=m.DEFAULT_REQUESTED_SNAP_VERSION){const i=this.get(t);if(i===undefined)throw new Error(`Could not find snap ${t}. Install the snap before attempting to update it.`);if(!(0,m.isValidSnapVersionRange)(n))throw new Error(`Received invalid Snap version range: "${n}".`);const o=await this._fetchSnap(t,n);if(!(0,m.gtVersion)(o.manifest.version,i.version))return console.warn(`Tried updating snap "${t}" within "${n}" version range, but newer version "${i.version}" is already installed`),null;const{newPermissions:a,unusedPermissions:c,approvedPermissions:u}=await this.calculatePermissionsChange(t,o.manifest.initialPermissions);if(!await this.messagingSystem.call("ApprovalController:addRequest",{origin:e,type:r.SNAP_APPROVAL_UPDATE,requestData:{snapId:t,newVersion:o.manifest.version,newPermissions:a,approvedPermissions:u}},!0))return null;this.isRunning(t)&&await this.stopSnap(t,b.stop),this._transitionSnapState(t,b.update),await this._set({origin:e,id:t,manifest:o.manifest,sourceCode:o.sourceCode,versionRange:n});const l=Object.keys(c);return(0,s.isNonEmptyArray)(l)&&this.messagingSystem.call("PermissionController:revokePermissions",{[t]:l}),(0,s.isNonEmptyArray)(Object.keys(a))&&this.messagingSystem.call("PermissionController:grantPermissions",{approvedPermissions:a,subject:{origin:t}}),await this._startSnap({snapId:t,sourceCode:o.sourceCode}),this.messagingSystem.publish("SnapController:snapUpdated",t,o.manifest.version,i.version),this.getTruncated(t)}async add(e){const{id:t}=e;this.validateSnapId(t);const r=t;if(!e||!("origin"in e)||!("id"in e)||!("manifest"in e)&&"sourceCode"in e||"manifest"in e&&!("sourceCode"in e))throw new Error(`Invalid add snap args for snap "${r}".`);const n=this._getSnapRuntimeData(r);n.installPromise||(console.info(`Adding snap: ${r}`),n.installPromise=this._set(e));try{return await n.installPromise}catch(e){throw n.installPromise=null,e}}validateSnapId(e){if(!e||"string"!=typeof e)throw new Error(`Invalid snap id: Not a string. Received "${e}"`);for(const t of Object.values(m.SnapIdPrefixes))if(e.startsWith(t)&&e.replace(t,"").length>0)return;throw new Error(`Invalid snap id. Received: "${e}"`)}async _startSnap(e){const{snapId:t}=e;if(this.isRunning(t))throw new Error(`Snap "${t}" is already started.`);try{const r=await this._executeWithTimeout(t,this._executeSnap({...e,endowments:await this._getEndowments(t)}));return this._transitionSnapState(t,b.start),r}catch(e){throw await this.terminateSnap(t),e}}async _getEndowments(e){let t=[];for(const r of this._environmentEndowmentPermissions)if(this.messagingSystem.call("PermissionController:hasPermission",e,r)){const n=await this.messagingSystem.call("PermissionController:getEndowments",e,r);if(n){if(!Array.isArray(n)||n.some((e=>"string"!=typeof e)))throw new Error("Expected an array of string endowment names.");t=t.concat(n)}}const r=[...new Set([...d.DEFAULT_ENDOWMENTS,...t])];return r.length{e.snaps[t]=d})),this.messagingSystem.publish("SnapController:snapAdded",t,d,o),d}async _fetchSnap(e,t=m.DEFAULT_REQUESTED_SNAP_VERSION){try{const r=(0,m.getSnapPrefix)(e);switch(r){case m.SnapIdPrefixes.local:return this._fetchLocalSnap(e.replace(m.SnapIdPrefixes.local,""));case m.SnapIdPrefixes.npm:return this._fetchNpmSnap(e.replace(m.SnapIdPrefixes.npm,""),t);default:return(0,u.assertExhaustive)(r)}}catch(t){throw new Error(`Failed to fetch Snap "${e}": ${t.message}`)}}async _fetchNpmSnap(e,t){if(!(0,m.isValidSnapVersionRange)(t))throw new Error(`Received invalid Snap version range: "${t}".`);const{manifest:r,sourceCode:n,svgIcon:i}=await(0,m.fetchNpmSnap)(e,t,this._npmRegistryUrl,this._fetchFunction);return{manifest:r,sourceCode:n,svgIcon:i}}async _fetchLocalSnap(e){const t={cache:"no-cache"},r=new URL(m.NpmSnapFileNames.Manifest,e);if(!m.LOCALHOST_HOSTNAMES.has(r.hostname))throw new Error(`Invalid URL: Locally hosted Snaps must be hosted on localhost. Received URL: "${r.toString()}"`);const n=await(await this._fetchFunction(r.toString(),t)).json();(0,f.validateSnapJsonFile)(m.NpmSnapFileNames.Manifest,n);const i=n,{source:{location:{npm:{filePath:s,iconPath:o}}}}=i,[a,c]=await Promise.all([(await this._fetchFunction(new URL(s,e).toString(),t)).text(),o?(await this._fetchFunction(new URL(o,e).toString(),t)).text():undefined]);return(0,m.validateSnapShasum)(i,a),{manifest:i,sourceCode:a,svgIcon:c}}async authorize(e){console.info(`Authorizing snap: ${e}`);const t=this.state.snaps[e],{initialPermissions:r}=t;try{const{newPermissions:t,unusedPermissions:n}=await this.calculatePermissionsChange(e,r),i=Object.keys(n);if((0,s.isNonEmptyArray)(i)&&this.messagingSystem.call("PermissionController:revokePermissions",{[e]:i}),(0,s.isNonEmptyArray)(Object.keys(t))){const[r]=await this.messagingSystem.call("PermissionController:requestPermissions",{origin:e},t);return Object.values(r).map((e=>e.parentCapability))}return[]}finally{this._getSnapRuntimeData(e).installPromise=null}}destroy(){super.destroy(),this._timeoutForLastRequestStatus&&clearTimeout(this._timeoutForLastRequestStatus),this.messagingSystem.unsubscribe("ExecutionService:unhandledError",this._onUnhandledSnapError)}async getRpcMessageHandler(e){const t=this._getSnapRuntimeData(e),r=t?.rpcHandler;if(r)return r;const n=new p.RequestQueue(5),i=new Map,o=async(t,r)=>{if(!1===this.state.snaps[e].enabled)throw new Error(`Snap "${e}" is disabled.`);if(this.state.snaps[e].status===w.installing)throw new Error(`Snap "${e}" is currently being installed. Please try again later.`);let o=await this._getRpcMessageHandler(e);if(!1===this.isRunning(e)){if(o)throw new Error("This snap should not have a handler in its current state. This is a bug, please report it.");let r=i.get(e);if(r){if(n.get(t)>=n.maxQueueSize)throw new Error("Exceeds maximum number of requests waiting to be resolved, please try again.")}else r=this.startSnap(e),i.set(e,r);n.increment(t);try{await r}finally{n.decrement(t),i.get(e)===r&&i.delete(e)}o=await this._getRpcMessageHandler(e)}if(!o)throw new Error(`Snap execution service returned no RPC handler for running snap "${e}".`);let c=r;if((0,s.hasProperty)(r,"jsonrpc")){if("2.0"!==r.jsonrpc)throw a.ethErrors.rpc.invalidRequest({message:'Invalid "jsonrpc" property. Must be "2.0" if provided.',data:r.jsonrpc})}else c={...r,jsonrpc:"2.0"};this._recordSnapRpcRequestStart(e);try{const r=await this._executeWithTimeout(e,o(t,c));return this._recordSnapRpcRequestFinish(e),r}catch(t){throw await this.stopSnap(e,b.crash),t}};return t.rpcHandler=o,o}async _executeWithTimeout(e,t){if(this.messagingSystem.call("PermissionController:hasPermission",e,h.LONG_RUNNING_PERMISSION))return t;const r=await(0,l.withTimeout)(t,this._maxRequestTime);if(r===l.hasTimedOut)throw new Error("The request timed out.");return r}_recordSnapRpcRequestStart(e){const t=this._getSnapRuntimeData(e);t.pendingRequests+=1,t.lastRequest=null}_recordSnapRpcRequestFinish(e){const t=this._getSnapRuntimeData(e);t.pendingRequests-=1,0===t.pendingRequests&&(t.lastRequest=Date.now())}_getSnapRuntimeData(e){return this._snapsRuntimeData.has(e)||this._snapsRuntimeData.set(e,{lastRequest:null,rpcHandler:null,installPromise:null,pendingRequests:0}),this._snapsRuntimeData.get(e)}async calculatePermissionsChange(e,t){const r=await this.messagingSystem.call("PermissionController:getPermissions",e)??{},n=(0,l.setDiff)(t,r),i=(0,l.setDiff)(r,t);return{newPermissions:n,unusedPermissions:i,approvedPermissions:(0,l.setDiff)(r,i)}}}r.SnapController=k}}},{package:"@metamask/snap-controllers"}],[1422,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.DEFAULT_ENDOWMENTS=void 0,r.DEFAULT_ENDOWMENTS=Object.freeze(["atob","btoa","BigInt","Buffer","console","crypto","Date","Math","setTimeout","clearTimeout","SubtleCrypto","TextDecoder","TextEncoder","URL","WebAssembly","setInterval","clearInterval"])}}},{package:"@metamask/snap-controllers"}],[1423,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.LONG_RUNNING_PERMISSION=void 0,r.LONG_RUNNING_PERMISSION="endowment:long-running"}}},{package:"@metamask/snap-controllers"}],[1424,{"./constants":1423,"./long-running":1425,"./network-access":1426},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.endowmentPermissionBuilders=void 0;const s=e("./long-running"),o=e("./network-access");r.endowmentPermissionBuilders={[o.networkAccessEndowmentBuilder.targetKey]:o.networkAccessEndowmentBuilder,[s.longRunningEndowmentBuilder.targetKey]:s.longRunningEndowmentBuilder},i(e("./constants"),r)}}},{package:"@metamask/snap-controllers"}],[1425,{"./constants":1423,"@metamask/controllers":1464},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.longRunningEndowmentBuilder=void 0;const n=e("@metamask/controllers"),i=e("./constants").LONG_RUNNING_PERMISSION;r.longRunningEndowmentBuilder=Object.freeze({targetKey:i,specificationBuilder:e=>({permissionType:n.PermissionType.Endowment,targetKey:i,allowedCaveats:null,endowmentGetter:e=>undefined})})}}},{package:"@metamask/snap-controllers"}],[1426,{"@metamask/controllers":1464},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.networkAccessEndowmentBuilder=void 0;const n=e("@metamask/controllers"),i="endowment:network-access";r.networkAccessEndowmentBuilder=Object.freeze({targetKey:i,specificationBuilder:e=>({permissionType:n.PermissionType.Endowment,targetKey:i,allowedCaveats:null,endowmentGetter:e=>["fetch","WebSocket"]})})}}},{package:"@metamask/snap-controllers"}],[1427,{"./SnapController":1421,"./default-endowments":1422,"./endowments":1424,"./json-schemas":1428,"./utils":1431},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e("./SnapController"),r),i(e("./json-schemas"),r),i(e("./utils"),r),i(e("./default-endowments"),r),i(e("./endowments"),r)}}},{package:"@metamask/snap-controllers"}],[1428,{"../utils":1431,"./validateNpmSnapPackageJson.js":1429,"./validateSnapManifest.js":1430},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.validateSnapJsonFile=void 0;const i=n(e("./validateNpmSnapPackageJson.js")),s=n(e("./validateSnapManifest.js")),o=e("../utils");r.validateSnapJsonFile=function(e,t){let r;switch(e){case o.NpmSnapFileNames.Manifest:t&&"object"==typeof t&&!Array.isArray(t)&&t.repository===undefined&&(t.repository=null),r=(0,s.default)(t);break;case o.NpmSnapFileNames.PackageJson:r=(0,i.default)(t);break;default:throw new Error(`Unrecognized file name "${e}".`)}if(r&&0!==r.length)throw new Error(`${r.reduce(((e,t={})=>{const{instancePath:r,message:n="unknown error"}=t;return`${e}${r?`\t${r}\n\t${n}\n\n`:`\t${n}\n\n`}`}),"").replace(/\n$/u,"")}`)}}}},{package:"@metamask/snap-controllers"}],[1429,{"ajv/dist/runtime/equal":1496,"ajv/dist/runtime/ucs2length":1497},function(){with(this)return function(){"use strict";return function(e,t,r){t.exports=a,t.exports.default=a;const n={title:"npm Snap package.json",type:"object",required:["version","name"],properties:{version:{type:"string",title:"Version",pattern:"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"},name:{type:"string",title:"Package Name",minLength:1,maxLength:214,pattern:"^(?:@[a-z0-9-*~][a-z0-9-*._~]*/)?[a-z0-9-~][a-z0-9-._~]*$"},private:{type:"boolean",title:"Private"},main:{type:"string",title:"Main",minLength:1},publishConfig:{type:"object",title:"Publish Config",required:["registry"],properties:{access:{type:"string",minLength:1},registry:{type:"string",enum:["https://registry.npmjs.org","https://registry.npmjs.org/"]}}},repository:{type:"object",title:"Repository",additionalProperties:!1,required:["type","url"],properties:{type:{type:"string",minLength:1},url:{type:"string",minLength:1}}}}},i=new RegExp("^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$","u"),s=new RegExp("^(?:@[a-z0-9-*~][a-z0-9-*._~]*/)?[a-z0-9-~][a-z0-9-._~]*$","u"),o=e("ajv/dist/runtime/ucs2length").default;e("ajv/dist/runtime/equal").default;function a(e,{instancePath:t="",parentData:r,parentDataProperty:c,rootData:u=e}={}){let l=null;if(e&&"object"==typeof e&&!Array.isArray(e)){if(e.version===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property '"+"version"+"'"};null===l?l=[e]:l.push(e)}if(e.name===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property '"+"name"+"'"};null===l?l=[e]:l.push(e)}if(e.version!==undefined){let r=e.version;if("string"==typeof r){if(!i.test(r)){const e={instancePath:t+"/version",schemaPath:"#/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"},message:'must match pattern "'+"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"+'"'};null===l?l=[e]:l.push(e)}}else{const e={instancePath:t+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};null===l?l=[e]:l.push(e)}}if(e.name!==undefined){let r=e.name;if("string"==typeof r){if(o(r)>214){const e={instancePath:t+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:214},message:"must NOT have more than 214 characters"};null===l?l=[e]:l.push(e)}if(o(r)<1){const e={instancePath:t+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===l?l=[e]:l.push(e)}if(!s.test(r)){const e={instancePath:t+"/name",schemaPath:"#/properties/name/pattern",keyword:"pattern",params:{pattern:"^(?:@[a-z0-9-*~][a-z0-9-*._~]*/)?[a-z0-9-~][a-z0-9-._~]*$"},message:'must match pattern "'+"^(?:@[a-z0-9-*~][a-z0-9-*._~]*/)?[a-z0-9-~][a-z0-9-._~]*$"+'"'};null===l?l=[e]:l.push(e)}}else{const e={instancePath:t+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};null===l?l=[e]:l.push(e)}}if(e.private!==undefined&&"boolean"!=typeof e.private){const e={instancePath:t+"/private",schemaPath:"#/properties/private/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};null===l?l=[e]:l.push(e)}if(e.main!==undefined){let r=e.main;if("string"==typeof r){if(o(r)<1){const e={instancePath:t+"/main",schemaPath:"#/properties/main/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===l?l=[e]:l.push(e)}}else{const e={instancePath:t+"/main",schemaPath:"#/properties/main/type",keyword:"type",params:{type:"string"},message:"must be string"};null===l?l=[e]:l.push(e)}}if(e.publishConfig!==undefined){let r=e.publishConfig;if(r&&"object"==typeof r&&!Array.isArray(r)){if(r.registry===undefined){const e={instancePath:t+"/publishConfig",schemaPath:"#/properties/publishConfig/required",keyword:"required",params:{missingProperty:"registry"},message:"must have required property '"+"registry"+"'"};null===l?l=[e]:l.push(e)}if(r.access!==undefined){let e=r.access;if("string"==typeof e){if(o(e)<1){const e={instancePath:t+"/publishConfig/access",schemaPath:"#/properties/publishConfig/properties/access/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===l?l=[e]:l.push(e)}}else{const e={instancePath:t+"/publishConfig/access",schemaPath:"#/properties/publishConfig/properties/access/type",keyword:"type",params:{type:"string"},message:"must be string"};null===l?l=[e]:l.push(e)}}if(r.registry!==undefined){let e=r.registry;if("string"!=typeof e){const e={instancePath:t+"/publishConfig/registry",schemaPath:"#/properties/publishConfig/properties/registry/type",keyword:"type",params:{type:"string"},message:"must be string"};null===l?l=[e]:l.push(e)}if("https://registry.npmjs.org"!==e&&"https://registry.npmjs.org/"!==e){const e={instancePath:t+"/publishConfig/registry",schemaPath:"#/properties/publishConfig/properties/registry/enum",keyword:"enum",params:{allowedValues:n.properties.publishConfig.properties.registry.enum},message:"must be equal to one of the allowed values"};null===l?l=[e]:l.push(e)}}}else{const e={instancePath:t+"/publishConfig",schemaPath:"#/properties/publishConfig/type",keyword:"type",params:{type:"object"},message:"must be object"};null===l?l=[e]:l.push(e)}}if(e.repository!==undefined){let r=e.repository;if(r&&"object"==typeof r&&!Array.isArray(r)){if(r.type===undefined){const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/required",keyword:"required",params:{missingProperty:"type"},message:"must have required property '"+"type"+"'"};null===l?l=[e]:l.push(e)}if(r.url===undefined){const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/required",keyword:"required",params:{missingProperty:"url"},message:"must have required property '"+"url"+"'"};null===l?l=[e]:l.push(e)}for(const e in r)if("type"!==e&&"url"!==e){const r={instancePath:t+"/repository",schemaPath:"#/properties/repository/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"};null===l?l=[r]:l.push(r)}if(r.type!==undefined){let e=r.type;if("string"==typeof e){if(o(e)<1){const e={instancePath:t+"/repository/type",schemaPath:"#/properties/repository/properties/type/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===l?l=[e]:l.push(e)}}else{const e={instancePath:t+"/repository/type",schemaPath:"#/properties/repository/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"};null===l?l=[e]:l.push(e)}}if(r.url!==undefined){let e=r.url;if("string"==typeof e){if(o(e)<1){const e={instancePath:t+"/repository/url",schemaPath:"#/properties/repository/properties/url/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===l?l=[e]:l.push(e)}}else{const e={instancePath:t+"/repository/url",schemaPath:"#/properties/repository/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"};null===l?l=[e]:l.push(e)}}}else{const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/type",keyword:"type",params:{type:"object"},message:"must be object"};null===l?l=[e]:l.push(e)}}}else{const e={instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};null===l?l=[e]:l.push(e)}return a.errors=l,l}}}},{package:"@metamask/snap-controllers"}],[143,{lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash");const i="2020-08-31";var s={version:60,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=60;const r=function(e){var t;const r=null==e||null===(t=e.NotificationController)||void 0===t?void 0:t.notifications;var s;(0,n.isPlainObject)(r)&&(null===(s=r[2])||void 0===s?void 0:s.date)===i&&delete e.NotificationController.notifications[2];return e}(t.data);return t.data=r,t}};r.default=s}}},{package:"$root$"}],[1430,{"ajv/dist/runtime/equal":1496,"ajv/dist/runtime/ucs2length":1497},function(){with(this)return function(){"use strict";return function(e,t,r){t.exports=u,t.exports.default=u;const n={title:"Snap Manifest",description:"The Snap manifest file MUST be named `snap.manifest.json` and located in the package root directory.",type:"object",additionalProperties:!1,required:["version","description","proposedName","source","initialPermissions","manifestVersion"],properties:{version:{type:"string",title:"Version",description:"MUST be a valid SemVer version string and equal to the corresponding `package.json` field.",pattern:"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"},description:{type:"string",title:"Description",description:"MUST be a non-empty string less than or equal to 280 characters. A short description of the Snap.",minLength:1,maxLength:280},proposedName:{type:"string",title:"Proposed Name",description:"MUST be a string less than or equal to 214 characters. The Snap author's proposed name for the Snap. The Snap host application may display this name unmodified in its user interface. The proposed name SHOULD be human-readable.",minLength:1,maxLength:214,pattern:"^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$"},repository:{title:"Repository",description:"MAY be omitted. If present, MUST be equal to the corresponding package.json field.",oneOf:[{type:"null"},{type:"object",additionalProperties:!1,required:["type","url"],properties:{type:{type:"string",minLength:1},url:{type:"string",minLength:1}}}]},source:{type:"object",title:"Source",description:"Specifies some Snap metadata and where to fetch the Snap during installation.",additionalProperties:!1,required:["shasum","location"],properties:{shasum:{type:"string",description:"MUST be the Base64-encoded string representation of the SHA-256 hash of the Snap source file.",minLength:44,maxLength:44,pattern:"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"},location:{title:"Source Location",type:"object",additionalProperties:!1,required:["npm"],properties:{npm:{title:"npm",type:"object",additionalProperties:!1,required:["filePath","packageName","registry"],properties:{filePath:{type:"string",title:"File Path",description:"The path to the Snap bundle file from the project root directory.",minLength:1},iconPath:{type:"string",title:"Icon Path",description:"The path to an .svg file from the project root directory.",pattern:"\\w+\\.svg$"},packageName:{type:"string",title:"Package Name",description:"The Snap's npm package name.",minLength:1},registry:{type:"string",title:"npm Registry",description:"The npm registry URL.",enum:["https://registry.npmjs.org","https://registry.npmjs.org/"]}}}}}}},initialPermissions:{type:"object",title:"Initial Permissions",description:"MUST be a valid EIP-2255 wallet_requestPermissions parameter object, specifying the initial permissions that will be requested when the Snap is added to the host application."},manifestVersion:{type:"string",title:"Manifest Version",description:"The Snap manifest specification version targeted by the manifest.",enum:["0.1"]}}},i=new RegExp("^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$","u"),s=new RegExp("^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$","u"),o=new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$","u"),a=new RegExp("\\w+\\.svg$","u"),c=e("ajv/dist/runtime/ucs2length").default;e("ajv/dist/runtime/equal").default;function u(e,{instancePath:t="",parentData:r,parentDataProperty:l,rootData:d=e}={}){let h=null,f=0;if(e&&"object"==typeof e&&!Array.isArray(e)){if(e.version===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property '"+"version"+"'"};null===h?h=[e]:h.push(e),f++}if(e.description===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"description"},message:"must have required property '"+"description"+"'"};null===h?h=[e]:h.push(e),f++}if(e.proposedName===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"proposedName"},message:"must have required property '"+"proposedName"+"'"};null===h?h=[e]:h.push(e),f++}if(e.source===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property '"+"source"+"'"};null===h?h=[e]:h.push(e),f++}if(e.initialPermissions===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"initialPermissions"},message:"must have required property '"+"initialPermissions"+"'"};null===h?h=[e]:h.push(e),f++}if(e.manifestVersion===undefined){const e={instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifestVersion"},message:"must have required property '"+"manifestVersion"+"'"};null===h?h=[e]:h.push(e),f++}for(const r in e)if("version"!==r&&"description"!==r&&"proposedName"!==r&&"repository"!==r&&"source"!==r&&"initialPermissions"!==r&&"manifestVersion"!==r){const e={instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"};null===h?h=[e]:h.push(e),f++}if(e.version!==undefined){let r=e.version;if("string"==typeof r){if(!i.test(r)){const e={instancePath:t+"/version",schemaPath:"#/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"},message:'must match pattern "'+"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"+'"'};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(e.description!==undefined){let r=e.description;if("string"==typeof r){if(c(r)>280){const e={instancePath:t+"/description",schemaPath:"#/properties/description/maxLength",keyword:"maxLength",params:{limit:280},message:"must NOT have more than 280 characters"};null===h?h=[e]:h.push(e),f++}if(c(r)<1){const e={instancePath:t+"/description",schemaPath:"#/properties/description/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(e.proposedName!==undefined){let r=e.proposedName;if("string"==typeof r){if(c(r)>214){const e={instancePath:t+"/proposedName",schemaPath:"#/properties/proposedName/maxLength",keyword:"maxLength",params:{limit:214},message:"must NOT have more than 214 characters"};null===h?h=[e]:h.push(e),f++}if(c(r)<1){const e={instancePath:t+"/proposedName",schemaPath:"#/properties/proposedName/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===h?h=[e]:h.push(e),f++}if(!s.test(r)){const e={instancePath:t+"/proposedName",schemaPath:"#/properties/proposedName/pattern",keyword:"pattern",params:{pattern:"^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$"},message:'must match pattern "'+"^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$"+'"'};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/proposedName",schemaPath:"#/properties/proposedName/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(e.repository!==undefined){let r=e.repository;const n=f;let i=!1,s=null;const o=f;if(null!==r){const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/oneOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};null===h?h=[e]:h.push(e),f++}(p=o===f)&&(i=!0,s=0);const a=f;if(r&&"object"==typeof r&&!Array.isArray(r)){if(r.type===undefined){const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/oneOf/1/required",keyword:"required",params:{missingProperty:"type"},message:"must have required property '"+"type"+"'"};null===h?h=[e]:h.push(e),f++}if(r.url===undefined){const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/oneOf/1/required",keyword:"required",params:{missingProperty:"url"},message:"must have required property '"+"url"+"'"};null===h?h=[e]:h.push(e),f++}for(const e in r)if("type"!==e&&"url"!==e){const r={instancePath:t+"/repository",schemaPath:"#/properties/repository/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"};null===h?h=[r]:h.push(r),f++}if(r.type!==undefined){let e=r.type;if("string"==typeof e){if(c(e)<1){const e={instancePath:t+"/repository/type",schemaPath:"#/properties/repository/oneOf/1/properties/type/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/repository/type",schemaPath:"#/properties/repository/oneOf/1/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(r.url!==undefined){let e=r.url;if("string"==typeof e){if(c(e)<1){const e={instancePath:t+"/repository/url",schemaPath:"#/properties/repository/oneOf/1/properties/url/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/repository/url",schemaPath:"#/properties/repository/oneOf/1/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}}else{const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};null===h?h=[e]:h.push(e),f++}var p;if((p=a===f)&&i?(i=!1,s=[s,1]):p&&(i=!0,s=1),i)f=n,null!==h&&(n?h.length=n:h=null);else{const e={instancePath:t+"/repository",schemaPath:"#/properties/repository/oneOf",keyword:"oneOf",params:{passingSchemas:s},message:"must match exactly one schema in oneOf"};null===h?h=[e]:h.push(e),f++}}if(e.source!==undefined){let r=e.source;if(r&&"object"==typeof r&&!Array.isArray(r)){if(r.shasum===undefined){const e={instancePath:t+"/source",schemaPath:"#/properties/source/required",keyword:"required",params:{missingProperty:"shasum"},message:"must have required property '"+"shasum"+"'"};null===h?h=[e]:h.push(e),f++}if(r.location===undefined){const e={instancePath:t+"/source",schemaPath:"#/properties/source/required",keyword:"required",params:{missingProperty:"location"},message:"must have required property '"+"location"+"'"};null===h?h=[e]:h.push(e),f++}for(const e in r)if("shasum"!==e&&"location"!==e){const r={instancePath:t+"/source",schemaPath:"#/properties/source/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"};null===h?h=[r]:h.push(r),f++}if(r.shasum!==undefined){let e=r.shasum;if("string"==typeof e){if(c(e)>44){const e={instancePath:t+"/source/shasum",schemaPath:"#/properties/source/properties/shasum/maxLength",keyword:"maxLength",params:{limit:44},message:"must NOT have more than 44 characters"};null===h?h=[e]:h.push(e),f++}if(c(e)<44){const e={instancePath:t+"/source/shasum",schemaPath:"#/properties/source/properties/shasum/minLength",keyword:"minLength",params:{limit:44},message:"must NOT have fewer than 44 characters"};null===h?h=[e]:h.push(e),f++}if(!o.test(e)){const e={instancePath:t+"/source/shasum",schemaPath:"#/properties/source/properties/shasum/pattern",keyword:"pattern",params:{pattern:"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"},message:'must match pattern "'+"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"+'"'};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/source/shasum",schemaPath:"#/properties/source/properties/shasum/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(r.location!==undefined){let e=r.location;if(e&&"object"==typeof e&&!Array.isArray(e)){if(e.npm===undefined){const e={instancePath:t+"/source/location",schemaPath:"#/properties/source/properties/location/required",keyword:"required",params:{missingProperty:"npm"},message:"must have required property '"+"npm"+"'"};null===h?h=[e]:h.push(e),f++}for(const r in e)if("npm"!==r){const e={instancePath:t+"/source/location",schemaPath:"#/properties/source/properties/location/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"};null===h?h=[e]:h.push(e),f++}if(e.npm!==undefined){let r=e.npm;if(r&&"object"==typeof r&&!Array.isArray(r)){if(r.filePath===undefined){const e={instancePath:t+"/source/location/npm",schemaPath:"#/properties/source/properties/location/properties/npm/required",keyword:"required",params:{missingProperty:"filePath"},message:"must have required property '"+"filePath"+"'"};null===h?h=[e]:h.push(e),f++}if(r.packageName===undefined){const e={instancePath:t+"/source/location/npm",schemaPath:"#/properties/source/properties/location/properties/npm/required",keyword:"required",params:{missingProperty:"packageName"},message:"must have required property '"+"packageName"+"'"};null===h?h=[e]:h.push(e),f++}if(r.registry===undefined){const e={instancePath:t+"/source/location/npm",schemaPath:"#/properties/source/properties/location/properties/npm/required",keyword:"required",params:{missingProperty:"registry"},message:"must have required property '"+"registry"+"'"};null===h?h=[e]:h.push(e),f++}for(const e in r)if("filePath"!==e&&"iconPath"!==e&&"packageName"!==e&&"registry"!==e){const r={instancePath:t+"/source/location/npm",schemaPath:"#/properties/source/properties/location/properties/npm/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"};null===h?h=[r]:h.push(r),f++}if(r.filePath!==undefined){let e=r.filePath;if("string"==typeof e){if(c(e)<1){const e={instancePath:t+"/source/location/npm/filePath",schemaPath:"#/properties/source/properties/location/properties/npm/properties/filePath/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/source/location/npm/filePath",schemaPath:"#/properties/source/properties/location/properties/npm/properties/filePath/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(r.iconPath!==undefined){let e=r.iconPath;if("string"==typeof e){if(!a.test(e)){const e={instancePath:t+"/source/location/npm/iconPath",schemaPath:"#/properties/source/properties/location/properties/npm/properties/iconPath/pattern",keyword:"pattern",params:{pattern:"\\w+\\.svg$"},message:'must match pattern "'+"\\w+\\.svg$"+'"'};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/source/location/npm/iconPath",schemaPath:"#/properties/source/properties/location/properties/npm/properties/iconPath/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(r.packageName!==undefined){let e=r.packageName;if("string"==typeof e){if(c(e)<1){const e={instancePath:t+"/source/location/npm/packageName",schemaPath:"#/properties/source/properties/location/properties/npm/properties/packageName/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};null===h?h=[e]:h.push(e),f++}}else{const e={instancePath:t+"/source/location/npm/packageName",schemaPath:"#/properties/source/properties/location/properties/npm/properties/packageName/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}}if(r.registry!==undefined){let e=r.registry;if("string"!=typeof e){const e={instancePath:t+"/source/location/npm/registry",schemaPath:"#/properties/source/properties/location/properties/npm/properties/registry/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}if("https://registry.npmjs.org"!==e&&"https://registry.npmjs.org/"!==e){const e={instancePath:t+"/source/location/npm/registry",schemaPath:"#/properties/source/properties/location/properties/npm/properties/registry/enum",keyword:"enum",params:{allowedValues:n.properties.source.properties.location.properties.npm.properties.registry.enum},message:"must be equal to one of the allowed values"};null===h?h=[e]:h.push(e),f++}}}else{const e={instancePath:t+"/source/location/npm",schemaPath:"#/properties/source/properties/location/properties/npm/type",keyword:"type",params:{type:"object"},message:"must be object"};null===h?h=[e]:h.push(e),f++}}}else{const e={instancePath:t+"/source/location",schemaPath:"#/properties/source/properties/location/type",keyword:"type",params:{type:"object"},message:"must be object"};null===h?h=[e]:h.push(e),f++}}}else{const e={instancePath:t+"/source",schemaPath:"#/properties/source/type",keyword:"type",params:{type:"object"},message:"must be object"};null===h?h=[e]:h.push(e),f++}}if(e.initialPermissions!==undefined){let r=e.initialPermissions;if(!r||"object"!=typeof r||Array.isArray(r)){const e={instancePath:t+"/initialPermissions",schemaPath:"#/properties/initialPermissions/type",keyword:"type",params:{type:"object"},message:"must be object"};null===h?h=[e]:h.push(e),f++}}if(e.manifestVersion!==undefined){let r=e.manifestVersion;if("string"!=typeof r){const e={instancePath:t+"/manifestVersion",schemaPath:"#/properties/manifestVersion/type",keyword:"type",params:{type:"string"},message:"must be string"};null===h?h=[e]:h.push(e),f++}if("0.1"!==r){const e={instancePath:t+"/manifestVersion",schemaPath:"#/properties/manifestVersion/enum",keyword:"enum",params:{allowedValues:n.properties.manifestVersion.enum},message:"must be equal to one of the allowed values"};null===h?h=[e]:h.push(e),f++}}}else{const e={instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};null===h?h=[e]:h.push(e),f++}return u.errors=h,h}}}},{package:"@metamask/snap-controllers"}],[1431,{"./json-schemas":1428,"@metamask/utils":1541,buffer:2175,"concat-stream":1499,crypto:2285,"fast-deep-equal":4384,"gunzip-maybe":4427,pump:5599,"readable-web-to-node-stream":5783,semver:5870,"tar-stream":6001},function(){with(this)return function(){"use strict";return function(e,t,r){(function(t){(function(){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.getSnapPermissionName=r.SNAP_PREFIX=r.getSnapPrefix=r.isValidSnapVersionRange=r.resolveVersion=r.stripDotSlash=r.validateSnapShasum=r.getTargetVersion=r.satifiesVersionRange=r.gtVersion=r.validateNpmSnapManifest=r.validateNpmSnap=r.ProgrammaticallyFixableSnapError=r.SnapValidationFailureReason=r.fetchNpmSnap=r.getSnapSourceShasum=r.PROPOSED_NAME_REGEX=r.DEFAULT_REQUESTED_SNAP_VERSION=r.DEFAULT_NPM_REGISTRY=r.LOCALHOST_HOSTNAMES=r.NpmSnapFileNames=r.SnapIdPrefixes=void 0;const i=e("crypto"),s=e("@metamask/utils"),o=n(e("concat-stream")),a=n(e("fast-deep-equal")),c=n(e("gunzip-maybe")),u=n(e("pump")),l=e("readable-web-to-node-stream"),d=e("semver"),h=e("tar-stream"),f=e("./json-schemas");var p,m;!function(e){e.npm="npm:",e.local="local:"}(p=r.SnapIdPrefixes||(r.SnapIdPrefixes={})),function(e){e.PackageJson="package.json",e.Manifest="snap.manifest.json"}(m=r.NpmSnapFileNames||(r.NpmSnapFileNames={})),r.LOCALHOST_HOSTNAMES=new Set(["localhost","127.0.0.1","::1"]),r.DEFAULT_NPM_REGISTRY="https://registry.npmjs.org",r.DEFAULT_REQUESTED_SNAP_VERSION="*";const g=1e5,v=`${Math.floor(100)}kb`;function y(e){return(0,i.createHash)("sha256").update(e,"utf8").digest("base64")}r.PROPOSED_NAME_REGEX=/^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,r.getSnapSourceShasum=y;const w=["manifest","packageJson","sourceCode"],b={manifest:m.Manifest,packageJson:m.PackageJson,sourceCode:"source code bundle"};var P;r.fetchNpmSnap=async function(e,t,n=r.DEFAULT_NPM_REGISTRY,i=fetch){const[a,d]=await async function(e,t,n=r.DEFAULT_NPM_REGISTRY,i=fetch){const o=await(await i(new URL(e,n).toString())).json();if(!(0,s.isObject)(o))throw new Error(`Failed to fetch package "${e}" metadata from npm.`);const a=M(Object.keys(o?.versions??{}),t);if(null===a)throw new Error(`Failed to find a matching version in npm metadata for package "${e}" and requested semver range "${t}"`);const c=o.versions?.[a]?.dist?.tarball;if(!function(e){try{return Boolean(new URL(e))}catch(e){return!1}}(c)||!c.endsWith(".tgz"))throw new Error(`Failed to find valid tarball URL in npm metadata for package "${e}".`);const u=new URL(n),l=new URL(c);l.hostname=u.hostname,l.protocol=u.protocol;const d=await i(l.toString());if(!d.ok)throw new Error(`Failed to fetch tarball for package "${e}".`);return[await d.blob().then((e=>e.stream())),a]}(e,t,n,i),f={};return await new Promise(((e,t)=>{(0,u.default)(function(e){if("function"!=typeof e.getReader)return e;return new l.ReadableWebToNodeStream(e)}(a),(0,c.default)(),function(e){const t=(0,h.extract)(),r=new Map;return t.on("entry",((n,i,s)=>{const{name:a,type:c}=n;if("file"===c){const n=a.replace(S,"");if(n===m.PackageJson)return i.pipe((0,o.default)((r=>{try{e.packageJson=JSON.parse(r.toString())}catch(e){return t.destroy(new Error(`Failed to parse "${m.PackageJson}".`))}return s()})));if(n===m.Manifest)return i.pipe((0,o.default)((r=>{try{e.manifest=JSON.parse(r.toString())}catch(e){return t.destroy(new Error(`Failed to parse "${m.Manifest}".`))}return s()})));if(/\w+\.(?:js|svg)$/u.test(n))return i.pipe((0,o.default)((e=>(r.set(n,e),s()))))}return i.on("end",(()=>s())),i.resume()})),t.once("finish",(()=>{if((0,s.isObject)(e.manifest)){const{filePath:t,iconPath:n}=e.manifest.source?.location?.npm??{},i=T(t),s=T(n);i&&(e.sourceCode=r.get(i)?.toString("utf8")),"string"==typeof s&&s.endsWith(".svg")&&(e.svgIcon=r.get(s)?.toString("utf8"))}r.clear()})),t}(f),(r=>{r?t(r):e()}))})),k(f,`npm Snap "${e}@${d}" validation error: `)},function(e){e.NameMismatch='"name" field mismatch',e.VersionMismatch='"version" field mismatch',e.RepositoryMismatch='"repository" field mismatch',e.ShasumMismatch='"shasum" field mismatch'}(P=r.SnapValidationFailureReason||(r.SnapValidationFailureReason={}));class E extends Error{constructor(e,t){super(e),this.reason=t}}function k(e,r){w.forEach((t=>{if(!e[t])throw new Error(`${r}Missing file "${b[t]}".`)}));const{manifest:n,packageJson:i,sourceCode:s,svgIcon:o}=e;try{(0,f.validateSnapJsonFile)(m.Manifest,n)}catch(e){throw new Error(`${r}"${m.Manifest}" is invalid:\n${e.message}`)}const a=n,{iconPath:c}=a.source.location.npm;if(c&&!o)throw new Error(`${r}Missing file "${c}".`);try{(0,f.validateSnapJsonFile)(m.PackageJson,i)}catch(e){throw new Error(`${r}"${m.PackageJson}" is invalid:\n${e.message}`)}const u=i;if(_({manifest:a,packageJson:u,sourceCode:s},r),o&&t.byteLength(o,"utf8")>g)throw new Error(`${r}The specified SVG icon exceeds the maximum size of ${v}.`);return{manifest:a,packageJson:u,sourceCode:s,svgIcon:o}}function _({manifest:e,packageJson:t,sourceCode:r},n){const i=t.name,s=t.version,o=t.repository,c=e.source.location.npm.packageName,u=e.version,l=e.repository;if(i!==c)throw new E(`${n}"${m.Manifest}" npm package name ("${c}") does not match the "${m.PackageJson}" "name" field ("${i}").`,P.NameMismatch);if(s!==u)throw new E(`${n}"${m.Manifest}" npm package version ("${u}") does not match the "${m.PackageJson}" "version" field ("${s}").`,P.VersionMismatch);if((o||l)&&!(0,a.default)(o,l))throw new E(`${n}"${m.Manifest}" "repository" field does not match the "${m.PackageJson}" "repository" field.`,P.RepositoryMismatch);return C(e,r,`${n}"${m.Manifest}" "shasum" field does not match computed shasum.`),[e,r,t]}function M(e,t){const r=(0,d.maxSatisfying)(e,t);return r||(0,d.maxSatisfying)(e,t,{includePrerelease:!0})}r.ProgrammaticallyFixableSnapError=E,r.validateNpmSnap=k,r.validateNpmSnapManifest=_,r.gtVersion=function(e,t){return(0,d.gt)(e,t,{includePrerelease:!0})},r.satifiesVersionRange=function(e,t){return(0,d.satisfies)(e,t,{includePrerelease:!0})},r.getTargetVersion=M;const S=/^package\//u;function C(e,t,r="Invalid Snap manifest: manifest shasum does not match computed shasum."){if(e.source.shasum!==y(t))throw new E(r,P.ShasumMismatch)}function T(e){return e?.replace(/^\.\//u,"")}r.validateSnapShasum=C,r.stripDotSlash=T,r.resolveVersion=function(e){return e===undefined||"latest"===e?r.DEFAULT_REQUESTED_SNAP_VERSION:e},r.isValidSnapVersionRange=function(e){return Boolean("string"==typeof e&&null!==(0,d.validRange)(e,{includePrerelease:!0}))},r.getSnapPrefix=function(e){const t=Object.values(p).find((t=>e.startsWith(t)));if(t!==undefined)return t;throw new Error(`Invalid or no prefix found for "${e}"`)},r.SNAP_PREFIX="wallet_snap_",r.getSnapPermissionName=function(e){return r.SNAP_PREFIX+e}}).call(this)}).call(this,e("buffer").Buffer)}}},{package:"@metamask/snap-controllers"}],[1432,{},function(){with(this)return function(){"use strict";return function(e,t,r){function n(e,t){let r,n;const i=new Promise(((i,s)=>{r=setTimeout((()=>{r=undefined,t===undefined?i():i(t)}),e),n=s}));return i.cancel=()=>{r!==undefined&&(clearTimeout(r),n("The delay has been canceled."))},i}Object.defineProperty(r,"__esModule",{value:!0}),r.assertExhaustive=r.withTimeout=r.hasTimedOut=r.delay=r.setDiff=void 0,r.setDiff=function(e,t){return Object.entries(e).reduce(((e,[r,n])=>(r in t||(e[r]=n),e)),{})},r.delay=n,r.hasTimedOut=Symbol("Used to check if the requested promise has timeout (see withTimeout)"),r.withTimeout=async function(e,t){const i=n(t,r.hasTimedOut);try{return await Promise.race([e,i])}finally{i.cancel()}},r.assertExhaustive=function(e){throw new Error("Invalid branch reached. Should be detected during compilation")}}}},{package:"@metamask/snap-controllers"}],[1433,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.BaseController=void 0;class n{constructor(e={},t={}){this.defaultConfig={},this.defaultState={},this.disabled=!1,this.name="BaseController",this.internalConfig=this.defaultConfig,this.internalState=this.defaultState,this.internalListeners=[],this.initialState=t,this.initialConfig=e}initialize(){return this.internalState=this.defaultState,this.internalConfig=this.defaultConfig,this.configure(this.initialConfig),this.update(this.initialState),this}get config(){return this.internalConfig}get state(){return this.internalState}configure(e,t=!1,r=!0){if(r){this.internalConfig=t?e:Object.assign(this.internalConfig,e);for(const e in this.internalConfig)void 0!==this.internalConfig[e]&&(this[e]=this.internalConfig[e])}else for(const t in e)void 0!==this.internalConfig[t]&&(this.internalConfig[t]=e[t],this[t]=e[t])}notify(){this.disabled||this.internalListeners.forEach((e=>{e(this.internalState)}))}subscribe(e){this.internalListeners.push(e)}unsubscribe(e){const t=this.internalListeners.findIndex((t=>e===t));return t>-1&&this.internalListeners.splice(t,1),t>-1}update(e,t=!1){this.internalState=t?Object.assign({},e):Object.assign({},this.internalState,e),this.notify()}}r.BaseController=n,r.default=n}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1434,{immer:4513},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getPersistentState=r.getAnonymizedState=r.BaseController=void 0;const n=e("immer");(0,n.enablePatches)();function i(e,t,r){return Object.keys(e).reduce(((n,i)=>{const s=t[i][r],o=e[i];return"function"==typeof s?n[i]=s(o):s&&(n[i]=o),n}),{})}r.BaseController=class{constructor({messenger:e,metadata:t,name:r,state:n}){this.messagingSystem=e,this.name=r,this.internalState=n,this.metadata=t,this.messagingSystem.registerActionHandler(`${r}:getState`,(()=>this.state))}get state(){return this.internalState}set state(e){throw new Error("Controller state cannot be directly mutated; use 'update' method instead.")}update(e){const[t,r]=n.produceWithPatches(this.internalState,e);this.internalState=t,this.messagingSystem.publish(`${this.name}:stateChange`,t,r)}destroy(){this.messagingSystem.clearEventSubscriptions(`${this.name}:stateChange`)}},r.getAnonymizedState=function(e,t){return i(e,t,"anonymous")},r.getPersistentState=function(e,t){return i(e,t,"persist")}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1435,{"./BaseController":1433},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.ComposableController=void 0;const n=e("./BaseController");class i extends n.BaseController{constructor(e,t){super(undefined,e.reduce(((e,t)=>(e[t.name]=t.state,e)),{})),this.controllers=[],this.name="ComposableController",this.initialize(),this.controllers=e,this.messagingSystem=t,this.controllers.forEach((e=>{const{name:t}=e;if(e.subscribe!==undefined)e.subscribe((e=>{this.update({[t]:e})}));else{if(!this.messagingSystem)throw new Error("Messaging system required if any BaseControllerV2 controllers are used");this.messagingSystem.subscribe(`${t}:stateChange`,(e=>{this.update({[t]:e})}))}}))}get flatState(){let e={};for(const t of this.controllers)e=Object.assign(Object.assign({},e),t.state);return e}}r.ComposableController=i,r.default=i}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1436,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.ControllerMessenger=r.RestrictedControllerMessenger=void 0;class n{constructor({controllerMessenger:e,name:t,allowedActions:r,allowedEvents:n}){this.controllerMessenger=e,this.controllerName=t,this.allowedActions=r||null,this.allowedEvents=n||null}registerActionHandler(e,t){if(!e.startsWith(`${this.controllerName}:`))throw new Error(`Only allowed registering action handlers prefixed by '${this.controllerName}:'`);this.controllerMessenger.registerActionHandler(e,t)}unregisterActionHandler(e){if(!e.startsWith(`${this.controllerName}:`))throw new Error(`Only allowed unregistering action handlers prefixed by '${this.controllerName}:'`);this.controllerMessenger.unregisterActionHandler(e)}call(e,...t){if(null===this.allowedActions)throw new Error("No actions allowed");if(!this.allowedActions.includes(e))throw new Error(`Action missing from allow list: ${e}`);return this.controllerMessenger.call(e,...t)}publish(e,...t){if(!e.startsWith(`${this.controllerName}:`))throw new Error(`Only allowed publishing events prefixed by '${this.controllerName}:'`);this.controllerMessenger.publish(e,...t)}subscribe(e,t,r){if(null===this.allowedEvents)throw new Error("No events allowed");if(!this.allowedEvents.includes(e))throw new Error(`Event missing from allow list: ${e}`);return r?this.controllerMessenger.subscribe(e,t,r):this.controllerMessenger.subscribe(e,t)}unsubscribe(e,t){if(null===this.allowedEvents)throw new Error("No events allowed");if(!this.allowedEvents.includes(e))throw new Error(`Event missing from allow list: ${e}`);this.controllerMessenger.unsubscribe(e,t)}clearEventSubscriptions(e){if(!e.startsWith(`${this.controllerName}:`))throw new Error(`Only allowed clearing events prefixed by '${this.controllerName}:'`);this.controllerMessenger.clearEventSubscriptions(e)}}r.RestrictedControllerMessenger=n;r.ControllerMessenger=class{constructor(){this.actions=new Map,this.events=new Map,this.eventPayloadCache=new Map}registerActionHandler(e,t){if(this.actions.has(e))throw new Error(`A handler for ${e} has already been registered`);this.actions.set(e,t)}unregisterActionHandler(e){this.actions.delete(e)}clearActions(){this.actions.clear()}call(e,...t){const r=this.actions.get(e);if(!r)throw new Error(`A handler for ${e} has not been registered`);return r(...t)}publish(e,...t){const r=this.events.get(e);if(r)for(const[e,n]of r.entries())if(n){const r=this.eventPayloadCache.get(e),i=n(...t);i!==r&&(this.eventPayloadCache.set(e,i),e(i,r))}else e(...t)}subscribe(e,t,r){let n=this.events.get(e);n||(n=new Map,this.events.set(e,n)),n.set(t,r)}unsubscribe(e,t){const r=this.events.get(e);if(!r||!r.has(t))throw new Error(`Subscription not found for event: ${e}`);r.get(t)&&this.eventPayloadCache.delete(t),r.delete(t)}clearEventSubscriptions(e){this.events.delete(e)}clearSubscriptions(){this.events.clear()}getRestricted({name:e,allowedActions:t,allowedEvents:r}){return new n({controllerMessenger:this,name:e,allowedActions:t,allowedEvents:r})}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1437,{"../BaseController":1433},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.AnnouncementController=void 0;const n=e("../BaseController"),i={announcements:{}};class s extends n.BaseController{constructor(e,t){super(e,t||i),this.initialize(),this._addAnnouncements()}_addAnnouncements(){const e={},{allAnnouncements:t}=this.config;Object.values(t).forEach((t=>{e[t.id]=this.state.announcements[t.id]?this.state.announcements[t.id]:Object.assign(Object.assign({},t),{isShown:!1})})),this.update({announcements:e})}updateViewed(e){const t=this.state.announcements;for(const r of Object.keys(e).map(Number))t[r].isShown=e[r];this.update({announcements:t},!0)}}r.AnnouncementController=s}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1438,{"../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.fetchExchangeRate=void 0;const i=e("../util");r.fetchExchangeRate=function(e,t,r){return n(this,void 0,void 0,(function*(){const n=yield(0,i.handleFetch)(function(e,t,r){return`https://min-api.cryptocompare.com/data/price?fsym=${t.toUpperCase()}&tsyms=${e.toUpperCase()}`+(r&&"USD"!==e.toUpperCase()?",USD":"")}(e,t,r));if("Error"===n.Response)throw new Error(n.Message);const s=Number(n[e.toUpperCase()]),o=Number(n.USD);if(!Number.isFinite(s))throw new Error(`Invalid response for ${e.toUpperCase()}: ${n[e.toUpperCase()]}`);if(r&&!Number.isFinite(o))throw new Error(`Invalid response for usdConversionRate: ${n.USD}`);return{conversionRate:s,usdConversionRate:o}}))}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1439,{"../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.fetchTokenMetadata=r.fetchTokenList=r.TOKEN_METADATA_NO_SUPPORT_ERROR=r.TOKEN_END_POINT_API=void 0;const i=e("../util");r.TOKEN_END_POINT_API="https://token-api.metaswap.codefi.network",r.TOKEN_METADATA_NO_SUPPORT_ERROR="TokenService Error: Network does not support fetchTokenMetadata";function s(e,t,r){return n(this,void 0,void 0,(function*(){const n={referrer:e,referrerPolicy:"no-referrer-when-downgrade",method:"GET",mode:"cors",signal:t,cache:"default"};n.headers=new window.Headers,n.headers.set("Content-Type","application/json");try{return yield(0,i.timeoutFetch)(e,n,r)}catch(e){e instanceof Error&&"AbortError"===e.name&&console.log("Request is aborted")}return undefined}))}function o(e){return n(this,void 0,void 0,(function*(){const t=yield e.json();if(null==t?void 0:t.error)throw new Error(`TokenService Error: ${t.error}`);return t}))}r.fetchTokenList=function(e,t,{timeout:i=1e4}={}){return n(this,void 0,void 0,(function*(){const n=function(e){return`${r.TOKEN_END_POINT_API}/tokens/${e}`}(e),a=yield s(n,t,i);return a?o(a):undefined}))},r.fetchTokenMetadata=function(e,t,a,{timeout:c=1e4}={}){return n(this,void 0,void 0,(function*(){if(!(0,i.isTokenDetectionSupportedForNetwork)(e))throw new Error(r.TOKEN_METADATA_NO_SUPPORT_ERROR);const n=function(e,t){return`${r.TOKEN_END_POINT_API}/token/${e}?address=${t}`}(e,t),u=yield s(n,a,c);return u?o(u):undefined}))}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[144,{lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash");var i={version:61,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=61;const r=function(e){const t=(new Date).getTime();e.AppStateController?(e.AppStateController.recoveryPhraseReminderHasBeenShown=!1,e.AppStateController.recoveryPhraseReminderLastShown=t):e.AppStateController={recoveryPhraseReminderHasBeenShown:!1,recoveryPhraseReminderLastShown:t};return e}(t.data);return t.data=r,t}};r.default=i}}},{package:"$root$"}],[1440,{"../BaseControllerV2":1434,"eth-rpc-errors":2537,nanoid:1538},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.ApprovalController=void 0;const n=e("eth-rpc-errors"),i=e("nanoid"),s=e("../BaseControllerV2"),o="ApprovalController",a={pendingApprovals:{persist:!1,anonymous:!0},pendingApprovalCount:{persist:!1,anonymous:!1}};class c extends s.BaseController{constructor({messenger:e,showApprovalRequest:t,state:r={}}){super({name:o,metadata:a,messenger:e,state:Object.assign(Object.assign({},{pendingApprovals:{},pendingApprovalCount:0}),r)}),this._approvals=new Map,this._origins=new Map,this._showApprovalRequest=t,this.registerMessageHandlers()}registerMessageHandlers(){this.messagingSystem.registerActionHandler(`${o}:clearRequests`,this.clear.bind(this)),this.messagingSystem.registerActionHandler(`${o}:addRequest`,((e,t)=>t?this.addAndShowApprovalRequest(e):this.add(e))),this.messagingSystem.registerActionHandler(`${o}:hasRequest`,this.has.bind(this)),this.messagingSystem.registerActionHandler(`${o}:acceptRequest`,this.accept.bind(this)),this.messagingSystem.registerActionHandler(`${o}:rejectRequest`,this.reject.bind(this))}addAndShowApprovalRequest(e){const t=this._add(e.origin,e.type,e.id,e.requestData);return this._showApprovalRequest(),t}add(e){return this._add(e.origin,e.type,e.id,e.requestData)}get(e){return this.state.pendingApprovals[e]}getApprovalCount(e={}){var t,r;if(!e.origin&&!e.type)throw new Error("Must specify origin, type, or both.");const{origin:n,type:i}=e;if(n&&i)return Number(Boolean(null===(t=this._origins.get(n))||void 0===t?void 0:t.has(i)));if(n)return(null===(r=this._origins.get(n))||void 0===r?void 0:r.size)||0;let s=0;for(const e of Object.values(this.state.pendingApprovals))e.type===i&&(s+=1);return s}getTotalApprovalCount(){return this.state.pendingApprovalCount}has(e={}){var t;const{id:r,origin:n,type:i}=e;if(r){if("string"!=typeof r)throw new Error("May not specify non-string id.");return this._approvals.has(r)}if(i&&"string"!=typeof i)throw new Error("May not specify non-string type.");if(n){if("string"!=typeof n)throw new Error("May not specify non-string origin.");return i?Boolean(null===(t=this._origins.get(n))||void 0===t?void 0:t.has(i)):this._origins.has(n)}if(i){for(const e of Object.values(this.state.pendingApprovals))if(e.type===i)return!0;return!1}throw new Error("Must specify a valid combination of id, origin, and type.")}accept(e,t){this._deleteApprovalAndGetCallbacks(e).resolve(t)}reject(e,t){this._deleteApprovalAndGetCallbacks(e).reject(t)}clear(e){for(const t of this._approvals.keys())this.reject(t,e);this._origins.clear(),this.update((()=>({pendingApprovals:{},pendingApprovalCount:0})))}_add(e,t,r=(0,i.nanoid)(),s){var o;if(this._validateAddParams(r,e,t,s),null===(o=this._origins.get(e))||void 0===o?void 0:o.has(t))throw n.ethErrors.rpc.resourceUnavailable(((e,t)=>`Request of type '${t}' already pending for origin ${e}. Please wait.`)(e,t));return new Promise(((n,i)=>{this._approvals.set(r,{resolve:n,reject:i}),this._addPendingApprovalOrigin(e,t),this._addToStore(r,e,t,s)}))}_validateAddParams(e,t,r,i){let s=null;if(e&&"string"==typeof e?this._approvals.has(e)?s=`Approval request with id '${e}' already exists.`:t&&"string"==typeof t?r&&"string"==typeof r?i&&("object"!=typeof i||Array.isArray(i))&&(s="Request data must be a plain object if specified."):s="Must specify non-empty string type.":s="Must specify non-empty string origin.":s="Must specify non-empty string id.",s)throw n.ethErrors.rpc.internal(s)}_addPendingApprovalOrigin(e,t){const r=this._origins.get(e)||new Set;r.add(t),this._origins.has(e)||this._origins.set(e,r)}_addToStore(e,t,r,n){const i={id:e,origin:t,type:r,time:Date.now(),requestData:n||null};this.update((t=>{t.pendingApprovals[e]=i,t.pendingApprovalCount=Object.keys(t.pendingApprovals).length}))}_delete(e){this._approvals.delete(e);const{origin:t,type:r}=this.state.pendingApprovals[e];this._origins.get(t).delete(r),this._isEmptyOrigin(t)&&this._origins.delete(t),this.update((t=>{delete t.pendingApprovals[e],t.pendingApprovalCount=Object.keys(t.pendingApprovals).length}))}_deleteApprovalAndGetCallbacks(e){const t=this._approvals.get(e);if(!t)throw new Error(`Approval request with id '${e}' not found.`);return this._delete(e),t}_isEmptyOrigin(e){var t;return!(null===(t=this._origins.get(e))||void 0===t?void 0:t.size)}}r.ApprovalController=c,r.default=c}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1441,{"../BaseController":1433,"../util":1489,"async-mutex":1830,"eth-query":2533},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.AccountTrackerController=void 0;const s=i(e("eth-query")),o=e("async-mutex"),a=e("../BaseController"),c=e("../util");class u extends a.BaseController{constructor({onPreferencesStateChange:e,getIdentities:t},r,i){super(r,i),this.mutex=new o.Mutex,this.name="AccountTrackerController",this.refresh=()=>n(this,void 0,void 0,(function*(){this.syncAccounts();const e=Object.assign({},this.state.accounts);for(const t in e)yield(0,c.safelyExecuteWithTimeout)((()=>n(this,void 0,void 0,(function*(){const r=yield(0,c.query)(this.ethQuery,"getBalance",[t]);e[t]={balance:(0,c.BNToHex)(r)}}))));this.update({accounts:e})})),this.defaultConfig={interval:1e4},this.defaultState={accounts:{}},this.initialize(),this.getIdentities=t,e((()=>{this.refresh()})),this.poll()}syncAccounts(){const{accounts:e}=this.state,t=Object.keys(this.getIdentities()),r=Object.keys(e),n=t.filter((e=>-1===r.indexOf(e))),i=r.filter((e=>-1===t.indexOf(e)));n.forEach((t=>{e[t]={balance:"0x0"}})),i.forEach((t=>{delete e[t]})),this.update({accounts:Object.assign({},e)})}set provider(e){this.ethQuery=new s.default(e)}get provider(){throw new Error("Property only used for setting")}poll(e){return n(this,void 0,void 0,(function*(){const t=yield this.mutex.acquire();e&&this.configure({interval:e},!1,!1),this.handle&&clearTimeout(this.handle),yield this.refresh(),this.handle=setTimeout((()=>{t(),this.poll(this.config.interval)}),this.config.interval)}))}syncBalanceWithAddresses(e){return n(this,void 0,void 0,(function*(){return yield Promise.all(e.map((e=>(0,c.safelyExecuteWithTimeout)((()=>n(this,void 0,void 0,(function*(){const t=yield(0,c.query)(this.ethQuery,"getBalance",[e]);return[e,t]}))))))).then((e=>e.reduce(((e,t)=>{if(!t)return e;const[r,n]=t;return Object.assign(Object.assign({},e),{[r]:{balance:n}})}),{})))}))}}r.AccountTrackerController=u,r.default=u}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1442,{"../BaseController":1433,"../constants":1455,"../util":1489,"./Standards/CollectibleStandards/ERC1155/ERC1155Standard":1446,"./Standards/CollectibleStandards/ERC721/ERC721Standard":1447,"./Standards/ERC20Standard":1448,"single-call-balance-checker-abi":5925,web3:6185},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.AssetsContractController=r.MISSING_PROVIDER_ERROR=r.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID=void 0;const s=i(e("web3")),o=i(e("single-call-balance-checker-abi")),a=e("../BaseController"),c=e("../constants"),u=e("../util"),l=e("./Standards/CollectibleStandards/ERC721/ERC721Standard"),d=e("./Standards/CollectibleStandards/ERC1155/ERC1155Standard"),h=e("./Standards/ERC20Standard");r.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID={[u.SupportedTokenDetectionNetworks.mainnet]:"0xb1f8e55c7f64d203c1400b9d8555d050f94adf39",[u.SupportedTokenDetectionNetworks.bsc]:"0x2352c63A83f9Fd126af8676146721Fa00924d7e4",[u.SupportedTokenDetectionNetworks.polygon]:"0x2352c63A83f9Fd126af8676146721Fa00924d7e4",[u.SupportedTokenDetectionNetworks.avax]:"0xD023D153a0DFa485130ECFdE2FAA7e612EF94818"},r.MISSING_PROVIDER_ERROR="AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available";class f extends a.BaseController{constructor({onPreferencesStateChange:e,onNetworkStateChange:t},r,n){super(r,n),this.name="AssetsContractController",this.defaultConfig={provider:undefined,ipfsGateway:c.IPFS_DEFAULT_GATEWAY_URL,chainId:u.SupportedTokenDetectionNetworks.mainnet},this.initialize(),e((({ipfsGateway:e})=>{this.configure({ipfsGateway:e})})),t((e=>{this.config.chainId!==e.provider.chainId&&this.configure({chainId:e.provider.chainId})}))}set provider(e){this.web3=new s.default(e),this.erc721Standard=new l.ERC721Standard(this.web3),this.erc1155Standard=new d.ERC1155Standard(this.web3),this.erc20Standard=new h.ERC20Standard(this.web3)}get provider(){throw new Error("Property only used for setting")}getERC20BalanceOf(e,t){return n(this,void 0,void 0,(function*(){if(!this.erc20Standard)throw new Error(r.MISSING_PROVIDER_ERROR);return this.erc20Standard.getBalanceOf(e,t)}))}getERC20TokenDecimals(e){return n(this,void 0,void 0,(function*(){if(this.erc20Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return yield this.erc20Standard.getTokenDecimals(e)}))}getERC721CollectibleTokenId(e,t,n){if(this.erc721Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return this.erc721Standard.getCollectibleTokenId(e,t,n)}getTokenStandardAndDetails(e,t,i){return n(this,void 0,void 0,(function*(){if(this.erc721Standard===undefined||this.erc1155Standard===undefined||this.erc20Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);const{ipfsGateway:n}=this.config;try{return Object.assign({},yield this.erc721Standard.getDetails(e,n,i))}catch(e){}try{return Object.assign({},yield this.erc1155Standard.getDetails(e,n,i))}catch(e){}try{return Object.assign({},yield this.erc20Standard.getDetails(e,t))}catch(e){}throw new Error("Unable to determine contract standard")}))}getERC721TokenURI(e,t){return n(this,void 0,void 0,(function*(){if(this.erc721Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return this.erc721Standard.getTokenURI(e,t)}))}getERC721AssetName(e){return n(this,void 0,void 0,(function*(){if(this.erc721Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return this.erc721Standard.getAssetName(e)}))}getERC721AssetSymbol(e){return n(this,void 0,void 0,(function*(){if(this.erc721Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return this.erc721Standard.getAssetSymbol(e)}))}getERC721OwnerOf(e,t){return n(this,void 0,void 0,(function*(){if(this.erc721Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return this.erc721Standard.getOwnerOf(e,t)}))}getERC1155TokenURI(e,t){return n(this,void 0,void 0,(function*(){if(this.erc1155Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return this.erc1155Standard.getTokenURI(e,t)}))}getERC1155BalanceOf(e,t,i){return n(this,void 0,void 0,(function*(){if(this.erc1155Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return yield this.erc1155Standard.getBalanceOf(t,e,i)}))}transferSingleERC1155(e,t,i,s,o){return n(this,void 0,void 0,(function*(){if(this.erc1155Standard===undefined)throw new Error(r.MISSING_PROVIDER_ERROR);return yield this.erc1155Standard.transferSingle(e,t,i,s,o)}))}getBalancesInSingleCall(e,t){return n(this,void 0,void 0,(function*(){if(!(this.config.chainId in r.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID))return{};const n=r.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[this.config.chainId],i=this.web3.eth.contract(o.default).at(n);return new Promise(((r,n)=>{i.balances([e],t,((e,i)=>{if(e)return void n(e);const s={};i.length>0&&t.forEach(((e,t)=>{const r=i[t];"0"!==String(r)&&(s[e]=r)})),r(s)}))}))}))}}r.AssetsContractController=f,r.default=f}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1443,{"../BaseController":1433,"../constants":1455,"../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.CollectibleDetectionController=void 0;const i=e("../BaseController"),s=e("../util"),o=e("../constants");class a extends i.BaseController{constructor({onPreferencesStateChange:e,onNetworkStateChange:t,getOpenSeaApiKey:r,addCollectible:n,getCollectiblesState:i},s,a){super(s,a),this.name="CollectibleDetectionController",this.isMainnet=()=>this.config.networkType===o.MAINNET,this.defaultConfig={interval:18e4,networkType:o.MAINNET,chainId:"1",selectedAddress:"",disabled:!0},this.initialize(),this.getCollectiblesState=i,e((({selectedAddress:e,useCollectibleDetection:t})=>{const{selectedAddress:r,disabled:n}=this.config;e===r&&!t===n||this.configure({selectedAddress:e,disabled:!t}),t!==undefined&&(t?this.start():this.stop())})),t((({provider:e})=>{this.configure({networkType:e.type,chainId:e.chainId})})),this.getOpenSeaApiKey=r,this.addCollectible=n}getOwnerCollectiblesApi({address:e,offset:t,useProxy:r}){return r?`${o.OPENSEA_PROXY_URL}/assets?owner=${e}&offset=${t}&limit=50`:`${o.OPENSEA_API_URL}/assets?owner=${e}&offset=${t}&limit=50`}getOwnerCollectibles(e){var t;return n(this,void 0,void 0,(function*(){let r,n=[];const i=this.getOpenSeaApiKey();let o=0,a=!1;do{if(r=yield(0,s.fetchWithErrorHandling)({url:this.getOwnerCollectiblesApi({address:e,offset:o,useProxy:!0}),timeout:15e3}),i&&!r&&(r=yield(0,s.fetchWithErrorHandling)({url:this.getOwnerCollectiblesApi({address:e,offset:o,useProxy:!1}),options:{headers:{"X-API-KEY":i}},timeout:15e3,errorCodesToCatch:[403]})),!r)return n;0!==(null===(t=null==r?void 0:r.assets)||void 0===t?void 0:t.length)?n=[...n,...r.assets]:a=!0,o+=50}while(!a);return n}))}start(){return n(this,void 0,void 0,(function*(){this.isMainnet()&&!this.disabled&&(yield this.startPolling())}))}stop(){this.stopPolling()}stopPolling(){this.intervalId&&clearInterval(this.intervalId)}startPolling(e){return n(this,void 0,void 0,(function*(){e&&this.configure({interval:e},!1,!1),this.stopPolling(),yield this.detectCollectibles(),this.intervalId=setInterval((()=>n(this,void 0,void 0,(function*(){yield this.detectCollectibles()}))),this.config.interval)}))}detectCollectibles(){return n(this,void 0,void 0,(function*(){if(!this.isMainnet()||this.disabled)return;const{selectedAddress:e,chainId:t}=this.config;if(!e)return;const r=(yield this.getOwnerCollectibles(e)).map((r=>n(this,void 0,void 0,(function*(){const{token_id:n,num_sales:i,background_color:o,image_url:a,image_preview_url:c,image_thumbnail_url:u,image_original_url:l,animation_url:d,animation_original_url:h,name:f,description:p,external_link:m,creator:g,asset_contract:{address:v,schema_name:y},last_sale:w}=r;let b;const{ignoredCollectibles:P}=this.getCollectiblesState();if(P.length&&(b=P.find((e=>e.address===(0,s.toChecksumHexAddress)(v)&&e.tokenId===n))),!b){const r=Object.assign({},{name:f},g&&{creator:g},p&&{description:p},a&&{image:a},i&&{numberOfSales:i},o&&{backgroundColor:o},c&&{imagePreview:c},u&&{imageThumbnail:u},l&&{imageOriginal:l},d&&{animation:d},h&&{animationOriginal:h},y&&{standard:y},m&&{externalLink:m},w&&{lastSale:w});yield this.addCollectible(v,n,r,{userAddress:e,chainId:t})}}))));yield Promise.all(r)}))}}r.CollectibleDetectionController=a,r.default=a}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1444,{"../BaseController":1433,"../constants":1455,"../util":1489,"./assetsUtil":1454,"async-mutex":1830,"ethereumjs-util":2612,events:2176},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.CollectiblesController=void 0;const i=e("events"),s=e("ethereumjs-util"),o=e("async-mutex"),a=e("../BaseController"),c=e("../util"),u=e("../constants"),l=e("./assetsUtil"),d="allCollectibles",h="allCollectibleContracts";class f extends a.BaseController{constructor({onPreferencesStateChange:e,onNetworkStateChange:t,getERC721AssetName:r,getERC721AssetSymbol:n,getERC721TokenURI:s,getERC721OwnerOf:a,getERC1155BalanceOf:c,getERC1155TokenURI:l,onCollectibleAdded:d},h,f){super(h,f),this.mutex=new o.Mutex,this.hub=new i.EventEmitter,this.name="CollectiblesController",this.defaultConfig={networkType:u.MAINNET,selectedAddress:"",chainId:"",ipfsGateway:u.IPFS_DEFAULT_GATEWAY_URL,openSeaEnabled:!1,useIPFSSubdomains:!0},this.defaultState={allCollectibleContracts:{},allCollectibles:{},ignoredCollectibles:[]},this.initialize(),this.getERC721AssetName=r,this.getERC721AssetSymbol=n,this.getERC721TokenURI=s,this.getERC721OwnerOf=a,this.getERC1155BalanceOf=c,this.getERC1155TokenURI=l,this.onCollectibleAdded=d,e((({selectedAddress:e,ipfsGateway:t,openSeaEnabled:r})=>{this.configure({selectedAddress:e,ipfsGateway:t,openSeaEnabled:r})})),t((({provider:e})=>{const{chainId:t}=e;this.configure({chainId:t})}))}getCollectibleApi({contractAddress:e,tokenId:t,useProxy:r}){const{chainId:n}=this.config;return n===u.RINKEBY_CHAIN_ID?`${u.OPENSEA_TEST_API_URL}/asset/${e}/${t}`:r?`${u.OPENSEA_PROXY_URL}/asset/${e}/${t}`:`${u.OPENSEA_API_URL}/asset/${e}/${t}`}getCollectibleContractInformationApi({contractAddress:e,useProxy:t}){const{chainId:r}=this.config;return r===u.RINKEBY_CHAIN_ID?`${u.OPENSEA_TEST_API_URL}/asset_contract/${e}`:t?`${u.OPENSEA_PROXY_URL}/asset_contract/${e}`:`${u.OPENSEA_API_URL}/asset_contract/${e}`}updateNestedCollectibleState(e,t,{userAddress:r,chainId:n}={userAddress:this.config.selectedAddress,chainId:this.config.chainId}){const{[t]:i}=this.state,s=i[r],o=Object.assign(Object.assign({},s),{[n]:e}),a=Object.assign(Object.assign({},i),{[r]:o});this.update({[t]:a})}getCollectibleInformationFromApi(e,t){return n(this,void 0,void 0,(function*(){let r=yield(0,c.fetchWithErrorHandling)({url:this.getCollectibleApi({contractAddress:e,tokenId:t,useProxy:!0})});if(!r&&this.openSeaApiKey&&(r=yield(0,c.fetchWithErrorHandling)({url:this.getCollectibleApi({contractAddress:e,tokenId:t,useProxy:!1}),options:{headers:{"X-API-KEY":this.openSeaApiKey}},errorCodesToCatch:[403]})),!r)return{name:null,description:null,image:null,standard:null};const{num_sales:n,background_color:i,image_url:s,image_preview_url:o,image_thumbnail_url:a,image_original_url:u,animation_url:l,animation_original_url:d,name:h,description:f,external_link:p,creator:m,last_sale:g,asset_contract:{schema_name:v}}=r;return Object.assign({},{name:h||null},{description:f||null},{image:s||null},m&&{creator:m},n&&{numberOfSales:n},i&&{backgroundColor:i},o&&{imagePreview:o},a&&{imageThumbnail:a},u&&{imageOriginal:u},l&&{animation:l},d&&{animationOriginal:d},p&&{externalLink:p},g&&{lastSale:g},v&&{standard:v})}))}getCollectibleInformationFromTokenURI(e,t){return n(this,void 0,void 0,(function*(){const{ipfsGateway:r,useIPFSSubdomains:n}=this.config,i=yield this.getCollectibleURIAndStandard(e,t);let s=i[0];const o=i[1];s.startsWith("ipfs://")&&(s=(0,c.getFormattedIpfsUrl)(r,s,n));try{const e=yield(0,c.handleFetch)(s);return{image:e[Object.prototype.hasOwnProperty.call(e,"image")?"image":"image_url"],name:e.name,description:e.description,standard:o,favorite:!1}}catch(e){return{image:null,name:null,description:null,standard:o||null,favorite:!1}}}))}getCollectibleURIAndStandard(e,t){return n(this,void 0,void 0,(function*(){try{return[yield this.getERC721TokenURI(e,t),u.ERC721]}catch(e){}try{const r=yield this.getERC1155TokenURI(e,t);if(!r.includes("{id}"))return[r,u.ERC1155];const n=(0,s.stripHexPrefix)((0,c.BNToHex)(new s.BN(t))).padStart(64,"0").toLowerCase();return[r.replace("{id}",n),u.ERC1155]}catch(e){}return["",""]}))}getCollectibleInformation(e,t){var r,i,s,o,a,u,l,d;return n(this,void 0,void 0,(function*(){const h=yield(0,c.safelyExecute)((()=>n(this,void 0,void 0,(function*(){return yield this.getCollectibleInformationFromTokenURI(e,t)}))));let f;return this.config.openSeaEnabled&&(f=yield(0,c.safelyExecute)((()=>n(this,void 0,void 0,(function*(){return yield this.getCollectibleInformationFromApi(e,t)}))))),Object.assign(Object.assign({},f),{name:null!==(i=null!==(r=h.name)&&void 0!==r?r:null==f?void 0:f.name)&&void 0!==i?i:null,description:null!==(o=null!==(s=h.description)&&void 0!==s?s:null==f?void 0:f.description)&&void 0!==o?o:null,image:null!==(u=null!==(a=h.image)&&void 0!==a?a:null==f?void 0:f.image)&&void 0!==u?u:null,standard:null!==(d=null!==(l=h.standard)&&void 0!==l?l:null==f?void 0:f.standard)&&void 0!==d?d:null})}))}getCollectibleContractInformationFromApi(e){return n(this,void 0,void 0,(function*(){let t=yield(0,c.fetchWithErrorHandling)({url:this.getCollectibleContractInformationApi({contractAddress:e,useProxy:!0})});return t||(this.openSeaApiKey&&(t=yield(0,c.fetchWithErrorHandling)({url:this.getCollectibleContractInformationApi({contractAddress:e,useProxy:!1}),options:{headers:{"X-API-KEY":this.openSeaApiKey}},errorCodesToCatch:[403]}),t)?t:{address:e,asset_contract_type:null,created_date:null,schema_name:null,symbol:null,total_supply:null,description:null,external_link:null,collection:{name:null,image_url:null}})}))}getCollectibleContractInformationFromContract(e){return n(this,void 0,void 0,(function*(){return{collection:{name:yield this.getERC721AssetName(e)},symbol:yield this.getERC721AssetSymbol(e),address:e}}))}getCollectibleContractInformation(e){return n(this,void 0,void 0,(function*(){const t=yield(0,c.safelyExecute)((()=>n(this,void 0,void 0,(function*(){return yield this.getCollectibleContractInformationFromContract(e)}))));let r;return this.config.openSeaEnabled&&(r=yield(0,c.safelyExecute)((()=>n(this,void 0,void 0,(function*(){return yield this.getCollectibleContractInformationFromApi(e)}))))),t||r?Object.assign(Object.assign(Object.assign({},r),t),{collection:Object.assign(Object.assign({image_url:null},null==r?void 0:r.collection),null==t?void 0:t.collection)}):{address:e,asset_contract_type:null,created_date:null,schema_name:null,symbol:null,total_supply:null,description:null,external_link:null,collection:{name:null,image_url:null}}}))}addIndividualCollectible(e,t,r,i,s){var o;return n(this,void 0,void 0,(function*(){const n=yield this.mutex.acquire();try{e=(0,c.toChecksumHexAddress)(e);const{allCollectibles:a}=this.state;let u,h;s?(u=s.chainId,h=s.userAddress):(u=this.config.chainId,h=this.config.selectedAddress);const f=(null===(o=a[h])||void 0===o?void 0:o[u])||[],p=f.find((r=>r.address.toLowerCase()===e.toLowerCase()&&r.tokenId===t));if(p){if(!(0,l.compareCollectiblesMetadata)(r,p))return f;{const r=f.findIndex((r=>r.address.toLowerCase()===e.toLowerCase()&&r.tokenId===t));-1!==r&&f.splice(r,1)}}const m=Object.assign({address:e,tokenId:t,favorite:(null==p?void 0:p.favorite)||!1,isCurrentlyOwned:!0},r),g=[...f,m];return this.updateNestedCollectibleState(g,d,{chainId:u,userAddress:h}),this.onCollectibleAdded&&this.onCollectibleAdded({address:e,symbol:i.symbol,tokenId:t.toString(),standard:r.standard,source:s?"detected":"custom"}),g}finally{n()}}))}addCollectibleContract(e,t){var r;return n(this,void 0,void 0,(function*(){const n=yield this.mutex.acquire();try{e=(0,c.toChecksumHexAddress)(e);const{allCollectibleContracts:i}=this.state;let s,o;t?(s=t.chainId,o=t.userAddress):(s=this.config.chainId,o=this.config.selectedAddress);const a=(null===(r=i[o])||void 0===r?void 0:r[s])||[];if(a.find((t=>t.address.toLowerCase()===e.toLowerCase())))return a;const u=yield this.getCollectibleContractInformation(e),{asset_contract_type:l,created_date:d,schema_name:f,symbol:p,total_supply:m,description:g,external_link:v,collection:{name:y,image_url:w}}=u;if(t&&!y||0===Object.keys(u).length)return a;const b=Object.assign({},{address:e},g&&{description:g},y&&{name:y},w&&{logo:w},p&&{symbol:p},null!=m&&{totalSupply:m},l&&{assetContractType:l},d&&{createdDate:d},f&&{schemaName:f},v&&{externalLink:v}),P=[...a,b];return this.updateNestedCollectibleState(P,h,{chainId:s,userAddress:o}),P}finally{n()}}))}removeAndIgnoreIndividualCollectible(e,t){var r;e=(0,c.toChecksumHexAddress)(e);const{allCollectibles:n,ignoredCollectibles:i}=this.state,{chainId:s,selectedAddress:o}=this.config,a=[...i],u=((null===(r=n[o])||void 0===r?void 0:r[s])||[]).filter((r=>{if(r.address.toLowerCase()===e.toLowerCase()&&r.tokenId===t){return!a.find((r=>r.address===e&&r.tokenId===t))&&a.push(r),!1}return!0}));this.updateNestedCollectibleState(u,d),this.update({ignoredCollectibles:a})}removeIndividualCollectible(e,t){var r;e=(0,c.toChecksumHexAddress)(e);const{allCollectibles:n}=this.state,{chainId:i,selectedAddress:s}=this.config,o=((null===(r=n[s])||void 0===r?void 0:r[i])||[]).filter((r=>!(r.address.toLowerCase()===e.toLowerCase()&&r.tokenId===t)));this.updateNestedCollectibleState(o,d)}removeCollectibleContract(e){var t;e=(0,c.toChecksumHexAddress)(e);const{allCollectibleContracts:r}=this.state,{chainId:n,selectedAddress:i}=this.config,s=((null===(t=r[i])||void 0===t?void 0:t[n])||[]).filter((t=>!(t.address.toLowerCase()===e.toLowerCase())));return this.updateNestedCollectibleState(s,h),s}setApiKey(e){this.openSeaApiKey=e}isCollectibleOwner(e,t,r){return n(this,void 0,void 0,(function*(){try{const n=yield this.getERC721OwnerOf(t,r);return e.toLowerCase()===n.toLowerCase()}catch(e){}try{return(yield this.getERC1155BalanceOf(e,t,r))>0}catch(e){}throw new Error("Unable to verify ownership. Probably because the standard is not supported or the chain is incorrect.")}))}addCollectibleVerifyOwnership(e,t){return n(this,void 0,void 0,(function*(){const{selectedAddress:r}=this.config;if(!(yield this.isCollectibleOwner(r,e,t)))throw new Error("This collectible is not owned by the user");yield this.addCollectible(e,t)}))}addCollectible(e,t,r,i){return n(this,void 0,void 0,(function*(){e=(0,c.toChecksumHexAddress)(e);const n=yield this.addCollectibleContract(e,i);r=r||(yield this.getCollectibleInformation(e,t));const s=n.find((t=>t.address.toLowerCase()===e.toLowerCase()));s&&(yield this.addIndividualCollectible(e,t,r,s,i))}))}removeCollectible(e,t){var r;e=(0,c.toChecksumHexAddress)(e),this.removeIndividualCollectible(e,t);const{allCollectibles:n}=this.state,{chainId:i,selectedAddress:s}=this.config;((null===(r=n[s])||void 0===r?void 0:r[i])||[]).find((t=>t.address.toLowerCase()===e.toLowerCase()))||this.removeCollectibleContract(e)}removeAndIgnoreCollectible(e,t){var r;e=(0,c.toChecksumHexAddress)(e),this.removeAndIgnoreIndividualCollectible(e,t);const{allCollectibles:n}=this.state,{chainId:i,selectedAddress:s}=this.config;((null===(r=n[s])||void 0===r?void 0:r[i])||[]).find((t=>t.address.toLowerCase()===e.toLowerCase()))||this.removeCollectibleContract(e)}clearIgnoredCollectibles(){this.update({ignoredCollectibles:[]})}checkAndUpdateSingleCollectibleOwnershipStatus(e,t,{userAddress:r,chainId:i}={userAddress:this.config.selectedAddress,chainId:this.config.chainId}){var s;return n(this,void 0,void 0,(function*(){const{address:n,tokenId:o}=e;let a=e.isCurrentlyOwned;try{a=yield this.isCollectibleOwner(r,n,o)}catch(e){if(!(e instanceof Error&&e.message.includes("Unable to verify ownership")))throw e}if(e.isCurrentlyOwned=a,!0===t)return e;const{allCollectibles:c}=this.state,u=(null===(s=c[r])||void 0===s?void 0:s[i])||[],l=u.find((e=>e.tokenId===o&&e.address.toLowerCase()===n.toLowerCase()));return l&&(l.isCurrentlyOwned=a,this.updateNestedCollectibleState(u,d,{userAddress:r,chainId:i})),e}))}checkAndUpdateAllCollectiblesOwnershipStatus(){var e;return n(this,void 0,void 0,(function*(){const{allCollectibles:t}=this.state,{chainId:r,selectedAddress:i}=this.config,s=(null===(e=t[i])||void 0===e?void 0:e[r])||[],o=yield Promise.all(s.map((e=>n(this,void 0,void 0,(function*(){var t;return null!==(t=yield this.checkAndUpdateSingleCollectibleOwnershipStatus(e,!0))&&void 0!==t?t:e})))));this.updateNestedCollectibleState(o,d)}))}updateCollectibleFavoriteStatus(e,t,r){var n;const{allCollectibles:i}=this.state,{chainId:s,selectedAddress:o}=this.config,a=(null===(n=i[o])||void 0===n?void 0:n[s])||[],c=a.findIndex((r=>r.address===e&&r.tokenId===t));if(-1===c)return;const u=Object.assign(Object.assign({},a[c]),{favorite:r});a[c]=u,this.updateNestedCollectibleState(a,d)}}r.CollectiblesController=f,r.default=f}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1445,{"../BaseControllerV2":1434,"../apis/crypto-compare":1438,"../constants":1455,"../util":1489,"async-mutex":1830},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.CurrencyRateController=void 0;const i=e("async-mutex"),s=e("../BaseControllerV2"),o=e("../util"),a=e("../apis/crypto-compare"),c=e("../constants"),u={conversionDate:{persist:!0,anonymous:!0},conversionRate:{persist:!0,anonymous:!0},currentCurrency:{persist:!0,anonymous:!0},nativeCurrency:{persist:!0,anonymous:!0},pendingCurrentCurrency:{persist:!1,anonymous:!0},pendingNativeCurrency:{persist:!1,anonymous:!0},usdConversionRate:{persist:!0,anonymous:!0}},l={conversionDate:0,conversionRate:0,currentCurrency:"usd",nativeCurrency:"ETH",pendingCurrentCurrency:null,pendingNativeCurrency:null,usdConversionRate:null};class d extends s.BaseController{constructor({includeUsdRate:e=!1,interval:t=18e4,messenger:r,state:n,fetchExchangeRate:s=a.fetchExchangeRate}){super({name:"CurrencyRateController",metadata:u,messenger:r,state:Object.assign(Object.assign({},l),n)}),this.mutex=new i.Mutex,this.includeUsdRate=e,this.intervalDelay=t,this.fetchExchangeRate=s}start(){return n(this,void 0,void 0,(function*(){yield this.startPolling()}))}stop(){this.stopPolling()}destroy(){super.destroy(),this.stopPolling()}setCurrentCurrency(e){return n(this,void 0,void 0,(function*(){this.update((t=>{t.pendingCurrentCurrency=e})),yield this.updateExchangeRate()}))}setNativeCurrency(e){return n(this,void 0,void 0,(function*(){this.update((t=>{t.pendingNativeCurrency=e})),yield this.updateExchangeRate()}))}stopPolling(){this.intervalId&&clearInterval(this.intervalId)}startPolling(){return n(this,void 0,void 0,(function*(){this.stopPolling(),yield(0,o.safelyExecute)((()=>this.updateExchangeRate())),this.intervalId=setInterval((()=>n(this,void 0,void 0,(function*(){yield(0,o.safelyExecute)((()=>this.updateExchangeRate()))}))),this.intervalDelay)}))}updateExchangeRate(){return n(this,void 0,void 0,(function*(){const e=yield this.mutex.acquire(),{currentCurrency:t,nativeCurrency:r,pendingCurrentCurrency:n,pendingNativeCurrency:i}=this.state;let s=null,o=null,a=null;const u=null!=n?n:t,l=null!=i?i:r,d=Object.values(c.TESTNET_TICKER_SYMBOLS).includes(l)?c.FALL_BACK_VS_CURRENCY:l;try{u&&l&&""!==u&&""!==l&&(({conversionRate:o,usdConversionRate:a}=yield this.fetchExchangeRate(u,d,this.includeUsdRate)),s=Date.now()/1e3)}catch(e){if(!(e instanceof Error&&e.message.includes("market does not exist for this coin pair")))throw e}finally{try{this.update((()=>({conversionDate:s,conversionRate:o,nativeCurrency:l,currentCurrency:u,pendingCurrentCurrency:null,pendingNativeCurrency:null,usdConversionRate:a})))}finally{e()}}return this.state}))}}r.CurrencyRateController=d,r.default=d}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1446,{"../../../../constants":1455,"../../../../util":1489,"@metamask/metamask-eth-abis":1195},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.ERC1155Standard=void 0;const i=e("@metamask/metamask-eth-abis"),s=e("../../../../constants"),o=e("../../../../util");r.ERC1155Standard=class{constructor(e){this.contractSupportsURIMetadataInterface=e=>n(this,void 0,void 0,(function*(){return this.contractSupportsInterface(e,s.ERC1155_METADATA_URI_INTERFACE_ID)})),this.contractSupportsTokenReceiverInterface=e=>n(this,void 0,void 0,(function*(){return this.contractSupportsInterface(e,s.ERC1155_TOKEN_RECEIVER_INTERFACE_ID)})),this.contractSupportsBase1155Interface=e=>n(this,void 0,void 0,(function*(){return this.contractSupportsInterface(e,s.ERC1155_INTERFACE_ID)})),this.getTokenURI=(e,t)=>n(this,void 0,void 0,(function*(){const r=this.web3.eth.contract(i.abiERC1155).at(e);return new Promise(((e,n)=>{r.uri(t,((t,r)=>{t?n(t):e(r)}))}))})),this.getBalanceOf=(e,t,r)=>n(this,void 0,void 0,(function*(){const n=this.web3.eth.contract(i.abiERC1155).at(e);return new Promise(((e,i)=>{n.balanceOf(t,r,((t,r)=>{t?i(t):e(r)}))}))})),this.transferSingle=(e,t,r,s,o)=>n(this,void 0,void 0,(function*(){const n=this.web3.eth.contract(i.abiERC1155).at(e);return new Promise(((i,a)=>{n.transferSingle(e,t,r,s,o,((e,t)=>{e?a(e):i(t)}))}))})),this.contractSupportsInterface=(e,t)=>n(this,void 0,void 0,(function*(){const r=this.web3.eth.contract(i.abiERC1155).at(e);return new Promise(((e,n)=>{r.supportsInterface(t,((t,r)=>{t?n(t):e(r)}))}))})),this.getDetails=(e,t,r)=>n(this,void 0,void 0,(function*(){if(!(yield this.contractSupportsBase1155Interface(e)))throw new Error("This isn't a valid ERC1155 contract");let n,i;if(r){n=yield this.getTokenURI(e,r),n.startsWith("ipfs://")&&(n=(0,o.getFormattedIpfsUrl)(t,n,!0));try{const e=yield(0,o.timeoutFetch)(n),r=yield e.json();i=null==r?void 0:r.image,(null==i?void 0:i.startsWith("ipfs://"))&&(i=(0,o.getFormattedIpfsUrl)(t,i,!0))}catch(e){}}return{standard:s.ERC1155,tokenURI:n,image:i}})),this.web3=e}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1447,{"../../../../constants":1455,"../../../../util":1489,"@metamask/metamask-eth-abis":1195},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.ERC721Standard=void 0;const i=e("@metamask/metamask-eth-abis"),s=e("../../../../util"),o=e("../../../../constants");r.ERC721Standard=class{constructor(e){this.contractSupportsMetadataInterface=e=>n(this,void 0,void 0,(function*(){return this.contractSupportsInterface(e,o.ERC721_METADATA_INTERFACE_ID)})),this.contractSupportsEnumerableInterface=e=>n(this,void 0,void 0,(function*(){return this.contractSupportsInterface(e,o.ERC721_ENUMERABLE_INTERFACE_ID)})),this.contractSupportsBase721Interface=e=>n(this,void 0,void 0,(function*(){return this.contractSupportsInterface(e,o.ERC721_INTERFACE_ID)})),this.getCollectibleTokenId=(e,t,r)=>n(this,void 0,void 0,(function*(){const n=this.web3.eth.contract(i.abiERC721).at(e);return new Promise(((e,i)=>{n.tokenOfOwnerByIndex(t,r,((t,r)=>{t?i(t):e(r)}))}))})),this.getTokenURI=(e,t)=>n(this,void 0,void 0,(function*(){const r=this.web3.eth.contract(i.abiERC721).at(e);if(!(yield this.contractSupportsMetadataInterface(e)))throw new Error("Contract does not support ERC721 metadata interface.");return new Promise(((e,n)=>{r.tokenURI(t,((t,r)=>{t?n(t):e(r)}))}))})),this.getAssetName=e=>n(this,void 0,void 0,(function*(){const t=this.web3.eth.contract(i.abiERC721).at(e);return new Promise(((e,r)=>{t.name(((t,n)=>{t?r(t):e(n)}))}))})),this.getAssetSymbol=e=>n(this,void 0,void 0,(function*(){const t=this.web3.eth.contract(i.abiERC721).at(e);return new Promise(((e,r)=>{t.symbol(((t,n)=>{t?r(t):e(n)}))}))})),this.contractSupportsInterface=(e,t)=>n(this,void 0,void 0,(function*(){const r=this.web3.eth.contract(i.abiERC721).at(e);return new Promise(((e,n)=>{r.supportsInterface(t,((t,r)=>{t?n(t):e(r)}))}))})),this.getDetails=(e,t,r)=>n(this,void 0,void 0,(function*(){if(!(yield this.contractSupportsBase721Interface(e)))throw new Error("This isn't a valid ERC721 contract");let n,i,a,c;try{a=yield this.getAssetSymbol(e)}catch(e){}try{c=yield this.getAssetName(e)}catch(e){}if(r)try{n=yield this.getTokenURI(e,r),n.startsWith("ipfs://")&&(n=(0,s.getFormattedIpfsUrl)(t,n,!0));const o=yield(0,s.timeoutFetch)(n),a=yield o.json();i=null==a?void 0:a.image,(null==i?void 0:i.startsWith("ipfs://"))&&(i=(0,s.getFormattedIpfsUrl)(t,i,!0))}catch(e){}return{standard:o.ERC721,tokenURI:n,symbol:a,name:c,image:i}})),this.web3=e}getOwnerOf(e,t){return n(this,void 0,void 0,(function*(){const r=this.web3.eth.contract(i.abiERC721).at(e);return new Promise(((e,n)=>{r.ownerOf(t,((t,r)=>{t?n(t):e(r)}))}))}))}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1448,{"../../constants":1455,"@metamask/metamask-eth-abis":1195,"ethereumjs-util":2612,"ethers/lib/utils":2637},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.ERC20Standard=void 0;const i=e("@metamask/metamask-eth-abis"),s=e("ethereumjs-util"),o=e("ethers/lib/utils"),a=e("../../constants");r.ERC20Standard=class{constructor(e){this.web3=e}getBalanceOf(e,t){return n(this,void 0,void 0,(function*(){const r=this.web3.eth.contract(i.abiERC20).at(e);return new Promise(((e,n)=>{r.balanceOf(t,((t,r)=>{t?n(t):e(r)}))}))}))}getTokenDecimals(e){return n(this,void 0,void 0,(function*(){const t=this.web3.eth.contract(i.abiERC20).at(e);return new Promise(((e,r)=>{t.decimals(((t,n)=>{t?r(t):e(n.toString())}))}))}))}getTokenSymbol(e){return n(this,void 0,void 0,(function*(){const t={to:e,data:"0x95d89b41"};return new Promise(((e,r)=>{this.web3.eth.call(t,undefined,((t,n)=>{if(t)return void r(t);const i=new o.AbiCoder;try{const t=i.decode(["string"],n)[0];if(t)return void e(t)}catch(e){}try{const t=(0,s.toUtf8)(n);return void e(t)}catch(e){}r(new Error("Failed to parse token symbol"))}))}))}))}getDetails(e,t){return n(this,void 0,void 0,(function*(){const[r,n]=yield Promise.all([this.getTokenDecimals(e),this.getTokenSymbol(e)]);let i;return t&&(i=yield this.getBalanceOf(e,t)),{decimals:r,symbol:n,balance:i,standard:a.ERC20}}))}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1449,{"../BaseController":1433,"../util":1489,"ethereumjs-util":2612},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.TokenBalancesController=r.BN=void 0;const i=e("ethereumjs-util");Object.defineProperty(r,"BN",{enumerable:!0,get:function(){return i.BN}});const s=e("../BaseController"),o=e("../util");class a extends s.BaseController{constructor({onTokensStateChange:e,getSelectedAddress:t,getERC20BalanceOf:r},n,i){super(n,i),this.name="TokenBalancesController",this.defaultConfig={interval:18e4,tokens:[]},this.defaultState={contractBalances:{}},this.initialize(),e((({tokens:e,detectedTokens:t})=>{this.configure({tokens:[...e,...t]}),this.updateBalances()})),this.getSelectedAddress=t,this.getERC20BalanceOf=r,this.poll()}poll(e){return n(this,void 0,void 0,(function*(){e&&this.configure({interval:e},!1,!1),this.handle&&clearTimeout(this.handle),yield(0,o.safelyExecute)((()=>this.updateBalances())),this.handle=setTimeout((()=>{this.poll(this.config.interval)}),this.config.interval)}))}updateBalances(){return n(this,void 0,void 0,(function*(){if(this.disabled)return;const{tokens:e}=this.config,t={};for(const r in e){const{address:n}=e[r];try{t[n]=yield this.getERC20BalanceOf(n,this.getSelectedAddress()),e[r].balanceError=null}catch(s){t[n]=new i.BN(0),e[r].balanceError=s}}this.update({contractBalances:t})}))}}r.TokenBalancesController=a,r.default=a}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[145,{lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash");var i={version:62,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=62;const r=function(e){if(e.MetaMetricsController){const{metaMetricsSendCount:t}=e.MetaMetricsController;t!==undefined&&delete e.MetaMetricsController.metaMetricsSendCount}return e}(t.data);return t.data=r,t}};r.default=i}}},{package:"$root$"}],[1450,{"../BaseController":1433,"../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.TokenDetectionController=void 0;const i=e("../BaseController"),s=e("../util");class o extends i.BaseController{constructor({onPreferencesStateChange:e,onNetworkStateChange:t,onTokenListStateChange:r,getBalancesInSingleCall:n,addDetectedTokens:i,getTokenListState:o,getTokensState:a,getNetworkState:c,getPreferencesState:u},l,d){const{provider:{chainId:h}}=c(),{useTokenDetection:f}=u();super(l,d),this.name="TokenDetectionController",this.defaultConfig=Object.assign({interval:18e4,selectedAddress:"",disabled:!0,chainId:h,isDetectionEnabledFromPreferences:f,isDetectionEnabledForNetwork:(0,s.isTokenDetectionSupportedForNetwork)(h)},l),this.initialize(),this.getTokensState=a,this.getTokenListState=o,this.addDetectedTokens=i,this.getBalancesInSingleCall=n,r((({tokenList:e})=>{Object.keys(e).length&&this.detectTokens()})),e((({selectedAddress:e,useTokenDetection:t})=>{const{selectedAddress:r,isDetectionEnabledFromPreferences:n}=this.config,i=e!==r,s=n!==t;this.configure({isDetectionEnabledFromPreferences:t,selectedAddress:e}),t&&(i||s)&&this.detectTokens()})),t((({provider:{chainId:e}})=>{const{chainId:t}=this.config,r=(0,s.isTokenDetectionSupportedForNetwork)(e),n=t!==e;this.configure({chainId:e,isDetectionEnabledForNetwork:r}),r&&n&&this.detectTokens()}))}start(){return n(this,void 0,void 0,(function*(){this.configure({disabled:!1}),yield this.startPolling()}))}stop(){this.configure({disabled:!0}),this.stopPolling()}stopPolling(){this.intervalId&&clearInterval(this.intervalId)}startPolling(e){return n(this,void 0,void 0,(function*(){e&&this.configure({interval:e},!1,!1),this.stopPolling(),yield this.detectTokens(),this.intervalId=setInterval((()=>n(this,void 0,void 0,(function*(){yield this.detectTokens()}))),this.config.interval)}))}detectTokens(){return n(this,void 0,void 0,(function*(){const{disabled:e,isDetectionEnabledForNetwork:t,isDetectionEnabledFromPreferences:r}=this.config;if(e||!t||!r)return;const{tokens:i}=this.getTokensState(),{selectedAddress:o}=this.config,a=i.map((e=>e.address.toLowerCase())),{tokenList:c}=this.getTokenListState(),u=[];for(const e in c)a.includes(e)||u.push(e);const l=[];if(l[0]=u.slice(0,1e3),l[1]=u.slice(1e3,u.length-1),o)for(const e of l){if(0===e.length)break;yield(0,s.safelyExecute)((()=>n(this,void 0,void 0,(function*(){const t=yield this.getBalancesInSingleCall(o,e),r=[];for(const e in t){let t;const{ignoredTokens:n}=this.getTokensState();n.length&&(t=n.find((t=>t===(0,s.toChecksumHexAddress)(e))));const i=Object.keys(c).find((t=>t.toLowerCase()===e.toLowerCase()))||"";if(t===undefined){const{decimals:t,symbol:n,aggregators:s,iconUrl:o}=c[i];r.push({address:e,decimals:t,symbol:n,aggregators:s,image:o,isERC721:!1})}}r.length&&(yield this.addDetectedTokens(r))}))))}}))}}r.TokenDetectionController=o,r.default=o}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1451,{"../BaseControllerV2":1434,"../apis/token-service":1439,"../util":1489,"./assetsUtil":1454,"abort-controller":1772,"async-mutex":1830},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.TokenListController=void 0;const i=e("async-mutex"),s=e("abort-controller"),o=e("../BaseControllerV2"),a=e("../util"),c=e("../apis/token-service"),u=e("./assetsUtil"),l={tokenList:{persist:!0,anonymous:!0},tokensChainsCache:{persist:!0,anonymous:!0}},d={tokenList:{},tokensChainsCache:{}};class h extends o.BaseController{constructor({chainId:e,onNetworkStateChange:t,interval:r=864e5,cacheRefreshThreshold:o=864e5,messenger:a,state:c}){super({name:"TokenListController",metadata:l,messenger:a,state:Object.assign(Object.assign({},d),c)}),this.mutex=new i.Mutex,this.intervalDelay=r,this.cacheRefreshThreshold=o,this.chainId=e,this.abortController=new s.AbortController,t((e=>n(this,void 0,void 0,(function*(){this.chainId!==e.provider.chainId&&(this.abortController.abort(),this.abortController=new s.AbortController,this.chainId=e.provider.chainId,this.update((()=>{var e;return Object.assign(Object.assign({},this.state),{tokenList:(null===(e=this.state.tokensChainsCache[this.chainId])||void 0===e?void 0:e.data)||{}})})),yield this.restart())}))))}start(){return n(this,void 0,void 0,(function*(){(0,a.isTokenDetectionSupportedForNetwork)(this.chainId)&&(yield this.startPolling())}))}restart(){return n(this,void 0,void 0,(function*(){this.stopPolling(),yield this.startPolling()}))}stop(){this.stopPolling()}destroy(){super.destroy(),this.stopPolling()}stopPolling(){this.intervalId&&clearInterval(this.intervalId)}startPolling(){return n(this,void 0,void 0,(function*(){yield(0,a.safelyExecute)((()=>this.fetchTokenList())),this.intervalId=setInterval((()=>n(this,void 0,void 0,(function*(){yield(0,a.safelyExecute)((()=>this.fetchTokenList()))}))),this.intervalDelay)}))}fetchTokenList(){var e;return n(this,void 0,void 0,(function*(){const t=yield this.mutex.acquire();try{const{tokensChainsCache:r}=this.state;let n={};const i=yield(0,a.safelyExecute)((()=>this.fetchFromCache()));if(i)n=Object.assign({},i);else{const t=yield(0,a.safelyExecute)((()=>(0,c.fetchTokenList)(this.chainId,this.abortController.signal)));if(!t)return n=Object.assign({},(null===(e=r[this.chainId])||void 0===e?void 0:e.data)||{}),void this.update((()=>({tokenList:n,tokensChainsCache:r})));const i=t.filter((e=>e.occurrences&&e.occurrences>=3&&"0x0000000000000000000000000000000000000000"!==e.address)),s=i.map((e=>e.symbol)),o=[...new Set(s.filter(((e,t)=>s.indexOf(e)!==t)))],l=i.filter((e=>!o.includes(e.symbol)));for(const e of l){const t=Object.assign(Object.assign({},e),{aggregators:(0,u.formatAggregatorNames)(e.aggregators),iconUrl:(0,u.formatIconUrlWithProxy)({chainId:this.chainId,tokenAddress:e.address})});n[e.address]=t}}const s=Object.assign(Object.assign({},r),{[this.chainId]:{timestamp:Date.now(),data:n}});this.update((()=>({tokenList:n,tokensChainsCache:s})))}finally{t()}}))}fetchFromCache(){return n(this,void 0,void 0,(function*(){const{tokensChainsCache:e}=this.state,t=e[this.chainId],r=Date.now();return(null==t?void 0:t.data)&&r-(null==t?void 0:t.timestamp)@metamask/controllers"}],[1452,{"../BaseController":1433,"../apis/crypto-compare":1438,"../constants":1455,"../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.TokenRatesController=void 0;const i=e("../BaseController"),s=e("../util"),o=e("../constants"),a=e("../apis/crypto-compare"),c={BASE_URL:"https://api.coingecko.com/api/v3",getTokenPriceURL(e,t){return`${this.BASE_URL}/simple/token_price/${e}?${t}`},getPlatformsURL(){return`${this.BASE_URL}/asset_platforms`},getSupportedVsCurrencies(){return`${this.BASE_URL}/simple/supported_vs_currencies`}};function u(e,t){var r;if(!t)return null;const n=null!==(r=t.find((({chain_identifier:t})=>null!==t&&String(t)===e)))&&void 0!==r?r:null;return(null==n?void 0:n.id)||null}class l extends i.BaseController{constructor({onTokensStateChange:e,onCurrencyRateStateChange:t,onNetworkStateChange:r},n,i){super(n,i),this.tokenList=[],this.supportedChains={timestamp:0,data:null},this.supportedVsCurrencies={timestamp:0,data:[]},this.name="TokenRatesController",this.defaultConfig={disabled:!0,interval:18e4,nativeCurrency:"eth",chainId:"",tokens:[],threshold:216e5},this.defaultState={contractExchangeRates:{}},this.initialize(),this.configure({disabled:!1},!1,!1),e((({tokens:e,detectedTokens:t})=>{this.configure({tokens:[...e,...t]})})),t((e=>{this.configure({nativeCurrency:e.nativeCurrency})})),r((({provider:e})=>{const{chainId:t}=e;this.update({contractExchangeRates:{}}),this.configure({chainId:t})})),this.poll()}poll(e){return n(this,void 0,void 0,(function*(){e&&this.configure({interval:e},!1,!1),this.handle&&clearTimeout(this.handle),yield(0,s.safelyExecute)((()=>this.updateExchangeRates())),this.handle=setTimeout((()=>{this.poll(this.config.interval)}),this.config.interval)}))}set chainId(e){!this.disabled&&(0,s.safelyExecute)((()=>this.updateExchangeRates()))}get chainId(){throw new Error("Property only used for setting")}set tokens(e){this.tokenList=e,!this.disabled&&(0,s.safelyExecute)((()=>this.updateExchangeRates()))}get tokens(){throw new Error("Property only used for setting")}fetchExchangeRate(e,t){return n(this,void 0,void 0,(function*(){const r=`contract_addresses=${this.tokenList.map((e=>e.address)).join(",")}&vs_currencies=${t.toLowerCase()}`;return(0,s.handleFetch)(c.getTokenPriceURL(e,r))}))}checkIsSupportedVsCurrency(e){return n(this,void 0,void 0,(function*(){const{threshold:t}=this.config,{timestamp:r,data:n}=this.supportedVsCurrencies;if(Date.now()-r>t){const t=yield(0,s.handleFetch)(c.getSupportedVsCurrencies());return this.supportedVsCurrencies={data:t,timestamp:Date.now()},t.includes(e.toLowerCase())}return n.includes(e.toLowerCase())}))}getChainSlug(){return n(this,void 0,void 0,(function*(){const{threshold:e,chainId:t}=this.config,{data:r,timestamp:n}=this.supportedChains;if(Date.now()-n>e){const e=yield(0,s.handleFetch)(c.getPlatformsURL());return this.supportedChains={data:e,timestamp:Date.now()},u(t,e)}return u(t,r)}))}updateExchangeRates(){return n(this,void 0,void 0,(function*(){if(0===this.tokenList.length||this.disabled)return;const e=yield this.getChainSlug();let t={};if(e){const{nativeCurrency:r}=this.config;t=yield this.fetchAndMapExchangeRates(r,e)}else this.tokenList.forEach((e=>{const r=(0,s.toChecksumHexAddress)(e.address);t[r]=undefined}));this.update({contractExchangeRates:t})}))}fetchAndMapExchangeRates(e,t){return n(this,void 0,void 0,(function*(){const r={};if(yield this.checkIsSupportedVsCurrency(e)){const n=yield this.fetchExchangeRate(t,e);this.tokenList.forEach((t=>{const i=n[t.address.toLowerCase()];r[(0,s.toChecksumHexAddress)(t.address)]=i?i[e.toLowerCase()]:0}))}else{let n,i=0;try{[n,{conversionRate:i}]=yield Promise.all([this.fetchExchangeRate(t,o.FALL_BACK_VS_CURRENCY),(0,a.fetchExchangeRate)(e,o.FALL_BACK_VS_CURRENCY,!1)])}catch(e){if(e instanceof Error&&e.message.includes("market does not exist for this coin pair"))return{};throw e}for(const[e,t]of Object.entries(n)){const n=t[o.FALL_BACK_VS_CURRENCY.toLowerCase()];r[(0,s.toChecksumHexAddress)(e)]=n*i}}return r}))}}r.TokenRatesController=l,r.default=l}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1453,{"../BaseController":1433,"../apis/token-service":1439,"../constants":1455,"../util":1489,"./assetsUtil":1454,"@metamask/contract-metadata":1029,"@metamask/metamask-eth-abis":1195,"abort-controller":1772,"async-mutex":1830,ethers:2636,events:2176,uuid:6096},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.TokensController=void 0;const s=e("events"),o=i(e("@metamask/contract-metadata")),a=e("@metamask/metamask-eth-abis"),c=e("uuid"),u=e("async-mutex"),l=e("ethers"),d=e("abort-controller"),h=e("../BaseController"),f=e("../util"),p=e("../constants"),m=e("../apis/token-service"),g=e("./assetsUtil");var v;!function(e){e.accepted="accepted",e.failed="failed",e.pending="pending",e.rejected="rejected"}(v||(v={}));class y extends h.BaseController{constructor({onPreferencesStateChange:e,onNetworkStateChange:t,config:r,state:n}){super(r,n),this.mutex=new u.Mutex,this.hub=new s.EventEmitter,this.name="TokensController",this.defaultConfig=Object.assign({networkType:p.MAINNET,selectedAddress:"",chainId:"",provider:undefined},r),this.defaultState=Object.assign({tokens:[],ignoredTokens:[],detectedTokens:[],allTokens:{},allIgnoredTokens:{},allDetectedTokens:{},suggestedAssets:[]},n),this.initialize(),this.abortController=new d.AbortController,e((({selectedAddress:e})=>{var t,r,n;const{allTokens:i,allIgnoredTokens:s,allDetectedTokens:o}=this.state,{chainId:a}=this.config;this.configure({selectedAddress:e}),this.update({tokens:(null===(t=i[a])||void 0===t?void 0:t[e])||[],ignoredTokens:(null===(r=s[a])||void 0===r?void 0:r[e])||[],detectedTokens:(null===(n=o[a])||void 0===n?void 0:n[e])||[]})})),t((({provider:e})=>{var t,r,n;const{allTokens:i,allIgnoredTokens:s,allDetectedTokens:o}=this.state,{selectedAddress:a}=this.config,{chainId:c}=e;this.abortController.abort(),this.abortController=new d.AbortController,this.configure({chainId:c}),this.ethersProvider=this._instantiateNewEthersProvider(),this.update({tokens:(null===(t=i[c])||void 0===t?void 0:t[a])||[],ignoredTokens:(null===(r=s[c])||void 0===r?void 0:r[a])||[],detectedTokens:(null===(n=o[c])||void 0===n?void 0:n[a])||[]})}))}failSuggestedAsset(e,t){const r=Object.assign(Object.assign({},e),{status:v.failed,error:t});this.hub.emit(`${e.id}:finished`,r)}fetchTokenMetadata(e){return n(this,void 0,void 0,(function*(){try{return yield(0,m.fetchTokenMetadata)(this.config.chainId,e,this.abortController.signal)}catch(e){if(e instanceof Error&&e.message.includes(m.TOKEN_METADATA_NO_SUPPORT_ERROR))return undefined;throw e}}))}_instantiateNewEthersProvider(){var e;return new l.ethers.providers.Web3Provider(null===(e=this.config)||void 0===e?void 0:e.provider)}addToken(e,t,r,i){return n(this,void 0,void 0,(function*(){const n=this.config.chainId,s=yield this.mutex.acquire();try{e=(0,f.toChecksumHexAddress)(e);const{tokens:o,ignoredTokens:a,detectedTokens:c}=this.state,u=[...o],[l,d]=yield Promise.all([this._detectIsERC721(e),this.fetchTokenMetadata(e)]);if(n!==this.config.chainId)throw new Error("TokensController Error: Switched networks while adding token");const h={address:e,symbol:t,decimals:r,image:i||(0,g.formatIconUrlWithProxy)({chainId:this.config.chainId,tokenAddress:e}),isERC721:l,aggregators:(0,g.formatAggregatorNames)((null==d?void 0:d.aggregators)||[])},p=u.find((t=>t.address.toLowerCase()===e.toLowerCase()));if(p){const e=u.indexOf(p);u[e]=h}else u.push(h);const m=a.filter((t=>t.toLowerCase()!==e.toLowerCase())),v=c.filter((t=>t.address.toLowerCase()!==e.toLowerCase())),{newAllTokens:y,newAllIgnoredTokens:w,newAllDetectedTokens:b}=this._getNewAllTokensState({newTokens:u,newIgnoredTokens:m,newDetectedTokens:v});return this.update({tokens:u,ignoredTokens:m,detectedTokens:v,allTokens:y,allIgnoredTokens:w,allDetectedTokens:b}),u}finally{s()}}))}addTokens(e){return n(this,void 0,void 0,(function*(){const t=yield this.mutex.acquire(),{tokens:r,detectedTokens:n,ignoredTokens:i}=this.state,s={},o=r.reduce(((e,t)=>(e[t.address]=t,e)),{});try{e.forEach((e=>{const{address:t,symbol:r,decimals:n,image:i,aggregators:a}=e,c={address:(0,f.toChecksumHexAddress)(t),symbol:r,decimals:n,image:i,aggregators:a};return o[t]=c,s[t.toLowerCase()]=!0,c}));const r=Object.values(o),a=n.filter((e=>!s[e.address.toLowerCase()])),c=i.filter((e=>!o[e.toLowerCase()])),{newAllTokens:u,newAllDetectedTokens:l,newAllIgnoredTokens:d}=this._getNewAllTokensState({newTokens:r,newDetectedTokens:a,newIgnoredTokens:c});this.update({tokens:r,allTokens:u,detectedTokens:a,allDetectedTokens:l,ignoredTokens:c,allIgnoredTokens:d})}finally{t()}}))}ignoreTokens(e){const{ignoredTokens:t,detectedTokens:r,tokens:n}=this.state,i={};let s=[...t];const o=e.map((e=>{const t=(0,f.toChecksumHexAddress)(e);return i[e.toLowerCase()]=!0,t}));s=[...t,...o];const a=r.filter((e=>!i[e.address.toLowerCase()])),c=n.filter((e=>!i[e.address.toLowerCase()])),{newAllIgnoredTokens:u,newAllDetectedTokens:l,newAllTokens:d}=this._getNewAllTokensState({newIgnoredTokens:s,newDetectedTokens:a,newTokens:c});this.update({ignoredTokens:s,tokens:c,detectedTokens:a,allIgnoredTokens:u,allDetectedTokens:l,allTokens:d})}addDetectedTokens(e){return n(this,void 0,void 0,(function*(){const t=yield this.mutex.acquire(),{tokens:r,detectedTokens:n,ignoredTokens:i}=this.state,s=[...r],o=[...n];try{e.forEach((e=>{const{address:t,symbol:r,decimals:n,image:a,aggregators:c,isERC721:u}=e,l=(0,f.toChecksumHexAddress)(t),d={address:l,symbol:r,decimals:n,image:a,isERC721:u,aggregators:c},h=s.find((e=>e.address.toLowerCase()===l.toLowerCase()));if(h){const e=s.indexOf(h);s[e]=d}else{if(-1===i.indexOf(t)){const e=o.find((e=>e.address.toLowerCase()===l.toLowerCase()));if(e){const t=o.indexOf(e);o[t]=d}else o.push(d)}}}));const{newAllTokens:r,newAllDetectedTokens:n}=this._getNewAllTokensState({newTokens:s,newDetectedTokens:o});this.update({tokens:s,allTokens:r,detectedTokens:o,allDetectedTokens:n})}finally{t()}}))}updateTokenType(e){return n(this,void 0,void 0,(function*(){const t=yield this._detectIsERC721(e),{tokens:r}=this.state,n=r.findIndex((t=>t.address.toLowerCase()===e.toLowerCase()));return r[n].isERC721=t,this.update({tokens:r}),r[n]}))}_detectIsERC721(e){var t,r;return n(this,void 0,void 0,(function*(){const n=(0,f.toChecksumHexAddress)(e);if(!0===(null===(t=o.default[n])||void 0===t?void 0:t.erc721))return Promise.resolve(!0);if(!0===(null===(r=o.default[n])||void 0===r?void 0:r.erc20))return Promise.resolve(!1);const i=yield this._createEthersContract(e,a.abiERC721,this.ethersProvider);try{return yield i.supportsInterface(p.ERC721_INTERFACE_ID)}catch(e){return!1}}))}_createEthersContract(e,t,r){return n(this,void 0,void 0,(function*(){return yield new l.ethers.Contract(e,t,r)}))}_generateRandomId(){return(0,c.v1)()}watchAsset(e,t){return n(this,void 0,void 0,(function*(){const r={asset:e,id:this._generateRandomId(),status:v.pending,time:Date.now(),type:t};try{if("ERC20"!==t)throw new Error(`Asset of type ${t} not supported`);(0,f.validateTokenToWatch)(e)}catch(e){return this.failSuggestedAsset(r,e),Promise.reject(e)}const n=new Promise(((e,t)=>{this.hub.once(`${r.id}:finished`,(r=>{switch(r.status){case v.accepted:return e(r.asset.address);case v.rejected:return t(new Error("User rejected to watch the asset."));case v.failed:return t(new Error(r.error.message));default:return t(new Error(`Unknown status: ${r.status}`))}}))})),{suggestedAssets:i}=this.state;return i.push(r),this.update({suggestedAssets:[...i]}),this.hub.emit("pendingSuggestedAsset",r),{result:n,suggestedAssetMeta:r}}))}acceptWatchAsset(e){return n(this,void 0,void 0,(function*(){const{suggestedAssets:t}=this.state,r=t.findIndex((({id:t})=>e===t)),n=t[r];try{if("ERC20"!==n.type)throw new Error(`Asset of type ${n.type} not supported`);{const{address:e,symbol:t,decimals:r,image:i}=n.asset;yield this.addToken(e,t,r,i),n.status=v.accepted,this.hub.emit(`${n.id}:finished`,n)}}catch(e){this.failSuggestedAsset(n,e)}const i=t.filter((({id:t})=>t!==e));this.update({suggestedAssets:[...i]})}))}rejectWatchAsset(e){const{suggestedAssets:t}=this.state,r=t.findIndex((({id:t})=>e===t)),n=t[r];if(!n)return;n.status=v.rejected,this.hub.emit(`${n.id}:finished`,n);const i=t.filter((({id:t})=>t!==e));this.update({suggestedAssets:[...i]})}_getNewAllTokensState(e){const{newTokens:t,newIgnoredTokens:r,newDetectedTokens:n}=e,{allTokens:i,allIgnoredTokens:s,allDetectedTokens:o}=this.state,{chainId:a,selectedAddress:c}=this.config;let u=i;if(t){const e=i[a],r=Object.assign(Object.assign({},e),{[c]:t});u=Object.assign(Object.assign({},i),{[a]:r})}let l=s;if(r){const e=s[a],t=Object.assign(Object.assign({},e),{[c]:r});l=Object.assign(Object.assign({},s),{[a]:t})}let d=o;if(n){const e=o[a],t=Object.assign(Object.assign({},e),{[c]:n});d=Object.assign(Object.assign({},o),{[a]:t})}return{newAllTokens:u,newAllIgnoredTokens:l,newAllDetectedTokens:d}}clearIgnoredTokens(){this.update({ignoredTokens:[],allIgnoredTokens:{}})}}r.TokensController=y,r.default=y}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1454,{"../util":1489,"ethereumjs-util":2612},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.formatIconUrlWithProxy=r.formatAggregatorNames=r.compareCollectiblesMetadata=void 0;const n=e("ethereumjs-util"),i=e("../util");r.compareCollectiblesMetadata=function(e,t){return["image","backgroundColor","imagePreview","imageThumbnail","imageOriginal","animation","animationOriginal","externalLink"].reduce(((r,n)=>e[n]&&e[n]!==t[n]?r+1:r),0)>0};const s={aave:"Aave",bancor:"Bancor",cmc:"CMC",cryptocom:"Crypto.com",coinGecko:"CoinGecko",oneInch:"1inch",paraswap:"Paraswap",pmm:"PMM",zapper:"Zapper",zerion:"Zerion",zeroEx:"0x",synthetix:"Synthetix",yearn:"Yearn",apeswap:"ApeSwap",binanceDex:"BinanceDex",pancakeTop100:"PancakeTop100",pancakeExtended:"PancakeExtended",balancer:"Balancer",quickswap:"QuickSwap",matcha:"Matcha",pangolinDex:"PangolinDex",pangolinDexStableCoin:"PangolinDexStableCoin",pangolinDexAvaxBridge:"PangolinDexAvaxBridge",traderJoe:"TraderJoe",airswapLight:"AirswapLight",kleros:"Kleros"};r.formatAggregatorNames=e=>e.map((e=>s[e]||`${e[0].toUpperCase()}${e.substring(1,e.length)}`));r.formatIconUrlWithProxy=({chainId:e,tokenAddress:t})=>{let r=e;return(0,n.isHexString)(e)&&(r=(0,i.convertHexToDecimal)(e).toString()),`https://static.metaswap.codefi.network/api/v1/tokenIcons/${r}/${t.toLowerCase()}.png`}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1455,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.OPENSEA_TEST_API_URL=r.OPENSEA_API_URL=r.OPENSEA_PROXY_URL=r.TESTNET_TICKER_SYMBOLS=r.ASSET_TYPES=r.GWEI=r.ERC1155_TOKEN_RECEIVER_INTERFACE_ID=r.ERC1155_METADATA_URI_INTERFACE_ID=r.ERC1155_INTERFACE_ID=r.ERC721_ENUMERABLE_INTERFACE_ID=r.ERC721_METADATA_INTERFACE_ID=r.ERC721_INTERFACE_ID=r.ERC20=r.ERC1155=r.ERC721=r.RINKEBY_CHAIN_ID=r.IPFS_DEFAULT_GATEWAY_URL=r.FALL_BACK_VS_CURRENCY=r.RPC=r.MAINNET=void 0,r.MAINNET="mainnet",r.RPC="rpc",r.FALL_BACK_VS_CURRENCY="ETH",r.IPFS_DEFAULT_GATEWAY_URL="https://cloudflare-ipfs.com/ipfs/",r.RINKEBY_CHAIN_ID="4",r.ERC721="ERC721",r.ERC1155="ERC1155",r.ERC20="ERC20",r.ERC721_INTERFACE_ID="0x80ac58cd",r.ERC721_METADATA_INTERFACE_ID="0x5b5e139f",r.ERC721_ENUMERABLE_INTERFACE_ID="0x780e9d63",r.ERC1155_INTERFACE_ID="0xd9b67a26",r.ERC1155_METADATA_URI_INTERFACE_ID="0x0e89341c",r.ERC1155_TOKEN_RECEIVER_INTERFACE_ID="0x4e2312e0",r.GWEI="gwei",r.ASSET_TYPES={NATIVE:"NATIVE",TOKEN:"TOKEN",COLLECTIBLE:"COLLECTIBLE",UNKNOWN:"UNKNOWN"},r.TESTNET_TICKER_SYMBOLS={RINKEBY:"RinkebyETH",GOERLI:"GoerliETH",ROPSTEN:"RopstenETH",KOVAN:"KovanETH"},r.OPENSEA_PROXY_URL="https://proxy.metaswap.codefi.network/opensea/v1/api/v1",r.OPENSEA_API_URL="https://api.opensea.io/api/v1",r.OPENSEA_TEST_API_URL="https://testnets-api.opensea.io/api/v1"}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1456,{"../BaseControllerV2":1434,"../util":1489,"./determineGasFeeCalculations":1457,"./fetchGasEstimatesViaEthFeeHistory":1459,"./gas-util":1463,"eth-query":2533,"ethereumjs-util":2612,uuid:6096},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.GasFeeController=r.GAS_ESTIMATE_TYPES=r.LEGACY_GAS_PRICES_API_URL=void 0;const s=i(e("eth-query")),o=e("uuid"),a=e("ethereumjs-util"),c=e("../BaseControllerV2"),u=e("../util"),l=e("./gas-util"),d=i(e("./determineGasFeeCalculations")),h=i(e("./fetchGasEstimatesViaEthFeeHistory"));r.LEGACY_GAS_PRICES_API_URL="https://api.metaswap.codefi.network/gasPrices",r.GAS_ESTIMATE_TYPES={FEE_MARKET:"fee-market",LEGACY:"legacy",ETH_GASPRICE:"eth_gasPrice",NONE:"none"};const f={gasFeeEstimates:{persist:!0,anonymous:!1},estimatedGasFeeTimeBounds:{persist:!0,anonymous:!1},gasEstimateType:{persist:!0,anonymous:!1}},p={gasFeeEstimates:{},estimatedGasFeeTimeBounds:{},gasEstimateType:r.GAS_ESTIMATE_TYPES.NONE};class m extends c.BaseController{constructor({interval:e=15e3,messenger:t,state:i,getCurrentNetworkEIP1559Compatibility:o,getCurrentAccountEIP1559Compatibility:a,getChainId:c,getCurrentNetworkLegacyGasAPICompatibility:u,getProvider:l,onNetworkStateChange:d,legacyAPIEndpoint:h=r.LEGACY_GAS_PRICES_API_URL,EIP1559APIEndpoint:m="https://mock-gas-server.herokuapp.com/",clientId:g}){super({name:"GasFeeController",metadata:f,messenger:t,state:Object.assign(Object.assign({},p),i)}),this.intervalDelay=e,this.pollTokens=new Set,this.getCurrentNetworkEIP1559Compatibility=o,this.getCurrentNetworkLegacyGasAPICompatibility=u,this.getCurrentAccountEIP1559Compatibility=a,this.EIP1559APIEndpoint=m,this.legacyAPIEndpoint=h,this.getChainId=c,this.currentChainId=this.getChainId();const v=l();this.ethQuery=new s.default(v),this.clientId=g,d((()=>n(this,void 0,void 0,(function*(){const e=l(),t=this.getChainId();this.ethQuery=new s.default(e),this.currentChainId!==t&&(this.currentChainId=t,yield this.resetPolling())}))))}resetPolling(){return n(this,void 0,void 0,(function*(){if(0!==this.pollTokens.size){const e=Array.from(this.pollTokens);this.stopPolling(),yield this.getGasFeeEstimatesAndStartPolling(e[0]),e.slice(1).forEach((e=>{this.pollTokens.add(e)}))}}))}fetchGasFeeEstimates(e){return n(this,void 0,void 0,(function*(){return yield this._fetchGasFeeEstimateData(e)}))}getGasFeeEstimatesAndStartPolling(e){return n(this,void 0,void 0,(function*(){const t=e||(0,o.v1)();return this.pollTokens.add(t),1===this.pollTokens.size&&(yield this._fetchGasFeeEstimateData(),this._poll()),t}))}_fetchGasFeeEstimateData(e={}){return n(this,void 0,void 0,(function*(){const{shouldUpdateState:t=!0}=e;let r;const n=this.getCurrentNetworkLegacyGasAPICompatibility();let i=this.getChainId();"string"==typeof i&&(0,a.isHexString)(i)&&(i=parseInt(i,16));try{r=yield this.getEIP1559Compatibility()}catch(e){console.error(e),r=!1}const s=yield(0,d.default)({isEIP1559Compatible:r,isLegacyGasAPICompatible:n,fetchGasEstimates:l.fetchGasEstimates,fetchGasEstimatesUrl:this.EIP1559APIEndpoint.replace("",`${i}`),fetchGasEstimatesViaEthFeeHistory:h.default,fetchLegacyGasPriceEstimates:l.fetchLegacyGasPriceEstimates,fetchLegacyGasPriceEstimatesUrl:this.legacyAPIEndpoint.replace("",`${i}`),fetchEthGasPriceEstimate:l.fetchEthGasPriceEstimate,calculateTimeEstimate:l.calculateTimeEstimate,clientId:this.clientId,ethQuery:this.ethQuery});return t&&this.update((e=>{e.gasFeeEstimates=s.gasFeeEstimates,e.estimatedGasFeeTimeBounds=s.estimatedGasFeeTimeBounds,e.gasEstimateType=s.gasEstimateType})),s}))}disconnectPoller(e){this.pollTokens.delete(e),0===this.pollTokens.size&&this.stopPolling()}stopPolling(){this.intervalId&&clearInterval(this.intervalId),this.pollTokens.clear(),this.resetState()}destroy(){super.destroy(),this.stopPolling()}_poll(){this.intervalId&&clearInterval(this.intervalId),this.intervalId=setInterval((()=>n(this,void 0,void 0,(function*(){yield(0,u.safelyExecute)((()=>this._fetchGasFeeEstimateData()))}))),this.intervalDelay)}resetState(){this.update((()=>p))}getEIP1559Compatibility(){var e,t;return n(this,void 0,void 0,(function*(){const r=yield this.getCurrentNetworkEIP1559Compatibility(),n=null===(t=null===(e=this.getCurrentAccountEIP1559Compatibility)||void 0===e?void 0:e.call(this))||void 0===t||t;return r&&n}))}getTimeEstimate(e,t){return this.state.gasFeeEstimates&&this.state.gasEstimateType===r.GAS_ESTIMATE_TYPES.FEE_MARKET?(0,l.calculateTimeEstimate)(e,t,this.state.gasFeeEstimates):{}}}r.GasFeeController=m,r.default=m}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1457,{"./GasFeeController":1456},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0});const i=e("./GasFeeController");r.default=function({isEIP1559Compatible:e,isLegacyGasAPICompatible:t,fetchGasEstimates:r,fetchGasEstimatesUrl:s,fetchGasEstimatesViaEthFeeHistory:o,fetchLegacyGasPriceEstimates:a,fetchLegacyGasPriceEstimatesUrl:c,fetchEthGasPriceEstimate:u,calculateTimeEstimate:l,clientId:d,ethQuery:h}){return n(this,void 0,void 0,(function*(){try{if(e){let e;try{e=yield r(s,d)}catch(t){e=yield o(h)}const{suggestedMaxPriorityFeePerGas:t,suggestedMaxFeePerGas:n}=e.medium;return{gasFeeEstimates:e,estimatedGasFeeTimeBounds:l(t,n,e),gasEstimateType:i.GAS_ESTIMATE_TYPES.FEE_MARKET}}if(t){return{gasFeeEstimates:yield a(c,d),estimatedGasFeeTimeBounds:{},gasEstimateType:i.GAS_ESTIMATE_TYPES.LEGACY}}throw new Error("Main gas fee/price estimation failed. Use fallback")}catch(e){try{return{gasFeeEstimates:yield u(h),estimatedGasFeeTimeBounds:{},gasEstimateType:i.GAS_ESTIMATE_TYPES.ETH_GASPRICE}}catch(e){if(e instanceof Error)throw new Error(`Gas fee/price estimation failed. Message: ${e.message}`);throw e}}}))}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1458,{"../util":1489,"ethereumjs-util":2612},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0});const i=e("ethereumjs-util"),s=e("../util"),o=1024;function a({ethQuery:e,numberOfBlocks:t,endBlockNumber:r,percentiles:i,includeNextBlock:o}){var a;return n(this,void 0,void 0,(function*(){const n=yield(0,s.query)(e,"eth_feeHistory",[(0,s.toHex)(t),(0,s.toHex)(r),i]),c=(0,s.fromHex)(n.oldestBlock);if(n.baseFeePerGas!==undefined&&n.baseFeePerGas.length>0&&n.gasUsedRatio.length>0&&(n.reward===undefined||n.reward.length>0)){const e=o?n.baseFeePerGas:n.baseFeePerGas.slice(0,t),r=n.gasUsedRatio,u=null!==(a=n.reward)&&void 0!==a?a:[],l=r.length;return e.map(((e,t)=>{const n=(0,s.fromHex)(e),o=c.addn(t);return t>=l?function({baseFeePerGas:e,number:t}){return{number:t,baseFeePerGas:e,gasUsedRatio:null,priorityFeesByPercentile:null}}({baseFeePerGas:n,number:o}):function({baseFeePerGas:e,number:t,blockIndex:r,gasUsedRatios:n,priorityFeePercentileGroups:i,percentiles:o}){const a=n[r],c=i[r];return{number:t,baseFeePerGas:e,gasUsedRatio:a,priorityFeesByPercentile:o.reduce(((e,t,r)=>{const n=c[r];return Object.assign(Object.assign({},e),{[t]:(0,s.fromHex)(n)})}),{})}}({baseFeePerGas:n,number:o,blockIndex:t,gasUsedRatios:r,priorityFeePercentileGroups:u,percentiles:i})}))}return[]}))}r.default=function({ethQuery:e,numberOfBlocks:t,endBlock:r="latest",percentiles:c=[],includeNextBlock:u=!1}){return n(this,void 0,void 0,(function*(){const n=c.length>0?Array.from(new Set(c)).sort(((e,t)=>e-t)):[],l=function(e,t){e.lt(new i.BN(t))&&(t=e.toNumber());const r=[];for(let n=e.subn(t);n.lt(e);n=n.addn(o)){const t=e.sub(n).toNumber(),i=ti===l.length-1?a({ethQuery:e,numberOfBlocks:t,endBlockNumber:r,percentiles:n,includeNextBlock:u}):a({ethQuery:e,numberOfBlocks:t,endBlockNumber:r,percentiles:n,includeNextBlock:!1}))))).reduce(((e,t)=>[...e,...t]),[])}))}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1459,{"../constants":1455,"./fetchBlockFeeHistory":1458,"./fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels":1460,"./fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock":1461,"ethjs-unit":2664},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});const s=e("ethjs-unit"),o=e("../constants"),a=i(e("./fetchBlockFeeHistory")),c=i(e("./fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock")),u=i(e("./fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels"));r.default=function(e){return n(this,void 0,void 0,(function*(){const t=yield(0,c.default)(e),r=yield(0,a.default)({ethQuery:e,endBlock:t.number,numberOfBlocks:5,percentiles:[10,20,30]}),n=(0,s.fromWei)(t.baseFeePerGas,o.GWEI),i=(0,u.default)(r);return Object.assign(Object.assign({},i),{estimatedBaseFee:n,historicalBaseFeeRange:null,baseFeeTrend:null,latestPriorityFeeRange:null,historicalPriorityFeeRange:null,priorityFeeTrend:null,networkCongestion:null})}))}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[146,{"@babel/runtime/helpers/defineProperty":194,"@babel/runtime/helpers/interopRequireDefault":200,lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var i=n(e("@babel/runtime/helpers/defineProperty")),s=e("lodash");function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function a(e){for(var t=1;t{Object.keys(l[e]).forEach((t=>{const r=l[e][t];h[t]===undefined?h[t]={[e]:r}:h[t]=a(a({},h[t]),{},{[e]:r})}))}));const f={};d&&Object.keys(d).forEach((e=>{Object.keys(d[e]).forEach((t=>{const r=d[e][t];f[t]===undefined?f[t]={[e]:r}:f[t]=a(a({},f[t]),{},{[e]:r})}))}));e.TokensController?(e.TokensController.allTokens=h,e.TokensController.allIgnoredTokens=f):e.TokensController={allTokens:h,allIgnoredTokens:f};return null==e||(null===(n=e.PreferencesController)||void 0===n||delete n.accountHiddenTokens),null==e||null===(i=e.PreferencesController)||void 0===i||delete i.accountTokens,null==e||null===(s=e.PreferencesController)||void 0===s||delete s.assetImages,null==e||null===(o=e.PreferencesController)||void 0===o||delete o.hiddenTokens,null==e||null===(c=e.PreferencesController)||void 0===c||delete c.tokens,null==e||null===(u=e.PreferencesController)||void 0===u||delete u.suggestedTokens,e}(t.data);return t.data=r,t}};r.default=c}}},{package:"$root$"}],[1460,{"../../constants":1455,"./medianOf":1462,"ethereumjs-util":2612,"ethjs-unit":2664},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});const i=e("ethereumjs-util"),s=e("ethjs-unit"),o=e("../../constants"),a=n(e("./medianOf")),c=["low","medium","high"],u={low:{percentile:10,baseFeePercentageMultiplier:new i.BN(110),priorityFeePercentageMultiplier:new i.BN(94),minSuggestedMaxPriorityFeePerGas:new i.BN(1e9),estimatedWaitTimes:{minWaitTimeEstimate:15e3,maxWaitTimeEstimate:3e4}},medium:{percentile:20,baseFeePercentageMultiplier:new i.BN(120),priorityFeePercentageMultiplier:new i.BN(97),minSuggestedMaxPriorityFeePerGas:new i.BN(15e8),estimatedWaitTimes:{minWaitTimeEstimate:15e3,maxWaitTimeEstimate:45e3}},high:{percentile:30,baseFeePercentageMultiplier:new i.BN(125),priorityFeePercentageMultiplier:new i.BN(98),minSuggestedMaxPriorityFeePerGas:new i.BN(2e9),estimatedWaitTimes:{minWaitTimeEstimate:15e3,maxWaitTimeEstimate:6e4}}};r.default=function(e){return c.reduce(((t,r)=>{const n=function(e,t){const r=u[e],n=t[t.length-1].baseFeePerGas.mul(r.baseFeePercentageMultiplier).divn(100),c=t.map((e=>"priorityFeesByPercentile"in e?e.priorityFeesByPercentile[r.percentile]:null)).filter(i.BN.isBN),l=(0,a.default)(c).mul(r.priorityFeePercentageMultiplier).divn(100),d=i.BN.max(l,r.minSuggestedMaxPriorityFeePerGas),h=n.add(d);return Object.assign(Object.assign({},r.estimatedWaitTimes),{suggestedMaxPriorityFeePerGas:(0,s.fromWei)(d,o.GWEI),suggestedMaxFeePerGas:(0,s.fromWei)(h,o.GWEI)})}(r,e);return Object.assign(Object.assign({},t),{[r]:n})}),{})}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1461,{"../../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0});const i=e("../../util");r.default=function(e,t=!1){return n(this,void 0,void 0,(function*(){const r=yield(0,i.query)(e,"blockNumber"),n=yield(0,i.query)(e,"getBlockByNumber",[r,t]);return Object.assign(Object.assign({},n),{number:(0,i.fromHex)(n.number),baseFeePerGas:(0,i.fromHex)(n.baseFeePerGas)})}))}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1462,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){const t=e.slice().sort(((e,t)=>e.cmp(t))),r=t.length;return t[Math.floor((r-1)/2)]}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1463,{"../util":1489,"ethereumjs-util":2612},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.calculateTimeEstimate=r.fetchEthGasPriceEstimate=r.fetchLegacyGasPriceEstimates=r.fetchGasEstimates=r.normalizeGWEIDecimalNumbers=void 0;const i=e("ethereumjs-util"),s=e("../util"),o=e=>({"X-Client-Id":e});function a(e){const t=(0,s.gweiDecToWEIBN)(e).toString(16);return(0,s.weiHexToGweiDec)(t).toString(10)}r.normalizeGWEIDecimalNumbers=a,r.fetchGasEstimates=function(e,t){return n(this,void 0,void 0,(function*(){const r=yield(0,s.handleFetch)(e,t?{headers:o(t)}:undefined);return{low:Object.assign(Object.assign({},r.low),{suggestedMaxPriorityFeePerGas:a(r.low.suggestedMaxPriorityFeePerGas),suggestedMaxFeePerGas:a(r.low.suggestedMaxFeePerGas)}),medium:Object.assign(Object.assign({},r.medium),{suggestedMaxPriorityFeePerGas:a(r.medium.suggestedMaxPriorityFeePerGas),suggestedMaxFeePerGas:a(r.medium.suggestedMaxFeePerGas)}),high:Object.assign(Object.assign({},r.high),{suggestedMaxPriorityFeePerGas:a(r.high.suggestedMaxPriorityFeePerGas),suggestedMaxFeePerGas:a(r.high.suggestedMaxFeePerGas)}),estimatedBaseFee:a(r.estimatedBaseFee),historicalBaseFeeRange:r.historicalBaseFeeRange,baseFeeTrend:r.baseFeeTrend,latestPriorityFeeRange:r.latestPriorityFeeRange,historicalPriorityFeeRange:r.historicalPriorityFeeRange,priorityFeeTrend:r.priorityFeeTrend,networkCongestion:r.networkCongestion}}))},r.fetchLegacyGasPriceEstimates=function(e,t){return n(this,void 0,void 0,(function*(){const r=yield(0,s.handleFetch)(e,{referrer:e,referrerPolicy:"no-referrer-when-downgrade",method:"GET",mode:"cors",headers:Object.assign({"Content-Type":"application/json"},t&&o(t))});return{low:r.SafeGasPrice,medium:r.ProposeGasPrice,high:r.FastGasPrice}}))},r.fetchEthGasPriceEstimate=function(e){return n(this,void 0,void 0,(function*(){const t=yield(0,s.query)(e,"gasPrice");return{gasPrice:(0,s.weiHexToGweiDec)(t).toString()}}))},r.calculateTimeEstimate=function(e,t,r){const{low:n,medium:o,high:a,estimatedBaseFee:c}=r,u=(0,s.gweiDecToWEIBN)(e),l=(0,s.gweiDecToWEIBN)(t),d=(0,s.gweiDecToWEIBN)(c),h=i.BN.min(u,l.sub(d)),f=(0,s.gweiDecToWEIBN)(n.suggestedMaxPriorityFeePerGas),p=(0,s.gweiDecToWEIBN)(o.suggestedMaxPriorityFeePerGas),m=(0,s.gweiDecToWEIBN)(a.suggestedMaxPriorityFeePerGas);let g,v;return h.lt(f)?(g=null,v="unknown"):h.gte(f)&&h.lt(p)?(g=n.minWaitTimeEstimate,v=n.maxWaitTimeEstimate):h.gte(p)&&h.lt(m)?(g=o.minWaitTimeEstimate,v=o.maxWaitTimeEstimate):h.eq(m)?(g=a.minWaitTimeEstimate,v=a.maxWaitTimeEstimate):(g=0,v=a.maxWaitTimeEstimate),{lowerTimeBound:g,upperTimeBound:v}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1464,{"./BaseController":1433,"./BaseControllerV2":1434,"./ComposableController":1435,"./ControllerMessenger":1436,"./announcement/AnnouncementController":1437,"./approval/ApprovalController":1440,"./assets/AccountTrackerController":1441,"./assets/AssetsContractController":1442,"./assets/CollectibleDetectionController":1443,"./assets/CollectiblesController":1444,"./assets/CurrencyRateController":1445,"./assets/TokenBalancesController":1449,"./assets/TokenDetectionController":1450,"./assets/TokenListController":1451,"./assets/TokenRatesController":1452,"./assets/TokensController":1453,"./gas/GasFeeController":1456,"./keyring/KeyringController":1465,"./message-manager/MessageManager":1467,"./message-manager/PersonalMessageManager":1468,"./message-manager/TypedMessageManager":1469,"./network/NetworkController":1470,"./notification/NotificationController":1471,"./permissions":1476,"./ratelimit/RateLimitController":1482,"./subject-metadata":1484,"./third-party/PhishingController":1485,"./transaction/TransactionController":1486,"./user/AddressBookController":1487,"./user/PreferencesController":1488,"./util":1489,"isomorphic-fetch":4825},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t},o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.util=r.getAnonymizedState=r.getPersistentState=r.BaseControllerV2=void 0,e("isomorphic-fetch");const a=s(e("./util"));r.util=a,o(e("./assets/AccountTrackerController"),r),o(e("./user/AddressBookController"),r),o(e("./approval/ApprovalController"),r),o(e("./assets/AssetsContractController"),r),o(e("./BaseController"),r);var c=e("./BaseControllerV2");Object.defineProperty(r,"BaseControllerV2",{enumerable:!0,get:function(){return c.BaseController}}),Object.defineProperty(r,"getPersistentState",{enumerable:!0,get:function(){return c.getPersistentState}}),Object.defineProperty(r,"getAnonymizedState",{enumerable:!0,get:function(){return c.getAnonymizedState}}),o(e("./ComposableController"),r),o(e("./ControllerMessenger"),r),o(e("./assets/CurrencyRateController"),r),o(e("./keyring/KeyringController"),r),o(e("./message-manager/MessageManager"),r),o(e("./network/NetworkController"),r),o(e("./third-party/PhishingController"),r),o(e("./user/PreferencesController"),r),o(e("./assets/TokenBalancesController"),r),o(e("./assets/TokenRatesController"),r),o(e("./transaction/TransactionController"),r),o(e("./message-manager/PersonalMessageManager"),r),o(e("./message-manager/TypedMessageManager"),r),o(e("./announcement/AnnouncementController"),r),o(e("./assets/TokenListController"),r),o(e("./gas/GasFeeController"),r),o(e("./assets/TokensController"),r),o(e("./assets/CollectiblesController"),r),o(e("./assets/TokenDetectionController"),r),o(e("./assets/CollectibleDetectionController"),r),o(e("./permissions"),r),o(e("./subject-metadata"),r),o(e("./ratelimit/RateLimitController"),r),o(e("./notification/NotificationController"),r)}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1465,{"../BaseController":1433,"../util":1489,"async-mutex":1830,"eth-keyring-controller":2520,"eth-sig-util":2539,"ethereumjs-util":2612,"ethereumjs-wallet":1519},function(){with(this)return function(){"use strict";return function(e,t,r){var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return s(t,e),t},a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},c=this&&this.__classPrivateFieldSet||function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.KeyringController=r.SignTypedDataVersion=r.AccountImportStrategy=r.KeyringTypes=void 0;const d=e("ethereumjs-util"),h=e("eth-sig-util"),f=o(e("ethereumjs-wallet")),p=l(e("eth-keyring-controller")),m=e("async-mutex"),g=e("../BaseController"),v=e("../util");var y,w;!function(e){e.simple="Simple Key Pair",e.hd="HD Key Tree",e.qr="QR Hardware Wallet Device"}(y=r.KeyringTypes||(r.KeyringTypes={})),function(e){e.privateKey="privateKey",e.json="json"}(r.AccountImportStrategy||(r.AccountImportStrategy={})),function(e){e.V1="V1",e.V3="V3",e.V4="V4"}(w=r.SignTypedDataVersion||(r.SignTypedDataVersion={}));class b extends g.BaseController{constructor({removeIdentity:e,syncIdentities:t,updateIdentities:r,setSelectedAddress:i,setAccountLabel:s},o,a){super(o,a),this.mutex=new m.Mutex,this.name="KeyringController",n.set(this,void 0),c(this,n,new p.default(Object.assign({initState:a},o)),"f"),this.defaultState=Object.assign(Object.assign({},u(this,n,"f").store.getState()),{keyrings:[]}),this.removeIdentity=e,this.syncIdentities=t,this.updateIdentities=r,this.setSelectedAddress=i,this.setAccountLabel=s,this.initialize(),this.fullUpdate()}addNewAccount(){return a(this,void 0,void 0,(function*(){const e=u(this,n,"f").getKeyringsByType("HD Key Tree")[0];if(!e)throw new Error("No HD keyring found");const t=yield u(this,n,"f").getAccounts();yield u(this,n,"f").addNewAccount(e);const r=yield u(this,n,"f").getAccounts();return yield this.verifySeedPhrase(),this.updateIdentities(r),r.forEach((e=>{t.includes(e)||this.setSelectedAddress(e)})),this.fullUpdate()}))}addNewAccountWithoutUpdate(){return a(this,void 0,void 0,(function*(){const e=u(this,n,"f").getKeyringsByType("HD Key Tree")[0];if(!e)throw new Error("No HD keyring found");return yield u(this,n,"f").addNewAccount(e),yield this.verifySeedPhrase(),this.fullUpdate()}))}createNewVaultAndRestore(e,t){return a(this,void 0,void 0,(function*(){const r=yield this.mutex.acquire();if(!e||!e.length)throw new Error("Invalid password");try{this.updateIdentities([]);const i=yield u(this,n,"f").createNewVaultAndRestore(e,t);return this.updateIdentities(yield u(this,n,"f").getAccounts()),this.fullUpdate(),i}finally{r()}}))}createNewVaultAndKeychain(e){return a(this,void 0,void 0,(function*(){const t=yield this.mutex.acquire();try{const r=yield u(this,n,"f").createNewVaultAndKeychain(e);return this.updateIdentities(yield u(this,n,"f").getAccounts()),this.fullUpdate(),r}finally{t()}}))}isUnlocked(){return u(this,n,"f").memStore.getState().isUnlocked}exportSeedPhrase(e){if(u(this,n,"f").password===e)return u(this,n,"f").keyrings[0].mnemonic;throw new Error("Invalid password")}exportAccount(e,t){if(u(this,n,"f").password===e)return u(this,n,"f").exportAccount(t);throw new Error("Invalid password")}getAccounts(){return u(this,n,"f").getAccounts()}importAccountWithStrategy(e,t){return a(this,void 0,void 0,(function*(){let r;switch(e){case"privateKey":const[n]=t;if(!n)throw new Error("Cannot import an empty key.");const i=(0,d.addHexPrefix)(n);let s;try{s=(0,d.toBuffer)(i)}catch(e){throw new Error("Cannot import invalid private key.")}if(!(0,d.isValidPrivate)(s))throw new Error("Cannot import invalid private key.");r=(0,d.stripHexPrefix)(i);break;case"json":let o;const[a,c]=t;try{o=f.thirdparty.fromEtherWallet(a,c)}catch(e){o=o||(yield f.default.fromV3(a,c,!0))}r=(0,d.bufferToHex)(o.getPrivateKey());break;default:throw new Error(`Unexpected import strategy: '${e}'`)}const i=yield u(this,n,"f").addNewKeyring(y.simple,[r]),s=yield i.getAccounts(),o=yield u(this,n,"f").getAccounts();return this.updateIdentities(o),this.setSelectedAddress(s[0]),this.fullUpdate()}))}removeAccount(e){return a(this,void 0,void 0,(function*(){return this.removeIdentity(e),yield u(this,n,"f").removeAccount(e),this.fullUpdate()}))}setLocked(){return u(this,n,"f").setLocked()}signMessage(e){return u(this,n,"f").signMessage(e)}signPersonalMessage(e){return u(this,n,"f").signPersonalMessage(e)}signTypedMessage(e,t){return a(this,void 0,void 0,(function*(){try{const r=(0,h.normalize)(e.from),i=yield this.getOrAddQRKeyring();if(-1!==(yield i.getAccounts()).findIndex((e=>e.toLowerCase()===r.toLowerCase()))){const r=Object.assign({},e);return t!==w.V1&&"string"==typeof r.data&&(r.data=JSON.parse(r.data)),u(this,n,"f").signTypedMessage(r,{version:t})}const{password:s}=u(this,n,"f"),o=yield this.exportAccount(s,r),a=(0,d.toBuffer)((0,d.addHexPrefix)(o));switch(t){case w.V1:return(0,h.signTypedDataLegacy)(a,{data:e.data});case w.V3:return(0,h.signTypedData)(a,{data:JSON.parse(e.data)});case w.V4:return(0,h.signTypedData_v4)(a,{data:JSON.parse(e.data)});default:throw new Error(`Unexpected signTypedMessage version: '${t}'`)}}catch(e){throw new Error(`Keyring Controller signTypedMessage: ${e}`)}}))}signTransaction(e,t){return u(this,n,"f").signTransaction(e,t)}submitPassword(e){return a(this,void 0,void 0,(function*(){yield u(this,n,"f").submitPassword(e);const t=yield u(this,n,"f").getAccounts();return yield this.syncIdentities(t),this.fullUpdate()}))}subscribe(e){u(this,n,"f").store.subscribe(e)}unsubscribe(e){return u(this,n,"f").store.unsubscribe(e)}onLock(e){return u(this,n,"f").on("lock",e)}onUnlock(e){return u(this,n,"f").on("unlock",e)}verifySeedPhrase(){return a(this,void 0,void 0,(function*(){const e=u(this,n,"f").getKeyringsByType(y.hd)[0];if(!e)throw new Error("No HD keyring found.");const t=(yield e.serialize()).mnemonic,r=yield e.getAccounts();if(0===r.length)throw new Error("Cannot verify an empty keyring.");const i=new(u(this,n,"f").getKeyringClassForType(y.hd))({mnemonic:t,numberOfAccounts:r.length}),s=yield i.getAccounts();if(s.length!==r.length)throw new Error("Seed phrase imported incorrect number of accounts.");return s.forEach(((e,t)=>{if(e.toLowerCase()!==r[t].toLowerCase())throw new Error("Seed phrase imported different accounts.")})),t}))}fullUpdate(){return a(this,void 0,void 0,(function*(){const e=yield Promise.all(u(this,n,"f").keyrings.map(((e,t)=>a(this,void 0,void 0,(function*(){const r=yield e.getAccounts();return{accounts:Array.isArray(r)?r.map((e=>(0,v.toChecksumHexAddress)(e))):[],index:t,type:e.type}})))));return this.update({keyrings:[...e]}),u(this,n,"f").fullUpdate()}))}addQRKeyring(){return a(this,void 0,void 0,(function*(){const e=yield u(this,n,"f").addNewKeyring(y.qr);return yield this.fullUpdate(),e}))}getOrAddQRKeyring(){return a(this,void 0,void 0,(function*(){return u(this,n,"f").getKeyringsByType(y.qr)[0]||(yield this.addQRKeyring())}))}restoreQRKeyring(e){return a(this,void 0,void 0,(function*(){(yield this.getOrAddQRKeyring()).deserialize(e),this.updateIdentities(yield u(this,n,"f").getAccounts()),yield this.fullUpdate()}))}resetQRKeyringState(){return a(this,void 0,void 0,(function*(){(yield this.getOrAddQRKeyring()).resetStore()}))}getQRKeyringState(){return a(this,void 0,void 0,(function*(){return(yield this.getOrAddQRKeyring()).getMemStore()}))}submitQRCryptoHDKey(e){return a(this,void 0,void 0,(function*(){(yield this.getOrAddQRKeyring()).submitCryptoHDKey(e)}))}submitQRCryptoAccount(e){return a(this,void 0,void 0,(function*(){(yield this.getOrAddQRKeyring()).submitCryptoAccount(e)}))}submitQRSignature(e,t){return a(this,void 0,void 0,(function*(){(yield this.getOrAddQRKeyring()).submitSignature(e,t)}))}cancelQRSignRequest(){return a(this,void 0,void 0,(function*(){(yield this.getOrAddQRKeyring()).cancelSignRequest()}))}connectQRHardware(e){return a(this,void 0,void 0,(function*(){try{const t=yield this.getOrAddQRKeyring();let r;switch(e){case-1:r=yield t.getPreviousPage();break;case 1:r=yield t.getNextPage();break;default:r=yield t.getFirstPage()}return r.map((e=>Object.assign(Object.assign({},e),{balance:"0x0"})))}catch(e){throw new Error(`Unspecified error when connect QR Hardware, ${e}`)}}))}unlockQRHardwareWalletAccount(e){return a(this,void 0,void 0,(function*(){const t=yield this.getOrAddQRKeyring();t.setAccountToUnlock(e);const r=yield u(this,n,"f").getAccounts();yield u(this,n,"f").addNewAccount(t);const i=yield u(this,n,"f").getAccounts();this.updateIdentities(i),i.forEach((n=>{r.includes(n)||(this.setAccountLabel&&this.setAccountLabel(n,`${t.getName()} ${e}`),this.setSelectedAddress(n))})),yield u(this,n,"f").persistAllKeyrings(),yield this.fullUpdate()}))}getAccountKeyringType(e){return a(this,void 0,void 0,(function*(){return(yield u(this,n,"f").getKeyringForAccount(e)).type}))}forgetQRDevice(){return a(this,void 0,void 0,(function*(){(yield this.getOrAddQRKeyring()).forgetDevice();(yield u(this,n,"f").getAccounts()).forEach((e=>{this.setSelectedAddress(e)})),yield u(this,n,"f").persistAllKeyrings(),yield this.fullUpdate()}))}}r.KeyringController=b,n=new WeakMap,r.default=b}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1466,{"../BaseController":1433,events:2176},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.AbstractMessageManager=void 0;const n=e("events"),i=e("../BaseController");class s extends i.BaseController{constructor(e,t){super(e,t),this.hub=new n.EventEmitter,this.name="AbstractMessageManager",this.defaultState={unapprovedMessages:{},unapprovedMessagesCount:0},this.messages=[],this.initialize()}saveMessageList(){const e=this.getUnapprovedMessages(),t=this.getUnapprovedMessagesCount();this.update({unapprovedMessages:e,unapprovedMessagesCount:t}),this.hub.emit("updateBadge")}setMessageStatus(e,t){const r=this.getMessage(e);if(!r)throw new Error(`${this.name}: Message not found for id: ${e}.`);r.status=t,this.updateMessage(r),this.hub.emit(`${e}:${t}`,r),"rejected"!==t&&"signed"!==t&&"errored"!==t||this.hub.emit(`${e}:finished`,r)}updateMessage(e){const t=this.messages.findIndex((t=>e.id===t.id));-1!==t&&(this.messages[t]=e),this.saveMessageList()}getUnapprovedMessagesCount(){return Object.keys(this.getUnapprovedMessages()).length}getUnapprovedMessages(){return this.messages.filter((e=>"unapproved"===e.status)).reduce(((e,t)=>(e[t.id]=t,e)),{})}addMessage(e){this.messages.push(e),this.saveMessageList()}getMessage(e){return this.messages.find((t=>t.id===e))}approveMessage(e){return this.setMessageStatusApproved(e.metamaskId),this.prepMessageForSigning(e)}setMessageStatusApproved(e){this.setMessageStatus(e,"approved")}setMessageStatusSigned(e,t){const r=this.getMessage(e);r&&(r.rawSig=t,this.updateMessage(r),this.setMessageStatus(e,"signed"))}rejectMessage(e){this.setMessageStatus(e,"rejected")}}r.AbstractMessageManager=s,r.default=s}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1467,{"../util":1489,"./AbstractMessageManager":1466,uuid:6096},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.MessageManager=void 0;const n=e("uuid"),i=e("../util"),s=e("./AbstractMessageManager");class o extends s.AbstractMessageManager{constructor(){super(...arguments),this.name="MessageManager"}addUnapprovedMessageAsync(e,t){return new Promise(((r,n)=>{(0,i.validateSignMessageData)(e);const s=this.addUnapprovedMessage(e,t);this.hub.once(`${s}:finished`,(t=>{switch(t.status){case"signed":return r(t.rawSig);case"rejected":return n(new Error("MetaMask Message Signature: User denied message signature."));default:return n(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(e)}`))}}))}))}addUnapprovedMessage(e,t){t&&(e.origin=t.origin),e.data=(0,i.normalizeMessageData)(e.data);const r=(0,n.v1)(),s={id:r,messageParams:e,status:"unapproved",time:Date.now(),type:"eth_sign"};return this.addMessage(s),this.hub.emit("unapprovedMessage",Object.assign(Object.assign({},e),{metamaskId:r})),r}prepMessageForSigning(e){return delete e.metamaskId,Promise.resolve(e)}}r.MessageManager=o,r.default=o}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1468,{"../util":1489,"./AbstractMessageManager":1466,uuid:6096},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.PersonalMessageManager=void 0;const n=e("uuid"),i=e("../util"),s=e("./AbstractMessageManager");class o extends s.AbstractMessageManager{constructor(){super(...arguments),this.name="PersonalMessageManager"}addUnapprovedMessageAsync(e,t){return new Promise(((r,n)=>{(0,i.validateSignMessageData)(e);const s=this.addUnapprovedMessage(e,t);this.hub.once(`${s}:finished`,(t=>{switch(t.status){case"signed":return r(t.rawSig);case"rejected":return n(new Error("MetaMask Personal Message Signature: User denied message signature."));default:return n(new Error(`MetaMask Personal Message Signature: Unknown problem: ${JSON.stringify(e)}`))}}))}))}addUnapprovedMessage(e,t){t&&(e.origin=t.origin),e.data=(0,i.normalizeMessageData)(e.data);const r=(0,n.v1)(),s={id:r,messageParams:e,status:"unapproved",time:Date.now(),type:"personal_sign"};return this.addMessage(s),this.hub.emit("unapprovedMessage",Object.assign(Object.assign({},e),{metamaskId:r})),r}prepMessageForSigning(e){return delete e.metamaskId,Promise.resolve(e)}}r.PersonalMessageManager=o,r.default=o}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1469,{"../util":1489,"./AbstractMessageManager":1466,uuid:6096},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.TypedMessageManager=void 0;const n=e("uuid"),i=e("../util"),s=e("./AbstractMessageManager");class o extends s.AbstractMessageManager{constructor(){super(...arguments),this.name="TypedMessageManager"}addUnapprovedMessageAsync(e,t,r){return new Promise(((n,s)=>{"V1"===t&&(0,i.validateTypedSignMessageDataV1)(e),"V3"===t&&(0,i.validateTypedSignMessageDataV3)(e);const o=this.addUnapprovedMessage(e,t,r);this.hub.once(`${o}:finished`,(t=>{switch(t.status){case"signed":return n(t.rawSig);case"rejected":return s(new Error("MetaMask Typed Message Signature: User denied message signature."));case"errored":return s(new Error(`MetaMask Typed Message Signature: ${t.error}`));default:return s(new Error(`MetaMask Typed Message Signature: Unknown problem: ${JSON.stringify(e)}`))}}))}))}addUnapprovedMessage(e,t,r){const i=(0,n.v1)(),s=Object.assign(Object.assign({},e),{metamaskId:i,version:t});r&&(e.origin=r.origin);const o={id:i,messageParams:e,status:"unapproved",time:Date.now(),type:"eth_signTypedData"};return this.addMessage(o),this.hub.emit("unapprovedMessage",s),i}setMessageStatusErrored(e,t){const r=this.getMessage(e);r&&(r.error=t,this.updateMessage(r),this.setMessageStatus(e,"errored"))}prepMessageForSigning(e){return delete e.metamaskId,delete e.version,Promise.resolve(e)}}r.TypedMessageManager=o,r.default=o}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[147,{"../../../shared/constants/transaction":6272,lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash"),i=e("../../../shared/constants/transaction");const s="sentEther";var o={version:64,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=64;const r=function(e){var t;const r=null==e||null===(t=e.TransactionController)||void 0===t?void 0:t.transactions;if((0,n.isPlainObject)(r))for(const e of Object.values(r))e.type===s&&(e.type=i.TRANSACTION_TYPES.SIMPLE_SEND),e.history&&e.history.map((e=>(e.type&&e.type===s&&(e.type=i.TRANSACTION_TYPES.SIMPLE_SEND),e)));return e}(t.data);return t.data=r,t}};r.default=o}}},{package:"$root$"}],[1470,{"../BaseController":1433,"../constants":1455,"async-mutex":1830,"eth-json-rpc-infura/src/createProvider":2486,"eth-query":2533,"web3-provider-engine/subproviders/provider":6167,"web3-provider-engine/zero":6177},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__rest||function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i{null==e||e.stop()}),500)}verifyNetwork(){"loading"===this.state.network&&this.lookupNetwork()}set providerConfig(e){this.internalProviderConfig=e;const{type:t,rpcTarget:r,chainId:n,ticker:i,nickname:s}=this.state.provider;this.initializeProvider(t,r,n,i,s),this.registerProvider(),this.lookupNetwork()}get providerConfig(){throw new Error("Property only used for setting")}lookupNetwork(){return n(this,void 0,void 0,(function*(){if(!this.ethQuery||!this.ethQuery.sendAsync)return;const e=yield this.mutex.acquire();this.ethQuery.sendAsync({method:"net_version"},((t,r)=>{this.update({network:t?"loading":r}),e()}))}))}setProviderType(e){const t=this.state.provider,{rpcTarget:r,chainId:n,nickname:s}=t,o=i(t,["rpcTarget","chainId","nickname"]);this.update({provider:Object.assign(Object.assign({},o),{type:e,ticker:"ETH",chainId:f[e]})}),this.refreshNetwork()}setRpcTarget(e,t,r,n){this.update({provider:Object.assign(Object.assign({},this.state.provider),{type:h.RPC,ticker:r,rpcTarget:e,chainId:t,nickname:n})}),this.refreshNetwork()}getEIP1559Compatibility(){var e;const{properties:t={}}=this.state;return t.isEIP1559Compatible||"function"!=typeof(null===(e=this.ethQuery)||void 0===e?void 0:e.sendAsync)?Promise.resolve(!0):new Promise(((e,r)=>{this.ethQuery.sendAsync({method:"eth_getBlockByNumber",params:["latest",!1]},((n,i)=>{if(n)r(n);else{const r=void 0!==i.baseFeePerGas;t.isEIP1559Compatible!==r&&this.update({properties:{isEIP1559Compatible:r}}),e(r)}}))}))}}r.NetworkController=p,r.default=p}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1471,{"../BaseControllerV2":1434,"../util":1489,nanoid:1538},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.NotificationController=void 0;const n=e("nanoid"),i=e("../util"),s=e("../BaseControllerV2"),o="NotificationController",a={notifications:{persist:!0,anonymous:!1}},c={notifications:{}};class u extends s.BaseController{constructor({messenger:e,state:t}){super({name:o,metadata:a,messenger:e,state:Object.assign(Object.assign({},c),t)}),this.messagingSystem.registerActionHandler(`${o}:show`,((e,t)=>this.show(e,t))),this.messagingSystem.registerActionHandler(`${o}:dismiss`,(e=>this.dismiss(e))),this.messagingSystem.registerActionHandler(`${o}:markRead`,(e=>this.markRead(e)))}show(e,t){const r=(0,n.nanoid)(),i={id:r,origin:e,createdDate:Date.now(),readDate:null,message:t};this.update((e=>{e.notifications[r]=i}))}dismiss(e){this.update((t=>{for(const r of e)(0,i.hasProperty)(t.notifications,r)&&delete t.notifications[r]}))}markRead(e){this.update((t=>{for(const r of e)(0,i.hasProperty)(t.notifications,r)&&(t.notifications[r].readDate=Date.now())}))}}r.NotificationController=u}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1472,{"./errors":1475},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.decorateWithCaveats=void 0;const i=e("./errors");r.decorateWithCaveats=function(e,t,r){const{caveats:s}=t;if(!s)return e;let o=t=>n(this,void 0,void 0,(function*(){return e(t)}));for(const e of s){const t=r[e.type];if(!t)throw new i.UnrecognizedCaveatTypeError(e.type);o=t.decorator(o,e)}return o}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1473,{nanoid:1538},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.hasSpecificationType=r.PermissionType=r.findCaveat=r.constructPermission=void 0;const n=e("nanoid");r.constructPermission=function(e){const{caveats:t=null,invoker:r,target:i}=e;return{id:(0,n.nanoid)(),parentCapability:i,invoker:r,caveats:t,date:(new Date).getTime()}},r.findCaveat=function(e,t){var r;return null===(r=e.caveats)||void 0===r?void 0:r.find((e=>e.type===t))},function(e){e.RestrictedMethod="RestrictedMethod",e.Endowment="Endowment"}(r.PermissionType||(r.PermissionType={})),r.hasSpecificationType=function(e,t){return e.permissionType===t}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1474,{"../BaseControllerV2":1434,"../util":1489,"./Caveat":1472,"./Permission":1473,"./errors":1475,"./permission-middleware":1477,"./utils":1481,"deep-freeze-strict":2351,"eth-rpc-errors":2537,immer:4513,nanoid:1538},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__rest||function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i{if(!r||!(0,d.hasProperty)(p.PermissionType,r))throw new Error(`Invalid permission type: "${r}"`);if(!e||/_$/u.test(e)||/[^_]\*$/u.test(e))throw new Error(`Invalid permission target key: "${e}"`);if(e!==n)throw new Error(`Invalid permission specification: key "${e}" must match specification.target value "${n}".`);i&&i.forEach((e=>{if(!(0,d.hasProperty)(t,e))throw new f.UnrecognizedCaveatTypeError(e)}))}))}registerMessageHandlers(){this.messagingSystem.registerActionHandler(`${v}:clearPermissions`,(()=>this.clearState())),this.messagingSystem.registerActionHandler(`${v}:getEndowments`,((e,t,r)=>this.getEndowments(e,t,r))),this.messagingSystem.registerActionHandler(`${v}:getSubjectNames`,(()=>this.getSubjectNames())),this.messagingSystem.registerActionHandler(`${v}:getPermissions`,(e=>this.getPermissions(e))),this.messagingSystem.registerActionHandler(`${v}:hasPermission`,((e,t)=>this.hasPermission(e,t))),this.messagingSystem.registerActionHandler(`${v}:hasPermissions`,(e=>this.hasPermissions(e))),this.messagingSystem.registerActionHandler(`${v}:grantPermissions`,this.grantPermissions.bind(this)),this.messagingSystem.registerActionHandler(`${v}:requestPermissions`,((e,t)=>this.requestPermissions(e,t))),this.messagingSystem.registerActionHandler(`${v}:revokeAllPermissions`,(e=>this.revokeAllPermissions(e))),this.messagingSystem.registerActionHandler(`${v}:revokePermissionForAllSubjects`,(e=>this.revokePermissionForAllSubjects(e))),this.messagingSystem.registerActionHandler(`${v}:revokePermissions`,this.revokePermissions.bind(this))}clearState(){this.update((e=>Object.assign({},{subjects:{}})))}getTypedPermissionSpecification(e,t,r){const n=e===p.PermissionType.RestrictedMethod?(0,f.methodNotFound)(t,r?{origin:r}:undefined):new f.EndowmentPermissionDoesNotExistError(t,r),i=this.getTargetKey(t);if(!i)throw n;const s=this.getPermissionSpecification(i);if(!(0,p.hasSpecificationType)(s,e))throw n;return s}getRestrictedMethod(e,t){return this.getTypedPermissionSpecification(p.PermissionType.RestrictedMethod,e,t).methodImplementation}getSubjectNames(){return Object.keys(this.state.subjects)}getPermission(e,t){var r;return null===(r=this.state.subjects[e])||void 0===r?void 0:r.permissions[t]}getPermissions(e){var t;return null===(t=this.state.subjects[e])||void 0===t?void 0:t.permissions}hasPermission(e,t){return Boolean(this.getPermission(e,t))}hasPermissions(e){return Boolean(this.state.subjects[e])}revokeAllPermissions(e){this.update((t=>{if(!t.subjects[e])throw new f.UnrecognizedSubjectError(e);delete t.subjects[e]}))}revokePermission(e,t){this.revokePermissions({[e]:[t]})}revokePermissions(e){this.update((t=>{Object.keys(e).forEach((r=>{if(!(0,d.hasProperty)(t.subjects,r))throw new f.UnrecognizedSubjectError(r);e[r].forEach((e=>{const{permissions:n}=t.subjects[r];if(!(0,d.hasProperty)(n,e))throw new f.PermissionDoesNotExistError(r,e);this.deletePermission(t.subjects,r,e)}))}))}))}revokePermissionForAllSubjects(e){0!==this.getSubjectNames().length&&this.update((t=>{Object.entries(t.subjects).forEach((([r,n])=>{const{permissions:i}=n;(0,d.hasProperty)(i,e)&&this.deletePermission(t.subjects,r,e)}))}))}deletePermission(e,t,r){const{permissions:n}=e[t];Object.keys(n).length>1?delete n[r]:delete e[t]}hasCaveat(e,t,r){return Boolean(this.getCaveat(e,t,r))}getCaveat(e,t,r){const n=this.getPermission(e,t);if(!n)throw new f.PermissionDoesNotExistError(e,t);return(0,p.findCaveat)(n,r)}addCaveat(e,t,r,n){if(this.hasCaveat(e,t,r))throw new f.CaveatAlreadyExistsError(e,t,r);this.setCaveat(e,t,r,n)}updateCaveat(e,t,r,n){if(!this.hasCaveat(e,t,r))throw new f.CaveatDoesNotExistError(e,t,r);this.setCaveat(e,t,r,n)}setCaveat(e,t,r,n){this.update((i=>{const s=i.subjects[e];if(!s)throw new f.UnrecognizedSubjectError(e);const o=s.permissions[t];if(!o)throw new f.PermissionDoesNotExistError(e,t);const a={type:r,value:n};if(this.validateCaveat(a,e,t),o.caveats){const e=o.caveats.findIndex((e=>e.type===a.type));-1===e?o.caveats.push(a):o.caveats.splice(e,1,a)}else o.caveats=[a];this.validateModifiedPermission(o,e,t)}))}updatePermissionsByCaveat(e,t){0!==Object.keys(this.state.subjects).length&&this.update((r=>{Object.values(r.subjects).forEach((n=>{Object.values(n.permissions).forEach((i=>{const{caveats:s}=i,o=null==s?void 0:s.find((({type:t})=>t===e));if(!o)return;const a=t(o.value);switch(a.operation){case y.noop:break;case y.updateValue:o.value=a.value,this.validateCaveat(o,n.origin,i.parentCapability);break;case y.deleteCaveat:this.deleteCaveat(i,e,n.origin,i.parentCapability);break;case y.revokePermission:this.deletePermission(r.subjects,n.origin,i.parentCapability);break;default:throw new Error(`Unrecognized mutation result: "${a.operation}"`)}}))}))}))}removeCaveat(e,t,r){this.update((n=>{var i;const s=null===(i=n.subjects[e])||void 0===i?void 0:i.permissions[t];if(!s)throw new f.PermissionDoesNotExistError(e,t);if(!s.caveats)throw new f.CaveatDoesNotExistError(e,t,r);this.deleteCaveat(s,r,e,t)}))}deleteCaveat(e,t,r,n){if(!e.caveats)throw new f.CaveatDoesNotExistError(r,n,t);const i=e.caveats.findIndex((e=>e.type===t));if(-1===i)throw new f.CaveatDoesNotExistError(r,n,t);1===e.caveats.length?e.caveats=null:e.caveats.splice(i,1),this.validateModifiedPermission(e,r,n)}validateModifiedPermission(e,t,r){const n=this.getTargetKey(e.parentCapability);if(!n)throw new Error(`Fatal: Existing permission target key "${n}" has no specification.`);this.validatePermission(this.getPermissionSpecification(n),e,t,r)}getTargetKey(e){if((0,d.hasProperty)(this._permissionSpecifications,e))return e;const t={};for(const e of Object.keys(this._permissionSpecifications)){const r=e.match(/(.+)\*$/u);r&&(t[r[1]]=!0)}const r=e.split("_");let n="";for(;r.length>0&&!(0,d.hasProperty)(this._permissionSpecifications,n)&&!t[n];)n+=`${r.shift()}_`;return t[n]?`${n}*`:undefined}grantPermissions({approvedPermissions:e,requestData:t,preserveExistingPermissions:r=!0,subject:n}){const{origin:i}=n;if(!i||"string"!=typeof i)throw new f.InvalidSubjectIdentifierError(i);const s=r?Object.assign({},this.getPermissions(i)):{};for(const[r,n]of Object.entries(e)){const e=this.getTargetKey(r);if(!e)throw(0,f.methodNotFound)(r);if(n.parentCapability!==undefined&&r!==n.parentCapability)throw new f.InvalidApprovedPermissionError(i,r,n);const o=r,a=this.getPermissionSpecification(e),c={caveats:this.constructCaveats(i,o,n.caveats),invoker:i,target:o};let u;a.factory?(u=a.factory(c,t),this.validatePermission(a,u,i,o)):(u=(0,p.constructPermission)(c),this.validatePermission(a,u,i,o,{invokePermissionValidator:!0,performCaveatValidation:!1})),s[o]=u}return this.setValidatedPermissions(i,s),s}validatePermission(e,t,r,n,{invokePermissionValidator:i,performCaveatValidation:s}={invokePermissionValidator:!0,performCaveatValidation:!0}){const{allowedCaveats:o,validator:a}=e;if((0,d.hasProperty)(t,"caveats")){const{caveats:e}=t;if(null!==e&&!(Array.isArray(e)&&e.length>0))throw new f.InvalidCaveatsPropertyError(r,n,e);const i=new Set;null==e||e.forEach((e=>{if(s&&this.validateCaveat(e,r,n),!(null==o?void 0:o.includes(e.type)))throw new f.ForbiddenCaveatError(e.type,r,n);if(i.has(e.type))throw new f.DuplicateCaveatError(e.type,r,n);i.add(e.type)}))}i&&a&&a(t,r,n)}setValidatedPermissions(e,t){this.update((r=>{r.subjects[e]||(r.subjects[e]={origin:e,permissions:{}}),r.subjects[e].permissions=(0,a.castDraft)(t)}))}constructCaveats(e,t,r){const n=null==r?void 0:r.map((r=>{this.validateCaveat(r,e,t);const{type:n,value:i}=r;return{type:n,value:i}}));return n&&(0,d.isNonEmptyArray)(n)?n:undefined}validateCaveat(e,t,r){var n;if(!(0,d.isPlainObject)(e))throw new f.InvalidCaveatError(e,t,r);if(2!==Object.keys(e).length)throw new f.InvalidCaveatFieldsError(e,t,r);if("string"!=typeof e.type)throw new f.InvalidCaveatTypeError(e,t,r);const i=this.getCaveatSpecification(e.type);if(!i)throw new f.UnrecognizedCaveatTypeError(e.type,t,r);if(!(0,d.hasProperty)(e,"value")||e.value===undefined)throw new f.CaveatMissingValueError(e,t,r);if(!(0,d.isValidJson)(e.value))throw new f.CaveatInvalidJsonError(e,t,r);null===(n=i.validator)||void 0===n||n.call(i,e,t,r)}requestPermissions(e,t,r={}){return n(this,void 0,void 0,(function*(){const{origin:n}=e,{id:s=(0,c.nanoid)(),preserveExistingPermissions:o=!0}=r;this.validateRequestedPermissions(n,t);const a={id:s,origin:n},u={metadata:a,permissions:t},l=yield this.requestUserApproval(u),{permissions:d}=l,h=i(l,["permissions"]);return[this.grantPermissions({subject:e,approvedPermissions:d,preserveExistingPermissions:o,requestData:h}),a]}))}validateRequestedPermissions(e,t){if(!(0,d.isPlainObject)(t))throw(0,f.invalidParams)({message:`Requested permissions for origin "${e}" is not a plain object.`,data:{origin:e,requestedPermissions:t}});if(0===Object.keys(t).length)throw(0,f.invalidParams)({message:`Permissions request for origin "${e}" contains no permissions.`,data:{requestedPermissions:t}});for(const r of Object.keys(t)){const n=t[r],i=this.getTargetKey(r);if(!i)throw(0,f.methodNotFound)(r,{origin:e,requestedPermissions:t});if(!(0,d.isPlainObject)(n)||n.parentCapability!==undefined&&r!==n.parentCapability)throw(0,f.invalidParams)({message:`Permissions request for origin "${e}" contains invalid requested permission(s).`,data:{origin:e,requestedPermissions:t}});this.validatePermission(this.getPermissionSpecification(i),n,e,r,{invokePermissionValidator:!1,performCaveatValidation:!0})}}requestUserApproval(e){return n(this,void 0,void 0,(function*(){const{origin:t,id:r}=e.metadata,n=yield this.messagingSystem.call("ApprovalController:addRequest",{id:r,origin:t,requestData:e,type:g.MethodNames.requestPermissions},!0);return this.validateApprovedPermissions(n,{id:r,origin:t}),n}))}validateApprovedPermissions(e,t){const{id:r,origin:n}=t;if(!(0,d.isPlainObject)(e)||!(0,d.isPlainObject)(e.metadata))throw(0,f.internalError)(`Approved permissions request for subject "${n}" is invalid.`,{data:{approvedRequest:e}});const{metadata:{id:i,origin:s},permissions:o}=e;if(i!==r)throw(0,f.internalError)(`Approved permissions request for subject "${n}" mutated its id.`,{originalId:r,mutatedId:i});if(s!==n)throw(0,f.internalError)(`Approved permissions request for subject "${n}" mutated its origin.`,{originalOrigin:n,mutatedOrigin:s});try{this.validateRequestedPermissions(n,o)}catch(e){if(e instanceof u.EthereumRpcError)throw(0,f.internalError)(`Invalid approved permissions request: ${e.message}`,e.data);throw(0,f.internalError)("Unrecognized error type",{error:e})}}acceptPermissionsRequest(e){return n(this,void 0,void 0,(function*(){const{id:t}=e.metadata;if(!this.hasApprovalRequest({id:t}))throw new f.PermissionsRequestNotFoundError(t);if(0!==Object.keys(e.permissions).length)try{this.messagingSystem.call("ApprovalController:acceptRequest",t,e)}catch(e){throw this._rejectPermissionsRequest(t,e),e}else this._rejectPermissionsRequest(t,(0,f.invalidParams)({message:"Must request at least one permission."}))}))}rejectPermissionsRequest(e){return n(this,void 0,void 0,(function*(){if(!this.hasApprovalRequest({id:e}))throw new f.PermissionsRequestNotFoundError(e);this._rejectPermissionsRequest(e,(0,f.userRejectedRequest)())}))}hasApprovalRequest(e){return this.messagingSystem.call("ApprovalController:hasRequest",e)}_rejectPermissionsRequest(e,t){return this.messagingSystem.call("ApprovalController:rejectRequest",e,t)}getEndowments(e,t,r){return n(this,void 0,void 0,(function*(){if(!this.hasPermission(e,t))throw(0,f.unauthorized)({data:{origin:e,targetName:t}});return this.getTypedPermissionSpecification(p.PermissionType.Endowment,t,e).endowmentGetter({origin:e,requestData:r})}))}executeRestrictedMethod(e,t,r){return n(this,void 0,void 0,(function*(){const n=this.getRestrictedMethod(t,e),i=yield this._executeRestrictedMethod(n,{origin:e},t,r);if(i===undefined)throw new Error(`Internal request for method "${t}" as origin "${e}" returned no result.`);return i}))}_executeRestrictedMethod(e,t,r,n=[]){const{origin:i}=t,s=this.getPermission(i,r);if(!s)throw(0,f.unauthorized)({data:{origin:i,method:r}});return(0,h.decorateWithCaveats)(e,s,this._caveatSpecifications)({method:r,params:n,context:{origin:i}})}}r.PermissionController=w}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1475,{"eth-rpc-errors":2537},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.PermissionsRequestNotFoundError=r.DuplicateCaveatError=r.ForbiddenCaveatError=r.InvalidCaveatFieldsError=r.CaveatInvalidJsonError=r.CaveatMissingValueError=r.InvalidCaveatTypeError=r.InvalidCaveatError=r.CaveatAlreadyExistsError=r.CaveatDoesNotExistError=r.InvalidCaveatsPropertyError=r.UnrecognizedCaveatTypeError=r.EndowmentPermissionDoesNotExistError=r.PermissionDoesNotExistError=r.InvalidApprovedPermissionError=r.UnrecognizedSubjectError=r.InvalidSubjectIdentifierError=r.internalError=r.userRejectedRequest=r.invalidParams=r.methodNotFound=r.unauthorized=void 0;const n=e("eth-rpc-errors");r.unauthorized=function(e){return n.ethErrors.provider.unauthorized({message:"Unauthorized to perform action. Try requesting the required permission(s) first. For more information, see: https://docs.metamask.io/guide/rpc-api.html#permissions",data:e.data})},r.methodNotFound=function(e,t){const r={message:`The method "${e}" does not exist / is not available.`};return t!==undefined&&(r.data=t),n.ethErrors.rpc.methodNotFound(r)},r.invalidParams=function(e){return n.ethErrors.rpc.invalidParams({data:e.data,message:e.message})},r.userRejectedRequest=function(e){return n.ethErrors.provider.userRejectedRequest({data:e})},r.internalError=function(e,t){return n.ethErrors.rpc.internal({message:e,data:t})};class i extends Error{constructor(e){super(`Invalid subject identifier: "${"string"==typeof e?e:typeof e}"`)}}r.InvalidSubjectIdentifierError=i;class s extends Error{constructor(e){super(`Unrecognized subject: "${e}" has no permissions.`)}}r.UnrecognizedSubjectError=s;class o extends Error{constructor(e,t,r){super(`Invalid approved permission for origin "${e}" and target "${t}".`),this.data={origin:e,target:t,approvedPermission:r}}}r.InvalidApprovedPermissionError=o;class a extends Error{constructor(e,t){super(`Subject "${e}" has no permission for "${t}".`)}}r.PermissionDoesNotExistError=a;class c extends Error{constructor(e,t){super(`Subject "${t}" has no permission for "${e}".`),t&&(this.data={origin:t})}}r.EndowmentPermissionDoesNotExistError=c;class u extends Error{constructor(e,t,r){super(`Unrecognized caveat type: "${e}"`),this.data={caveatType:e},t!==undefined&&(this.data.origin=t),r!==undefined&&(this.data.target=r)}}r.UnrecognizedCaveatTypeError=u;class l extends Error{constructor(e,t,r){super(`The "caveats" property of permission for "${t}" of subject "${e}" is invalid. It must be a non-empty array if specified.`),this.data={origin:e,target:t,caveatsProperty:r}}}r.InvalidCaveatsPropertyError=l;class d extends Error{constructor(e,t,r){super(`Permission for "${t}" of subject "${e}" has no caveat of type "${r}".`)}}r.CaveatDoesNotExistError=d;class h extends Error{constructor(e,t,r){super(`Permission for "${t}" of subject "${e}" already has a caveat of type "${r}".`)}}r.CaveatAlreadyExistsError=h;class f extends n.EthereumRpcError{constructor(e,t,r){super(n.errorCodes.rpc.invalidParams,"Invalid caveat. Caveats must be plain objects.",{receivedCaveat:e}),this.data={origin:t,target:r}}}r.InvalidCaveatError=f;class p extends Error{constructor(e,t,r){super(`Caveat types must be strings. Received: "${typeof e.type}"`),this.data={caveat:e,origin:t,target:r}}}r.InvalidCaveatTypeError=p;class m extends Error{constructor(e,t,r){super('Caveat is missing "value" field.'),this.data={caveat:e,origin:t,target:r}}}r.CaveatMissingValueError=m;class g extends Error{constructor(e,t,r){super('Caveat "value" is invalid JSON.'),this.data={caveat:e,origin:t,target:r}}}r.CaveatInvalidJsonError=g;class v extends Error{constructor(e,t,r){super(`Caveat has unexpected number of fields: "${Object.keys(e).length}"`),this.data={caveat:e,origin:t,target:r}}}r.InvalidCaveatFieldsError=v;class y extends Error{constructor(e,t,r){super(`Permissions for target "${r}" may not have caveats of type "${e}".`),this.data={caveatType:e,origin:t,target:r}}}r.ForbiddenCaveatError=y;class w extends Error{constructor(e,t,r){super(`Permissions for target "${r}" contains multiple caveats of type "${e}".`),this.data={caveatType:e,origin:t,target:r}}}r.DuplicateCaveatError=w;class b extends Error{constructor(e){super(`Permissions request with id "${e}" not found.`)}}r.PermissionsRequestNotFoundError=b}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1476,{"./Caveat":1472,"./Permission":1473,"./PermissionController":1474,"./rpc-methods":1479,"./utils":1481},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(r,"__esModule",{value:!0}),r.permissionRpcMethods=void 0,s(e("./Caveat"),r),s(e("./Permission"),r),s(e("./PermissionController"),r),s(e("./utils"),r),r.permissionRpcMethods=o(e("./rpc-methods"))}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1477,{"./errors":1475,"json-rpc-engine":4837},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.getPermissionMiddlewareFactory=void 0;const i=e("json-rpc-engine"),s=e("./errors");r.getPermissionMiddlewareFactory=function({executeRestrictedMethod:e,getRestrictedMethod:t,isUnrestrictedMethod:r}){return function(o){const{origin:a}=o;if("string"!=typeof a||!a)throw new Error('The subject "origin" must be a non-empty string.');return(0,i.createAsyncMiddleware)(((i,c,u)=>n(this,void 0,void 0,(function*(){const{method:n,params:l}=i;if(r(n))return u();const d=t(n,a),h=yield e(d,o,n,l);return h===undefined?(c.error=(0,s.internalError)(`Request for method "${i.method}" returned undefined result.`,{request:i}),undefined):(c.result=h,undefined)}))))}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1478,{"../utils":1481},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.getPermissionsHandler=void 0;const i=e("../utils");r.getPermissionsHandler={methodNames:[i.MethodNames.getPermissions],implementation:function(e,t,r,i,{getPermissionsForOrigin:s}){return n(this,void 0,void 0,(function*(){return t.result=Object.values(s()||{}),i()}))},hookNames:{getPermissionsForOrigin:!0}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1479,{"./getPermissions":1478,"./requestPermissions":1480},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.handlers=void 0;const n=e("./requestPermissions"),i=e("./getPermissions");r.handlers=[n.requestPermissionsHandler,i.getPermissionsHandler]}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[148,{lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("lodash");var i={version:65,async migrate(e){const t=(0,n.cloneDeep)(e);t.meta.version=65;const r=function(e){if(e.PreferencesController){var t;const{completedOnboarding:r,firstTimeFlowType:n}=e.PreferencesController;e.OnboardingController=null!==(t=e.OnboardingController)&&void 0!==t?t:{},r!==undefined&&(e.OnboardingController.completedOnboarding=r,delete e.PreferencesController.completedOnboarding),n!==undefined&&(e.OnboardingController.firstTimeFlowType=n,delete e.PreferencesController.firstTimeFlowType)}return e}(t.data);return t.data=r,t}};r.default=i}}},{package:"$root$"}],[1480,{"../../util":1489,"../errors":1475,"../utils":1481,"eth-rpc-errors":2537},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.requestPermissionsHandler=void 0;const i=e("eth-rpc-errors"),s=e("../utils"),o=e("../errors"),a=e("../../util");r.requestPermissionsHandler={methodNames:[s.MethodNames.requestPermissions],implementation:function(e,t,r,s,{requestPermissionsForOrigin:c}){return n(this,void 0,void 0,(function*(){const{id:r,params:n}=e;if("number"!=typeof r&&"string"!=typeof r||"string"==typeof r&&!r)return s(i.ethErrors.rpc.invalidRequest({message:"Invalid request: Must specify a valid id.",data:{request:e}}));if(!Array.isArray(n)||!(0,a.isPlainObject)(n[0]))return s((0,o.invalidParams)({data:{request:e}}));const[u]=n,[l]=yield c(u,String(r));return t.result=Object.values(l),s()}))},hookNames:{requestPermissionsForOrigin:!0}}}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1481,{},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.MethodNames=void 0,function(e){e.requestPermissions="wallet_requestPermissions",e.getPermissions="wallet_getPermissions"}(r.MethodNames||(r.MethodNames={}))}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1482,{"../BaseControllerV2":1434,"eth-rpc-errors":2537},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(r,"__esModule",{value:!0}),r.RateLimitController=void 0;const i=e("eth-rpc-errors"),s=e("../BaseControllerV2"),o="RateLimitController",a={requests:{persist:!1,anonymous:!1}};class c extends s.BaseController{constructor({rateLimitTimeout:e=5e3,rateLimitCount:t=1,messenger:r,state:n,implementations:i}){const s={requests:Object.keys(i).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:{}})),{})};super({name:o,metadata:a,messenger:r,state:Object.assign(Object.assign({},s),n)}),this.implementations=i,this.rateLimitTimeout=e,this.rateLimitCount=t,this.messagingSystem.registerActionHandler(`${o}:call`,((e,t,...r)=>this.call(e,t,...r)))}call(e,t,...r){return n(this,void 0,void 0,(function*(){if(this.isRateLimited(t,e))throw i.ethErrors.rpc.limitExceeded({message:`"${t}" is currently rate-limited. Please try again later.`});this.recordRequest(t,e);const n=this.implementations[t];if(!n)throw new Error("Invalid api type");return n(...r)}))}isRateLimited(e,t){return this.state.requests[e][t]>=this.rateLimitCount}recordRequest(e,t){this.update((r=>{var n;const i=null!==(n=r.requests[e][t])&&void 0!==n?n:0;r.requests[e][t]=i+1,0===i&&setTimeout((()=>this.resetRequestCount(e,t)),this.rateLimitTimeout)}))}resetRequestCount(e,t){this.update((r=>{r.requests[e][t]=0}))}}r.RateLimitController=c}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1483,{"../BaseControllerV2":1434},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.SubjectMetadataController=void 0;const n=e("../BaseControllerV2"),i={subjectMetadata:{persist:!0,anonymous:!1}},s={subjectMetadata:{}};class o extends n.BaseController{constructor({messenger:e,subjectCacheLimit:t,state:r={}}){if(!Number.isInteger(t)||t<1)throw new Error(`subjectCacheLimit must be a positive integer. Received: "${t}"`);const n=t=>e.call("PermissionController:hasPermissions",t);super({name:"SubjectMetadataController",metadata:i,messenger:e,state:Object.assign({},o.getTrimmedState(r,n))}),this.subjectHasPermissions=n,this.subjectCacheLimit=t,this.subjectsWithoutPermissionsEcounteredSinceStartup=new Set}clearState(){this.subjectsWithoutPermissionsEcounteredSinceStartup.clear(),this.update((e=>Object.assign({},s)))}addSubjectMetadata(e){const{origin:t}=e,r=Object.assign(Object.assign({},e),{extensionId:e.extensionId||null,iconUrl:e.iconUrl||null,name:e.name||null});let n=null;if(this.subjectsWithoutPermissionsEcounteredSinceStartup.size>=this.subjectCacheLimit){const e=this.subjectsWithoutPermissionsEcounteredSinceStartup.values().next().value;this.subjectsWithoutPermissionsEcounteredSinceStartup.delete(e),this.subjectHasPermissions(e)||(n=e)}this.subjectsWithoutPermissionsEcounteredSinceStartup.add(t),this.update((e=>{e.subjectMetadata[t]=r,"string"==typeof n&&delete e.subjectMetadata[n]}))}trimMetadataState(){this.update((e=>o.getTrimmedState(e,this.subjectHasPermissions)))}static getTrimmedState(e,t){const{subjectMetadata:r={}}=e;return{subjectMetadata:Object.keys(r).reduce(((e,n)=>(t(n)&&(e[n]=r[n]),e)),{})}}}r.SubjectMetadataController=o}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1484,{"./SubjectMetadataController":1483},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e("./SubjectMetadataController"),r)}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1485,{"../BaseController":1433,"../util":1489,"eth-phishing-detect/src/config.json":2531,"eth-phishing-detect/src/detector":2532,"punycode/":5600},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.PhishingController=void 0;const s=e("punycode/"),o=i(e("eth-phishing-detect/src/config.json")),a=i(e("eth-phishing-detect/src/detector")),c=e("../BaseController"),u=e("../util");class l extends c.BaseController{constructor(e,t){super(e,t),this.configUrlMetaMask="https://cdn.jsdelivr.net/gh/MetaMask/eth-phishing-detect@master/src/config.json",this.configUrlPhishFortHotlist="https://cdn.jsdelivr.net/gh/phishfort/phishfort-lists@master/blacklists/hotlist.json",this.name="PhishingController",this.defaultConfig={interval:36e5},this.defaultState={phishing:[{allowlist:o.default.whitelist,blocklist:o.default.blacklist,fuzzylist:o.default.fuzzylist,tolerance:o.default.tolerance,name:"MetaMask",version:o.default.version}],whitelist:[]},this.detector=new a.default(this.defaultState.phishing),this.initialize(),this.poll()}poll(e){return n(this,void 0,void 0,(function*(){e&&this.configure({interval:e},!1,!1),this.handle&&clearTimeout(this.handle),yield(0,u.safelyExecute)((()=>this.updatePhishingLists())),this.handle=setTimeout((()=>{this.poll(this.config.interval)}),this.config.interval)}))}test(e){const t=(0,s.toASCII)(e);return-1!==this.state.whitelist.indexOf(t)?{result:!1,type:"all"}:this.detector.check(t)}bypass(e){const t=(0,s.toASCII)(e),{whitelist:r}=this.state;-1===r.indexOf(t)&&this.update({whitelist:[...r,t]})}updatePhishingLists(){return n(this,void 0,void 0,(function*(){if(this.disabled)return;const e=[],[t,r]=yield Promise.all([yield this.queryConfig(this.configUrlMetaMask),yield this.queryConfig(this.configUrlPhishFortHotlist)]),n={allowlist:t?t.whitelist:[],blocklist:t?t.blacklist:[],fuzzylist:t?t.fuzzylist:[],tolerance:t?t.tolerance:0,name:"MetaMask",version:t?t.version:0};t&&e.push(n);const i={allowlist:[],blocklist:(r||[]).filter((e=>!n.blocklist.includes(e))),fuzzylist:[],tolerance:0,name:"PhishFort",version:1};r&&e.push(i),e.length&&(this.detector=new a.default(e),this.update({phishing:e}))}))}queryConfig(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(e,{cache:"no-cache"});return 200===t.status?yield t.json():null}))}}r.PhishingController=l,r.default=l}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1486,{"../BaseController":1433,"../constants":1455,"../util":1489,"@ethereumjs/common":406,"@ethereumjs/tx":410,"async-mutex":1830,"eth-method-registry":1516,"eth-query":2533,"eth-rpc-errors":2537,"ethereumjs-util":2612,events:2176,uuid:6096},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.TransactionController=r.SPEED_UP_RATE=r.CANCEL_RATE=r.WalletDevice=r.TransactionStatus=void 0;const s=e("events"),o=e("ethereumjs-util"),a=e("eth-rpc-errors"),c=i(e("eth-method-registry")),u=i(e("eth-query")),l=i(e("@ethereumjs/common")),d=e("@ethereumjs/tx"),h=e("uuid"),f=e("async-mutex"),p=e("../BaseController"),m=e("../util"),g=e("../constants"),v="london";var y;!function(e){e.approved="approved",e.cancelled="cancelled",e.confirmed="confirmed",e.failed="failed",e.rejected="rejected",e.signed="signed",e.submitted="submitted",e.unapproved="unapproved"}(y=r.TransactionStatus||(r.TransactionStatus={})),function(e){e.MM_MOBILE="metamask_mobile",e.MM_EXTENSION="metamask_extension",e.OTHER="other_device"}(r.WalletDevice||(r.WalletDevice={})),r.CANCEL_RATE=1.5,r.SPEED_UP_RATE=1.1;class w extends p.BaseController{constructor({getNetworkState:e,onNetworkStateChange:t,getProvider:r},n,i){super(n,i),this.mutex=new f.Mutex,this.normalizeTokenTx=(e,t,r)=>{const n=1e3*parseInt(e.timeStamp,10),{to:i,from:s,gas:o,gasPrice:a,gasUsed:c,hash:u,contractAddress:l,tokenDecimal:d,tokenSymbol:f,value:p}=e;return{id:(0,h.v1)({msecs:n}),isTransfer:!0,networkID:t,chainId:r,status:y.confirmed,time:n,transaction:{chainId:1,from:s,gas:o,gasPrice:a,gasUsed:c,to:i,value:p},transactionHash:u,transferInformation:{contractAddress:l,decimals:Number(d),symbol:f},verifiedOnBlockchain:!1}},this.hub=new s.EventEmitter,this.name="TransactionController",this.defaultConfig={interval:15e3,txHistoryLimit:40},this.defaultState={methodData:{},transactions:[]},this.initialize();const o=r();this.getNetworkState=e,this.ethQuery=new u.default(o),this.registry=new c.default({provider:o}),t((()=>{const e=r();this.ethQuery=new u.default(e),this.registry=new c.default({provider:e})})),this.poll()}failTransaction(e,t){const r=Object.assign(Object.assign({},e),{error:t,status:y.failed});this.updateTransaction(r),this.hub.emit(`${e.id}:finished`,r)}registryLookup(e){return n(this,void 0,void 0,(function*(){const t=yield this.registry.lookup(e);return{registryMethod:t,parsedRegistryMethod:this.registry.parse(t)}}))}normalizeTx(e,t,r){const n=1e3*parseInt(e.timeStamp,10),i={blockNumber:e.blockNumber,id:(0,h.v1)({msecs:n}),networkID:t,chainId:r,time:n,transaction:{data:e.input,from:e.from,gas:(0,m.BNToHex)(new o.BN(e.gas)),gasPrice:(0,m.BNToHex)(new o.BN(e.gasPrice)),gasUsed:(0,m.BNToHex)(new o.BN(e.gasUsed)),nonce:(0,m.BNToHex)(new o.BN(e.nonce)),to:e.to,value:(0,m.BNToHex)(new o.BN(e.value))},transactionHash:e.hash,verifiedOnBlockchain:!1};return"0"===e.isError?Object.assign(Object.assign({},i),{status:y.confirmed}):Object.assign(Object.assign({},i),{error:new Error("Transaction failed"),status:y.failed})}poll(e){return n(this,void 0,void 0,(function*(){e&&this.configure({interval:e},!1,!1),this.handle&&clearTimeout(this.handle),yield(0,m.safelyExecute)((()=>this.queryTransactionStatuses())),this.handle=setTimeout((()=>{this.poll(this.config.interval)}),this.config.interval)}))}handleMethodData(e){return n(this,void 0,void 0,(function*(){const t=yield this.mutex.acquire();try{const{methodData:r}=this.state;if(Object.keys(r).find((t=>e===t)))return r[e];const n=yield this.registryLookup(e);return this.update({methodData:Object.assign(Object.assign({},r),{[e]:n})}),n}finally{t()}}))}addTransaction(e,t,r){return n(this,void 0,void 0,(function*(){const{provider:n,network:i}=this.getNetworkState(),{transactions:s}=this.state;e=(0,m.normalizeTransaction)(e),(0,m.validateTransaction)(e);const o={id:(0,h.v1)(),networkID:i,chainId:n.chainId,origin:t,status:y.unapproved,time:Date.now(),transaction:e,deviceConfirmedOn:r,verifiedOnBlockchain:!1};try{const{gas:t}=yield this.estimateGas(e);e.gas=t}catch(e){return this.failTransaction(o,e),Promise.reject(e)}const c=new Promise(((e,t)=>{this.hub.once(`${o.id}:finished`,(r=>{switch(r.status){case y.submitted:return e(r.transactionHash);case y.rejected:return t(a.ethErrors.provider.userRejectedRequest("User rejected the transaction"));case y.cancelled:return t(a.ethErrors.rpc.internal("User cancelled the transaction"));case y.failed:return t(a.ethErrors.rpc.internal(r.error.message));default:return t(a.ethErrors.rpc.internal(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(r)}`))}}))}));return s.push(o),this.update({transactions:this.trimTransactionsForState(s)}),this.hub.emit("unapprovedTransaction",o),{result:c,transactionMeta:o}}))}prepareUnsignedEthTx(e){return d.TransactionFactory.fromTxData(e,{common:this.getCommonConfiguration(),freeze:!1})}getCommonConfiguration(){const{network:e,provider:{type:t,chainId:r,nickname:n}}=this.getNetworkState();if(t!==g.RPC)return new l.default({chain:t,hardfork:v});const i={name:n,chainId:parseInt(r,undefined),networkId:parseInt(e,undefined)};return l.default.forCustomChain(g.MAINNET,i,v)}approveTransaction(e){return n(this,void 0,void 0,(function*(){const{transactions:t}=this.state,r=yield this.mutex.acquire(),{provider:n}=this.getNetworkState(),{chainId:i}=n,s=t.findIndex((({id:t})=>e===t)),a=t[s],{nonce:c}=a.transaction;try{const{from:e}=a.transaction;if(!this.sign)return r(),void this.failTransaction(a,new Error("No sign method defined."));if(!i)return r(),void this.failTransaction(a,new Error("No chainId defined."));const t=parseInt(i,undefined),{approved:n}=y,s=c||(yield(0,m.query)(this.ethQuery,"getTransactionCount",[e,"pending"]));a.status=n,a.transaction.nonce=s,a.transaction.chainId=t;const u=Object.assign(Object.assign({},a.transaction),{gasLimit:a.transaction.gas,chainId:t,nonce:s,status:n}),l=(0,m.isEIP1559Transaction)(a.transaction),d=l?Object.assign(Object.assign({},u),{maxFeePerGas:a.transaction.maxFeePerGas,maxPriorityFeePerGas:a.transaction.maxPriorityFeePerGas,estimatedBaseFee:a.transaction.estimatedBaseFee,type:2}):u;l&&delete d.gasPrice;const h=this.prepareUnsignedEthTx(d),f=yield this.sign(h,e);a.status=y.signed,this.updateTransaction(a);const p=(0,o.bufferToHex)(f.serialize());a.rawTransaction=p,this.updateTransaction(a);const g=yield(0,m.query)(this.ethQuery,"sendRawTransaction",[p]);a.transactionHash=g,a.status=y.submitted,this.updateTransaction(a),this.hub.emit(`${a.id}:finished`,a)}catch(e){this.failTransaction(a,e)}finally{r()}}))}cancelTransaction(e){const t=this.state.transactions.find((({id:t})=>t===e));if(!t)return;t.status=y.rejected,this.hub.emit(`${t.id}:finished`,t);const r=this.state.transactions.filter((({id:t})=>t!==e));this.update({transactions:this.trimTransactionsForState(r)})}stopTransaction(e,t){var i,s;return n(this,void 0,void 0,(function*(){t&&(0,m.validateGasValues)(t);const n=this.state.transactions.find((({id:t})=>t===e));if(!n)return;if(!this.sign)throw new Error("No sign method defined.");const a=(0,m.getIncreasedPriceFromExisting)(n.transaction.gasPrice,r.CANCEL_RATE),c=(0,m.isGasPriceValue)(t)&&t.gasPrice,u=c&&(0,m.validateMinimumIncrease)(c,a)||a,l=null===(i=n.transaction)||void 0===i?void 0:i.maxFeePerGas,d=(0,m.getIncreasedPriceFromExisting)(l,r.CANCEL_RATE),h=(0,m.isFeeMarketEIP1559Values)(t)&&t.maxFeePerGas,f=h&&(0,m.validateMinimumIncrease)(h,d)||l&&d,p=null===(s=n.transaction)||void 0===s?void 0:s.maxPriorityFeePerGas,g=(0,m.getIncreasedPriceFromExisting)(p,r.CANCEL_RATE),v=(0,m.isFeeMarketEIP1559Values)(t)&&t.maxPriorityFeePerGas,w=v&&(0,m.validateMinimumIncrease)(v,g)||p&&g,b=f&&w?{from:n.transaction.from,gasLimit:n.transaction.gas,maxFeePerGas:f,maxPriorityFeePerGas:w,type:2,nonce:n.transaction.nonce,to:n.transaction.from,value:"0x0"}:{from:n.transaction.from,gasLimit:n.transaction.gas,gasPrice:u,nonce:n.transaction.nonce,to:n.transaction.from,value:"0x0"},P=this.prepareUnsignedEthTx(b),E=yield this.sign(P,n.transaction.from),k=(0,o.bufferToHex)(E.serialize());yield(0,m.query)(this.ethQuery,"sendRawTransaction",[k]),n.status=y.cancelled,this.hub.emit(`${n.id}:finished`,n)}))}speedUpTransaction(e,t){var i,s;return n(this,void 0,void 0,(function*(){t&&(0,m.validateGasValues)(t);const n=this.state.transactions.find((({id:t})=>t===e));if(!n)return;if(!this.sign)throw new Error("No sign method defined.");const{transactions:a}=this.state,c=(0,m.getIncreasedPriceFromExisting)(n.transaction.gasPrice,r.SPEED_UP_RATE),u=(0,m.isGasPriceValue)(t)&&t.gasPrice,l=u&&(0,m.validateMinimumIncrease)(u,c)||c,d=null===(i=n.transaction)||void 0===i?void 0:i.maxFeePerGas,f=(0,m.getIncreasedPriceFromExisting)(d,r.SPEED_UP_RATE),p=(0,m.isFeeMarketEIP1559Values)(t)&&t.maxFeePerGas,g=p&&(0,m.validateMinimumIncrease)(p,f)||d&&f,v=null===(s=n.transaction)||void 0===s?void 0:s.maxPriorityFeePerGas,y=(0,m.getIncreasedPriceFromExisting)(v,r.SPEED_UP_RATE),w=(0,m.isFeeMarketEIP1559Values)(t)&&t.maxPriorityFeePerGas,b=w&&(0,m.validateMinimumIncrease)(w,y)||v&&y,P=g&&b?Object.assign(Object.assign({},n.transaction),{gasLimit:n.transaction.gas,maxFeePerGas:g,maxPriorityFeePerGas:b,type:2}):Object.assign(Object.assign({},n.transaction),{gasLimit:n.transaction.gas,gasPrice:l}),E=this.prepareUnsignedEthTx(P),k=yield this.sign(E,n.transaction.from),_=(0,o.bufferToHex)(k.serialize()),M=yield(0,m.query)(this.ethQuery,"sendRawTransaction",[_]),S=Object.assign(Object.assign({},n),{id:(0,h.v1)(),time:Date.now(),transactionHash:M}),C=g&&b?Object.assign(Object.assign({},S),{transaction:Object.assign(Object.assign({},n.transaction),{maxFeePerGas:g,maxPriorityFeePerGas:b})}):Object.assign(Object.assign({},S),{transaction:Object.assign(Object.assign({},n.transaction),{gasPrice:l})});a.push(C),this.update({transactions:this.trimTransactionsForState(a)}),this.hub.emit(`${n.id}:speedup`,C)}))}estimateGas(e){return n(this,void 0,void 0,(function*(){const t=Object.assign({},e),{gas:r,gasPrice:n,to:i,value:s,data:a}=t,c=void 0===n?yield(0,m.query)(this.ethQuery,"gasPrice"):n,{isCustomNetwork:u}=this.getNetworkState();if(void 0!==r)return{gas:r,gasPrice:c};const{gasLimit:l}=yield(0,m.query)(this.ethQuery,"getBlockByNumber",["latest",!1]),d=i?yield(0,m.query)(this.ethQuery,"getCode",[i]):undefined;if(!u&&(!i||i&&!a&&(!d||"0x"===d)))return{gas:"0x5208",gasPrice:c};t.data=a?(0,o.addHexPrefix)(a):a,t.value=void 0===s?"0x0":s;const h=(0,m.hexToBN)(l);t.gas=(0,m.BNToHex)((0,m.fractionBN)(h,19,20));const f=yield(0,m.query)(this.ethQuery,"estimateGas",[t]),p=(0,m.hexToBN)(f),g=h.muln(.9),v=p.muln(1.5);return p.gt(g)||u?{gas:(0,o.addHexPrefix)(f),gasPrice:c}:v.lt(g)?{gas:(0,o.addHexPrefix)((0,m.BNToHex)(v)),gasPrice:c}:{gas:(0,o.addHexPrefix)((0,m.BNToHex)(g)),gasPrice:c}}))}queryTransactionStatuses(){return n(this,void 0,void 0,(function*(){const{transactions:e}=this.state,{provider:t,network:r}=this.getNetworkState(),{chainId:i}=t;let s=!1;yield(0,m.safelyExecute)((()=>Promise.all(e.map(((t,o)=>n(this,void 0,void 0,(function*(){const n=t.chainId===i||!t.chainId&&t.networkID===r;if(!t.verifiedOnBlockchain&&n){const[r,n]=yield this.blockchainTransactionStateReconciler(t);n&&(e[o]=r,s=n)}}))))))),s&&this.update({transactions:this.trimTransactionsForState(e)})}))}updateTransaction(e){const{transactions:t}=this.state;e.transaction=(0,m.normalizeTransaction)(e.transaction),(0,m.validateTransaction)(e.transaction);const r=t.findIndex((({id:t})=>e.id===t));t[r]=e,this.update({transactions:this.trimTransactionsForState(t)})}wipeTransactions(e){if(e)return void this.update({transactions:[]});const{provider:t,network:r}=this.getNetworkState(),{chainId:n}=t,i=this.state.transactions.filter((({networkID:e,chainId:t})=>!(t===n||!t&&e===r)));this.update({transactions:this.trimTransactionsForState(i)})}fetchAll(e,t){return n(this,void 0,void 0,(function*(){const{provider:r,network:i}=this.getNetworkState(),{chainId:s,type:o}=r,{transactions:a}=this.state;if(-1===["1","3","4","42"].indexOf(i))return undefined;const[c,u]=yield(0,m.handleTransactionFetch)(o,e,this.config.txHistoryLimit,t),l=c.result.map((e=>this.normalizeTx(e,i,s))),d=u.result.map((e=>this.normalizeTokenTx(e,i,s))),[h,f]=this.etherscanTransactionStateReconciler([...l,...d],a);let p;return f.sort(((e,t)=>e.timen(this,void 0,void 0,(function*(){if((t.chainId===s||!t.chainId&&t.networkID===i)&&t.transaction.to&&t.transaction.to.toLowerCase()===e.toLowerCase()&&t.blockNumber&&(!p||parseInt(p,10){const{chainId:r,networkID:n,status:i,transaction:s,time:o}=e;if(s){const e=`${s.nonce}-${null!=r?r:n}-${new Date(o).toDateString()}`;if(t.has(e))return!0;if(t.size{const t=r.findIndex((({transactionHash:t})=>t===e.transactionHash));return-1===t?e:r[t]}));return[n.length>0||i.length>0,[...n,...i]]}getNewTransactions(e,t){return e.filter((e=>!t.find((({transactionHash:t})=>t===e.transactionHash))))}getUpdatedTransactions(e,t){return e.filter((e=>t.find((t=>e.transactionHash===t.transactionHash&&this.isTransactionOutdated(e,t)))))}isTransactionOutdated(e,t){const r=this.isStatusOutdated(e.transactionHash,t.transactionHash,e.status,t.status),n=this.isGasDataOutdated(e.transaction.gasUsed,t.transaction.gasUsed);return r||n}isStatusOutdated(e,t,r,n){return e===t&&r!==n}isGasDataOutdated(e,t){return e!==t}}r.TransactionController=w,r.default=w}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1487,{"../BaseController":1433,"../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.AddressBookController=void 0;const n=e("../util"),i=e("../BaseController");class s extends i.BaseController{constructor(e,t){super(e,t),this.name="AddressBookController",this.defaultState={addressBook:{}},this.initialize()}clear(){this.update({addressBook:{}})}delete(e,t){if(t=(0,n.toChecksumHexAddress)(t),!(0,n.isValidHexAddress)(t)||!this.state.addressBook[e]||!this.state.addressBook[e][t])return!1;const r=Object.assign({},this.state.addressBook);return delete r[e][t],0===Object.keys(r[e]).length&&delete r[e],this.update({addressBook:r}),!0}set(e,t,r="1",i=""){if(e=(0,n.toChecksumHexAddress)(e),!(0,n.isValidHexAddress)(e))return!1;const s={address:e,chainId:r,isEns:!1,memo:i,name:t},o=(0,n.normalizeEnsName)(t);return o&&(s.name=o,s.isEns=!0),this.update({addressBook:Object.assign(Object.assign({},this.state.addressBook),{[r]:Object.assign(Object.assign({},this.state.addressBook[r]),{[e]:s})})}),!0}}r.AddressBookController=s,r.default=s}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1488,{"../BaseController":1433,"../util":1489},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.PreferencesController=void 0;const n=e("../BaseController"),i=e("../util");class s extends n.BaseController{constructor(e,t){super(e,t),this.name="PreferencesController",this.defaultState={featureFlags:{},frequentRpcList:[],identities:{},ipfsGateway:"https://ipfs.io/ipfs/",lostIdentities:{},selectedAddress:"",useTokenDetection:!0,useCollectibleDetection:!1,openSeaEnabled:!1},this.initialize()}addIdentities(e){const{identities:t}=this.state;e.forEach((e=>{if(e=(0,i.toChecksumHexAddress)(e),t[e])return;const r=Object.keys(t).length;t[e]={name:`Account ${r+1}`,address:e,importTime:Date.now()}})),this.update({identities:Object.assign({},t)})}removeIdentity(e){e=(0,i.toChecksumHexAddress)(e);const{identities:t}=this.state;t[e]&&(delete t[e],this.update({identities:Object.assign({},t)}),e===this.state.selectedAddress&&this.update({selectedAddress:Object.keys(t)[0]}))}setAccountLabel(e,t){e=(0,i.toChecksumHexAddress)(e);const{identities:r}=this.state;r[e]=r[e]||{},r[e].name=t,this.update({identities:Object.assign({},r)})}setFeatureFlag(e,t){const r=this.state.featureFlags,n=Object.assign(Object.assign({},r),{[e]:t});this.update({featureFlags:Object.assign({},n)})}syncIdentities(e){e=e.map((e=>(0,i.toChecksumHexAddress)(e)));const{identities:t,lostIdentities:r}=this.state,n={};for(const r in t)-1===e.indexOf(r)&&(n[r]=t[r],delete t[r]);if(Object.keys(n).length>0)for(const e in n)r[e]=n[e];return this.update({identities:Object.assign({},t),lostIdentities:Object.assign({},r)}),this.addIdentities(e),-1===e.indexOf(this.state.selectedAddress)&&this.update({selectedAddress:e[0]}),this.state.selectedAddress}updateIdentities(e){e=e.map((e=>(0,i.toChecksumHexAddress)(e)));const t=this.state.identities,r=e.reduce(((e,r,n)=>(e[r]=t[r]||{address:r,name:`Account ${n+1}`,importTime:Date.now()},e)),{});let{selectedAddress:n}=this.state;Object.keys(r).includes(n)||(n=Object.keys(r)[0]),this.update({identities:Object.assign({},r),selectedAddress:n})}addToFrequentRpcList(e,t,r,n,i){const{frequentRpcList:s}=this.state,o=s.findIndex((({rpcUrl:t})=>t===e));-1!==o&&s.splice(o,1);const a={rpcUrl:e,chainId:t,ticker:r,nickname:n,rpcPrefs:i};s.push(a),this.update({frequentRpcList:[...s]})}removeFromFrequentRpcList(e){const{frequentRpcList:t}=this.state,r=t.findIndex((({rpcUrl:t})=>t===e));-1!==r&&t.splice(r,1),this.update({frequentRpcList:[...t]})}setSelectedAddress(e){this.update({selectedAddress:(0,i.toChecksumHexAddress)(e)})}setIpfsGateway(e){this.update({ipfsGateway:e})}setUseTokenDetection(e){this.update({useTokenDetection:e})}setUseCollectibleDetection(e){if(e&&!this.state.openSeaEnabled)throw new Error("useCollectibleDetection cannot be enabled if openSeaEnabled is false");this.update({useCollectibleDetection:e})}setOpenSeaEnabled(e){this.update({openSeaEnabled:e}),e||this.update({useCollectibleDetection:!1})}}r.PreferencesController=s,r.default=s}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[1489,{"./constants":1455,buffer:2175,"eth-ens-namehash":2462,"eth-rpc-errors":2537,"eth-sig-util":2539,"ethereumjs-util":2612,"ethjs-unit":2664,"fast-deep-equal":4384,jsonschema:4850,"multiformats/cid":5314},function(){with(this)return function(){"use strict";return function(e,t,r){(function(t){(function(){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.isTokenDetectionSupportedForNetwork=r.SupportedTokenDetectionNetworks=r.isValidJson=r.isNonEmptyArray=r.hasProperty=r.isPlainObject=r.getFormattedIpfsUrl=r.addUrlProtocolPrefix=r.getIpfsCIDv1AndPath=r.removeIpfsProtocolPrefix=r.validateMinimumIncrease=r.isGasPriceValue=r.isFeeMarketEIP1559Values=r.validateGasValues=r.getIncreasedPriceFromExisting=r.getIncreasedPriceHex=r.convertHexToDecimal=r.isEIP1559Transaction=r.query=r.normalizeEnsName=r.timeoutFetch=r.fetchWithErrorHandling=r.handleFetch=r.successfulFetch=r.isSmartContractCode=r.validateTokenToWatch=r.validateTypedSignMessageDataV3=r.validateTypedSignMessageDataV1=r.validateSignMessageData=r.normalizeMessageData=r.validateTransaction=r.isValidHexAddress=r.toChecksumHexAddress=r.safelyExecuteWithTimeout=r.safelyExecute=r.normalizeTransaction=r.toHex=r.fromHex=r.hexToText=r.hexToBN=r.handleTransactionFetch=r.getEtherscanApiUrl=r.getBuyURL=r.weiHexToGweiDec=r.gweiDecToWEIBN=r.fractionBN=r.BNToHex=void 0;const s=e("ethereumjs-util"),o=e("ethjs-unit"),a=e("eth-rpc-errors"),c=i(e("eth-ens-namehash")),u=e("eth-sig-util"),l=e("jsonschema"),d=e("multiformats/cid"),h=i(e("fast-deep-equal")),f=e("./constants"),p=new Error("timeout"),m=/^[0-9A-Fa-f]+$/gu,g={data:e=>(0,s.addHexPrefix)(e),from:e=>(0,s.addHexPrefix)(e).toLowerCase(),gas:e=>(0,s.addHexPrefix)(e),gasPrice:e=>(0,s.addHexPrefix)(e),nonce:e=>(0,s.addHexPrefix)(e),to:e=>(0,s.addHexPrefix)(e).toLowerCase(),value:e=>(0,s.addHexPrefix)(e),maxFeePerGas:e=>(0,s.addHexPrefix)(e),maxPriorityFeePerGas:e=>(0,s.addHexPrefix)(e),estimatedBaseFee:e=>(0,s.addHexPrefix)(e)};function v(e,t){let r="api";e!==f.MAINNET&&(r=`api-${e}`);let n=`${`https://${r}.etherscan.io`}/api?`;for(const e in t)t[e]&&(n+=`${e}=${t[e]}&`);return n+="tag=latest&page=1",n}function y(e){return new s.BN((0,s.stripHexPrefix)(e),16)}function w(e,{allowNonPrefixed:t=!0}={}){const r=t?(0,s.addHexPrefix)(e):e;return!!(0,s.isHexString)(r)&&(0,s.isValidAddress)(r)}function b(e,t){return n(this,void 0,void 0,(function*(){const r=yield fetch(e,t);if(!r.ok)throw new Error(`Fetch failed with status '${r.status}' for request '${e}'`);return r}))}function P(e,t){return n(this,void 0,void 0,(function*(){const r=yield b(e,t);return yield r.json()}))}r.BNToHex=function(e){return(0,s.addHexPrefix)(e.toString(16))},r.fractionBN=function(e,t,r){const n=new s.BN(t),i=new s.BN(r);return e.mul(n).div(i)},r.gweiDecToWEIBN=function(e){if(Number.isNaN(e))return new s.BN(0);const t=e.toString().split("."),r=t[0]||"0";let n=t[1]||"";if(!n)return(0,o.toWei)(r,"gwei");if(n.length<=9)return(0,o.toWei)(`${r}.${n}`,"gwei");const i=n.slice(9)[0];n=n.slice(0,9);let a=(0,o.toWei)(`${r}.${n}`,"gwei");return Number(i)>=5&&(a=a.add(new s.BN(1))),a},r.weiHexToGweiDec=function(e){const t=new s.BN((0,s.stripHexPrefix)(e),16);return(0,o.fromWei)(t,"gwei").toString(10)},r.getBuyURL=function(e="1",t,r=5){switch(e){case"1":return`https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${r}&address=${t}&crypto_currency=ETH`;case"3":return"https://faucet.metamask.io/";case"4":return"https://www.rinkeby.io/";case"5":return"https://goerli-faucet.slock.it/";case"42":return"https://github.com/kovan-testnet/faucet";default:return undefined}},r.getEtherscanApiUrl=v,r.handleTransactionFetch=function(e,t,r,i){return n(this,void 0,void 0,(function*(){const n={module:"account",address:t,startBlock:null==i?void 0:i.fromBlock,apikey:null==i?void 0:i.etherscanApiKey,offset:r.toString(),order:"desc"},s=P(v(e,Object.assign(Object.assign({},n),{action:"txlist"}))),o=P(v(e,Object.assign(Object.assign({},n),{action:"tokentx"})));let[a,c]=yield Promise.all([s,o]);return("0"===a.status||a.result.length<=0)&&(a={status:a.status,result:[]}),("0"===c.status||c.result.length<=0)&&(c={status:c.status,result:[]}),[a,c]}))},r.hexToBN=y,r.hexToText=function(e){try{const r=(0,s.stripHexPrefix)(e);return t.from(r,"hex").toString("utf8")}catch(t){return e}},r.fromHex=function(e){return s.BN.isBN(e)?e:new s.BN(y(e).toString(10))},r.toHex=function(e){return"string"==typeof e&&(0,s.isHexString)(e)?e:`0x${s.BN.isBN(e)?e.toString(16):new s.BN(e.toString(),10).toString(16)}`},r.normalizeTransaction=function(e){const t={from:""};let r;for(r in g)e[r]&&(t[r]=g[r](e[r]));return t},r.safelyExecute=function(e,t=!1){return n(this,void 0,void 0,(function*(){try{return yield e()}catch(e){return t&&console.error(e),undefined}}))},r.safelyExecuteWithTimeout=function(e,t=!1,r=500){return n(this,void 0,void 0,(function*(){try{return yield Promise.race([e(),new Promise(((e,t)=>setTimeout((()=>{t(p)}),r)))])}catch(e){return t&&console.error(e),undefined}}))},r.toChecksumHexAddress=function(e){const t=(0,s.addHexPrefix)(e);return(0,s.isHexString)(t)?(0,s.toChecksumAddress)(t):t},r.isValidHexAddress=w,r.validateTransaction=function(e){if(!e.from||"string"!=typeof e.from||!w(e.from))throw new Error(`Invalid "from" address: ${e.from} must be a valid string.`);if("0x"===e.to||e.to===undefined){if(!e.data)throw new Error(`Invalid "to" address: ${e.to} must be a valid string.`);delete e.to}else if(e.to!==undefined&&!w(e.to))throw new Error(`Invalid "to" address: ${e.to} must be a valid string.`);if(e.value!==undefined){const t=e.value.toString();if(t.includes("-"))throw new Error(`Invalid "value": ${t} is not a positive number.`);if(t.includes("."))throw new Error(`Invalid "value": ${t} number must be denominated in wei.`);const r=parseInt(e.value,10);if(!(Number.isFinite(r)&&!Number.isNaN(r)&&!isNaN(Number(t))&&Number.isSafeInteger(r)))throw new Error(`Invalid "value": ${t} number must be a valid number.`)}},r.normalizeMessageData=function(e){try{const t=(0,s.stripHexPrefix)(e);if(t.match(m))return(0,s.addHexPrefix)(t)}catch(e){}return(0,s.bufferToHex)(t.from(e,"utf8"))},r.validateSignMessageData=function(e){const{from:t,data:r}=e;if(!t||"string"!=typeof t||!w(t))throw new Error(`Invalid "from" address: ${t} must be a valid string.`);if(!r||"string"!=typeof r)throw new Error(`Invalid message "data": ${r} must be a valid string.`)},r.validateTypedSignMessageDataV1=function(e){if(!e.from||"string"!=typeof e.from||!w(e.from))throw new Error(`Invalid "from" address: ${e.from} must be a valid string.`);if(!e.data||!Array.isArray(e.data))throw new Error(`Invalid message "data": ${e.data} must be a valid array.`);try{(0,u.typedSignatureHash)(e.data)}catch(e){throw new Error("Expected EIP712 typed data.")}},r.validateTypedSignMessageDataV3=function(e){if(!e.from||"string"!=typeof e.from||!w(e.from))throw new Error(`Invalid "from" address: ${e.from} must be a valid string.`);if(!e.data||"string"!=typeof e.data)throw new Error(`Invalid message "data": ${e.data} must be a valid array.`);let t;try{t=JSON.parse(e.data)}catch(e){throw new Error("Data must be passed as a valid JSON string.")}if((0,l.validate)(t,u.TYPED_MESSAGE_SCHEMA).errors.length>0)throw new Error("Data must conform to EIP-712 schema. See https://git.io/fNtcx.")},r.validateTokenToWatch=function(e){const{address:t,symbol:r,decimals:n}=e;if(!t||!r||void 0===n)throw a.ethErrors.rpc.invalidParams("Must specify address, symbol, and decimals.");if("string"!=typeof r)throw a.ethErrors.rpc.invalidParams("Invalid symbol: not a string.");if(r.length>11)throw a.ethErrors.rpc.invalidParams(`Invalid symbol "${r}": longer than 11 characters.`);const i=parseInt(n,10);if(isNaN(i)||i>36||i<0)throw a.ethErrors.rpc.invalidParams(`Invalid decimals "${n}": must be 0 <= 36.`);if(!w(t))throw a.ethErrors.rpc.invalidParams(`Invalid address "${t}".`)},r.isSmartContractCode=function(e){return!!e&&("0x"!==e&&"0x0"!==e)},r.successfulFetch=b,r.handleFetch=P,r.fetchWithErrorHandling=function({url:e,options:t,timeout:r,errorCodesToCatch:i}){return n(this,void 0,void 0,(function*(){let n;try{n=r?Promise.race([yield P(e,t),new Promise(((e,t)=>setTimeout((()=>{t(p)}),r)))]):yield P(e,t)}catch(e){!function(e,t=[]){var r;if(!e)return;const n=t.some((t=>{var r;return null===(r=e.message)||void 0===r?void 0:r.includes(`Fetch failed with status '${t}'`)}));if(!(e instanceof Error&&(n||(null===(r=e.message)||void 0===r?void 0:r.includes("Failed to fetch"))||e===p)))throw e;console.error(e)}(e,i)}return n}))},r.timeoutFetch=function(e,t,r=500){return n(this,void 0,void 0,(function*(){return Promise.race([b(e,t),new Promise(((e,t)=>setTimeout((()=>{t(p)}),r)))])}))},r.normalizeEnsName=function(e){if(e&&"string"==typeof e)try{const t=c.default.normalize(e.trim());if(t.match(/^(([\w\d-]+)\.)*[\w\d-]{7,}\.(eth|test)$/u))return t}catch(e){}return null},r.query=function(e,t,r=[]){return new Promise(((n,i)=>{const s=(e,t)=>{e?i(e):n(t)};"function"==typeof e[t]?e[t](...r,s):e.sendAsync({method:t,params:r},s)}))};r.isEIP1559Transaction=e=>{const t=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);return t(e,"maxFeePerGas")&&t(e,"maxPriorityFeePerGas")};r.convertHexToDecimal=e=>parseInt(e===undefined?"0x0":e,16);r.getIncreasedPriceHex=(e,t)=>(0,s.addHexPrefix)(`${parseInt(""+e*t,10).toString(16)}`);r.getIncreasedPriceFromExisting=(e,t)=>(0,r.getIncreasedPriceHex)((0,r.convertHexToDecimal)(e),t);r.validateGasValues=e=>{Object.keys(e).forEach((t=>{const r=e[t];if("string"!=typeof r||!(0,s.isHexString)(r))throw new TypeError(`expected hex string for ${t} but received: ${r}`)}))};r.isFeeMarketEIP1559Values=e=>(null==e?void 0:e.maxFeePerGas)!==undefined||(null==e?void 0:e.maxPriorityFeePerGas)!==undefined;function E(e){if(e.startsWith("ipfs://ipfs/"))return e.replace("ipfs://ipfs/","");if(e.startsWith("ipfs://"))return e.replace("ipfs://","");throw new Error("this method should not be used with non ipfs urls")}function k(e){const t=E(e),r=t.indexOf("/"),n=-1!==r?t.substring(0,r):t,i=-1!==r?t.substring(r):undefined;return{cid:d.CID.parse(n).toV1().toString(),path:i}}function _(e){return e.match(/(^http:\/\/)|(^https:\/\/)/u)?e:`https://${e}`}r.isGasPriceValue=e=>(null==e?void 0:e.gasPrice)!==undefined,r.validateMinimumIncrease=function(e,t){const n=(0,r.convertHexToDecimal)(e),i=(0,r.convertHexToDecimal)(t);if(n>=i)return e;throw new Error(`The proposed value: ${n} should meet or exceed the minimum value: ${i}`)},r.removeIpfsProtocolPrefix=E,r.getIpfsCIDv1AndPath=k,r.addUrlProtocolPrefix=_,r.getFormattedIpfsUrl=function(e,t,r){const{host:n,protocol:i,origin:s}=new URL(_(e));if(r){const{cid:e,path:r}=k(t);return`${i}//${e}.ipfs.${n}${null!=r?r:""}`}return`${s}/ipfs/${E(t)}`},r.isPlainObject=function(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)};var M;r.hasProperty=(e,t)=>Reflect.hasOwnProperty.call(e,t),r.isNonEmptyArray=function(e){return Array.isArray(e)&&e.length>0},r.isValidJson=function(e){try{return(0,h.default)(e,JSON.parse(JSON.stringify(e)))}catch(e){return!1}},function(e){e.mainnet="1",e.bsc="56",e.polygon="137",e.avax="43114"}(M=r.SupportedTokenDetectionNetworks||(r.SupportedTokenDetectionNetworks={})),r.isTokenDetectionSupportedForNetwork=function(e){return Object.values(M).includes(e)}}).call(this)}).call(this,e("buffer").Buffer)}}},{package:"@metamask/snap-controllers>@metamask/controllers"}],[149,{"../../../shared/constants/hardware-wallets":6264,"@babel/runtime/helpers/defineProperty":194,"@babel/runtime/helpers/interopRequireDefault":200,lodash:5255},function(){with(this)return function(){"use strict";return function(e,t,r){var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var i=n(e("@babel/runtime/helpers/defineProperty")),s=e("lodash"),o=e("../../../shared/constants/hardware-wallets");function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t{const t=this._children[e];this._addChild(e,t)}))}_addChild(e,t){const r=t=>{const r=this.getState();r[e]=t,this.putState(r)};t.subscribe(r),r(t.getState())}}r.ComposedStore=i}}},{package:"@metamask/snap-controllers>@metamask/obs-store"}],[1491,{"./ObservableStore":1492},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.MergedStore=void 0;const n=e("./ObservableStore");class i extends n.ObservableStore{constructor(e=[]){super({}),this._children=e,e.forEach((e=>this._addChild(e))),this._updateWholeState()}_addChild(e){e.subscribe((()=>this._updateWholeState()))}_updateWholeState(){const e=this._children.map((e=>e.getState())),t=Object.assign({},...e);this.putState(t)}}r.MergedStore=i}}},{package:"@metamask/snap-controllers>@metamask/obs-store"}],[1492,{"@metamask/safe-event-emitter":1319},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.ObservableStore=void 0;const i=n(e("@metamask/safe-event-emitter"));class s extends i.default{constructor(e){super(),this._state=e||{}}getState(){return this._getState()}putState(e){this._putState(e),this.emit("update",e)}updateState(e){if(e&&"object"==typeof e){const t=this.getState();this.putState(Object.assign(Object.assign({},t),e))}else this.putState(e)}subscribe(e){this.on("update",e)}unsubscribe(e){this.removeListener("update",e)}_getState(){return this._state}_putState(e){this._state=e}}r.ObservableStore=s}}},{package:"@metamask/snap-controllers>@metamask/obs-store"}],[1493,{stream:2178},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.storeAsStream=void 0;const n=e("stream");class i extends n.Duplex{constructor(e){super({objectMode:!0}),this.resume(),this.handler=e=>this.push(e),this.obsStore=e,this.obsStore.subscribe(this.handler)}pipe(e,t){const r=super.pipe(e,t);return e.write(this.obsStore.getState()),r}_write(e,t,r){this.obsStore.putState(e),r()}_read(e){return undefined}_destroy(e,t){this.obsStore.unsubscribe(this.handler),super._destroy(e,t)}}r.storeAsStream=function(e){return new i(e)}}}},{package:"@metamask/snap-controllers>@metamask/obs-store"}],[1494,{"./ComposedStore":1490,"./MergedStore":1491,"./ObservableStore":1492,"./asStream":1493,"./transform":1495},function(){with(this)return function(){"use strict";return function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){n===undefined&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){n===undefined&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e("./asStream"),r),i(e("./ComposedStore"),r),i(e("./MergedStore"),r),i(e("./ObservableStore"),r),i(e("./transform"),r)}}},{package:"@metamask/snap-controllers>@metamask/obs-store"}],[1495,{through2:1540},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.storeTransformStream=void 0;const n=e("through2");r.storeTransformStream=function(e){return n.obj(((t,r,n)=>{try{return n(null,e(t)),undefined}catch(e){return n(e),undefined}}))}}}},{package:"@metamask/snap-controllers>@metamask/obs-store"}],[1496,{"fast-deep-equal":4384},function(){with(this)return function(){"use strict";return function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});const n=e("fast-deep-equal");n.code='require("ajv/dist/runtime/equal").default',r.default=n}}},{package:"@metamask/snap-controllers>ajv"}],[1497,{},function(){with(this)return function(){"use strict";return function(e,t,r){function n(e){const t=e.length;let r,n=0,i=0;for(;i=55296&&r<=56319&&iajv"}],[1498,{},function(){with(this)return function(){"use strict";return function(e,t,r){!function(t,r){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function s(e,t,r){if(s.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var o;"object"==typeof t?t.exports=s:r.BN=s,s.BN=s,s.wordSize=26;try{o=e("buf"+"fer").Buffer}catch(e){}function a(e,t,r){for(var n=0,i=Math.min(e.length,r),s=t;s=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function c(e,t,r,n){for(var i=0,s=Math.min(e.length,r),o=t;o=49?a-49+10:a>=17?a-17+10:a}return i}s.isBN=function(e){return e instanceof s||null!==e&&"object"==typeof e&&e.constructor.wordSize===s.wordSize&&Array.isArray(e.words)},s.max=function(e,t){return e.cmp(t)>0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},s.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},s.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)o=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[s]|=o<>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(i=0,s=0;i>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this.strip()},s.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=a(e,r,r+6),this.words[n]|=i<>>26-s&4194303,(s+=24)>=26&&(s-=26,n++);r+6!==t&&(i=a(e,t,r+6),this.words[n]|=i<>>26-s&4194303),this.strip()},s.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var s=e.length-r,o=s%n,a=Math.min(s,s-o)+r,u=0,l=r;l1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},s.prototype.inspect=function(){return(this.red?"