@magic-sdk/provider 28.0.2 → 28.0.3-canary.26f7932.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -2,5 +2,5 @@
2
2
  - Extension \`${e.name}\` supports version(s) \`${r}\``:r||(t+=`
3
3
  - Extension \`${e.name}\` does not support ${m.platform} environments.`)}),new S(C.SDKErrorCode.IncompatibleExtensions,t)}function je(n){let t=e=>{let r=e+1,o=r%10,s=r%100;return o===1&&s!==11?`${r}st`:o===2&&s!==12?`${r}nd`:o===3&&s!==13?`${r}rd`:`${r}th`};return new S(C.SDKErrorCode.InvalidArgument,`Invalid ${t(n.argument)} argument given to \`${n.procedure}\`.
4
4
  Expected: \`${n.expected}\`
5
- Received: \`${n.received}\``)}function Fn(){return new D(C.SDKWarningCode.DuplicateIframe,"Duplicate iframes found.")}function Be(){return new D(C.SDKWarningCode.SyncWeb3Method,"Non-async web3 methods are deprecated in web3 > 1.0 and are not supported by the Magic web3 provider. Please use an async method instead.")}function He(){return new D(C.SDKWarningCode.ReactNativeEndpointConfiguration,`CUSTOM DOMAINS ARE NOT SUPPORTED WHEN USING MAGIC SDK WITH REACT NATIVE! The \`endpoint\` parameter SHOULD NOT be provided. The Magic \`<iframe>\` is automatically wrapped by a WebView pointed at \`${m.defaultEndpoint}\`. Changing this default behavior will lead to unexpected results and potentially security-threatening bugs.`)}function W(n){let{method:t,removalVersions:e,useInstead:r}=n,o=e[m.sdkName],s=r?` Use \`${r}\` instead.`:"",a=`\`${t}\` will be removed from \`${m.sdkName}\` in version \`${o}\`.${s}`;return new D(C.SDKWarningCode.DeprecationNotice,a)}var h=require("@magic-sdk/types");var Z=require("@magic-sdk/types");function*Jn(){let n=0;for(;;)n<Number.MAX_SAFE_INTEGER?yield++n:n=0}var Gn=Jn();function Re(){return Gn.next().value}var Pt=Symbol("Payload pre-processed by Magic SDK");function Mt(n){return Object.defineProperty(n,Pt,{value:!0,enumerable:!1}),n}function Kn(n){return!!n[Pt]}function j(n){var t,e,r;return Kn(n)||(n.jsonrpc=(t=n.jsonrpc)!=null?t:"2.0",n.id=Re(),n.method=(e=n.method)!=null?e:"noop",n.params=(r=n.params)!=null?r:[],Mt(n)),n}function d(n,t=[]){return Mt({params:t,method:n,jsonrpc:"2.0",id:Re()})}var F=class{constructor(t){t instanceof F?(this._jsonrpc=t.payload.jsonrpc,this._id=t.payload.id,this._result=t.payload.result,this._error=t.payload.error):De(t)?(this._jsonrpc=t.jsonrpc,this._id=t.id,this._result=t.result,this._error=t.error):(this._jsonrpc=t.jsonrpc,this._id=t.id,this._result=void 0,this._error=void 0)}applyError(t){return this._error=t,this}applyResult(t){return this._result=t,this}get hasError(){return typeof this._error!="undefined"&&this._error!==null}get hasResult(){return typeof this._result!="undefined"}get payload(){return{jsonrpc:this._jsonrpc,id:this._id,result:this._result,error:this._error}}};var $t=Xt(Nt()),Te=class extends $t.default{};function le(){let n=new Te;return{emitter:n,createChainingEmitterMethod:(r,o)=>(...s)=>(n[r].apply(n,s),o),createBoundEmitterMethod:r=>(...o)=>n[r].apply(n,o)}}var Ct=Symbol("isPromiEvent");function Xe(n){return!!n[Ct]}function O(n){let t=Ie(n),{createBoundEmitterMethod:e,createChainingEmitterMethod:r}=le(),o=Symbol("Promise.then"),s=Symbol("Promise.catch"),a=Symbol("Promise.finally"),i=(l,p)=>(...$)=>{let I=p[l].apply(p,$);return c(I)},c=l=>Object.assign(l,{[Ct]:!0,[o]:l[o]||l.then,[s]:l[s]||l.catch,[a]:l[a]||l.finally,then:i(o,l),catch:i(s,l),finally:i(a,l),on:r("on",l),once:r("once",l),addListener:r("addListener",l),off:r("off",l),removeListener:r("removeListener",l),removeAllListeners:r("removeAllListeners",l),emit:e("emit"),eventNames:e("eventNames"),listeners:e("listeners"),listenerCount:e("listenerCount")}),u=c(t.then(l=>(u.emit("done",l),u.emit("settled"),l),l=>{throw u.emit("error",l),u.emit("settled"),l}));return u}function Ie(n){return new Promise((t,e)=>{let r=n(t,e);Promise.resolve(r).catch(e)})}var x=class{constructor(t){this.sdk=t}get overlay(){return this.sdk.overlay}request(t){let e=this.overlay.post(Z.MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST,j(t)),r=O((s,a)=>{e.then(i=>{if(o(),i.hasError)a(new L(i.payload.error));else if(i.hasResult)s(i.payload.result);else throw Je()}).catch(i=>{o(),a(i)})}),o=this.overlay.on(Z.MagicIncomingWindowMessage.MAGIC_HANDLE_EVENT,s=>{var i;let{response:a}=s.data;if(a.id===t.id&&((i=a.result)==null?void 0:i.event)){let{event:c,params:u=[]}=a.result;r.emit(c,...u)}});return r}createIntermediaryEvent(t,e){return o=>{let s=d(Z.MagicPayloadMethod.IntermediaryEvent,[{payloadId:e,eventType:t,args:o}]);this.request(s)}}};function ze(n,t){let[e]=n.split(".").map(Number);return e>=t}var B={"magic-sdk":"v18.0.0","@magic-sdk/react-native":"v14.0.0","@magic-sdk/react-native-bare":"v19.0.0","@magic-sdk/react-native-expo":"v19.0.0"},be=class extends x{loginWithMagicLink(t){let e=m.sdkName==="@magic-sdk/react-native"||m.sdkName==="@magic-sdk/react-native-bare"||m.sdkName==="@magic-sdk/react-native-expo";if(e&&ze(m.version,19))throw new Error("loginWithMagicLink() is deprecated for this package, please utlize a passcode method like loginWithSMS or loginWithEmailOTP instead.");e&&W({method:"auth.loginWithMagicLink()",removalVersions:B,useInstead:"auth.loginWithEmailOTP()"}).log();let{email:r,showUI:o=!0,redirectURI:s,overrides:a}=t,i=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithMagicLinkTestMode:h.MagicPayloadMethod.LoginWithMagicLink,[{email:r,showUI:o,redirectURI:s,overrides:a}]);return this.request(i)}loginWithSMS(t){let{phoneNumber:e}=t,r=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithSmsTestMode:h.MagicPayloadMethod.LoginWithSms,[{phoneNumber:e,showUI:!0}]);return this.request(r)}loginWithEmailOTP(t){let{email:e,showUI:r,deviceCheckUI:o,overrides:s}=t,a=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithEmailOTPTestMode:h.MagicPayloadMethod.LoginWithEmailOTP,[{email:e,showUI:r,deviceCheckUI:o,overrides:s}]),i=this.request(a);return!o&&i&&i.on(h.DeviceVerificationEventEmit.Retry,()=>{this.createIntermediaryEvent(h.DeviceVerificationEventEmit.Retry,a.id)()}),!r&&i&&(i.on(h.LoginWithEmailOTPEventEmit.VerifyEmailOtp,c=>{this.createIntermediaryEvent(h.LoginWithEmailOTPEventEmit.VerifyEmailOtp,a.id)(c)}),i.on(h.LoginWithEmailOTPEventEmit.Cancel,()=>{this.createIntermediaryEvent(h.LoginWithEmailOTPEventEmit.Cancel,a.id)()})),i}loginWithCredential(t){let e=t!=null?t:"";if(!t&&m.platform==="web"){e=window.location.search;let o=window.location.origin+window.location.pathname;window.history.replaceState(null,"",o)}let r=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithCredentialTestMode:h.MagicPayloadMethod.LoginWithCredential,[e]);return this.request(r)}setAuthorizationToken(t){let e=d(h.MagicPayloadMethod.SetAuthorizationToken,[{jwt:t}]);return this.request(e)}updateEmailWithUI(t){let{email:e,showUI:r=!0}=t,o=d(this.sdk.testMode?h.MagicPayloadMethod.UpdateEmailTestMode:h.MagicPayloadMethod.UpdateEmail,[{email:e,showUI:r}]),s=this.request(o);return r||(s.on(h.RecencyCheckEventEmit.Retry,()=>{this.createIntermediaryEvent(h.RecencyCheckEventEmit.Retry,o.id)()}),s.on(h.RecencyCheckEventEmit.Cancel,()=>{this.createIntermediaryEvent(h.RecencyCheckEventEmit.Cancel,o.id)()}),s.on(h.RecencyCheckEventEmit.VerifyEmailOtp,a=>{this.createIntermediaryEvent(h.RecencyCheckEventEmit.VerifyEmailOtp,o.id)(a)}),s.on(h.UpdateEmailEventEmit.RetryWithNewEmail,a=>{this.createIntermediaryEvent(h.UpdateEmailEventEmit.RetryWithNewEmail,o.id)(a)}),s.on(h.UpdateEmailEventEmit.Cancel,()=>{this.createIntermediaryEvent(h.UpdateEmailEventEmit.Cancel,o.id)()}),s.on(h.UpdateEmailEventEmit.VerifyEmailOtp,a=>{this.createIntermediaryEvent(h.UpdateEmailEventEmit.VerifyEmailOtp,o.id)(a)})),s}};var v=require("@magic-sdk/types");var Q={};lt(Q,{clear:()=>Hn,getItem:()=>R,iterate:()=>Ye,key:()=>Xn,keys:()=>zn,length:()=>Vn,removeItem:()=>A,setItem:()=>N});var we;function J(n){return(...t)=>f(this,null,function*(){return we||(we=yield m.configureStorage()),yield we.ready(),we[n](...t)})}var R=J("getItem"),N=J("setItem"),A=J("removeItem"),Hn=J("clear"),Vn=J("length"),Xn=J("key"),zn=J("keys"),Ye=J("iterate");function Ze(){let n=window.crypto.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&191|128;let t="";return t+=n[0].toString(16),t+=n[1].toString(16),t+=n[2].toString(16),t+=n[3].toString(16),t+="-",t+=n[4].toString(16),t+=n[5].toString(16),t+="-",t+=n[6].toString(16),t+=n[7].toString(16),t+="-",t+=n[8].toString(16),t+=n[9].toString(16),t+="-",t+=n[10].toString(16),t+=n[11].toString(16),t+=n[12].toString(16),t+=n[13].toString(16),t+=n[14].toString(16),t+=n[15].toString(16),t}var Pe="STORE_KEY_PRIVATE_KEY",ue="STORE_KEY_PUBLIC_JWK",St="ECDSA",Yn="P-256",Zn={name:St,namedCurve:Yn};function ee(){let n=typeof window!="undefined"&&!!window.crypto,t=n&&!!window.crypto.subtle;return n&&t}function Qn(){A(ue),A(Pe)}function Qe(){return f(this,null,function*(){let n=yield er();if(!n){console.info("unable to create public key or webcrypto is unsupported");return}let{subtle:t}=window.crypto,e=yield R(Pe);if(!e||!t){console.info("unable to find private key or webcrypto unsupported");return}let r={iat:Math.floor(new Date().getTime()/1e3),jti:Ze()},o={typ:"dpop+jwt",alg:"ES256",jwk:n},s={protected:At(JSON.stringify(o)),claims:At(JSON.stringify(r))},a=nr(`${s.protected}.${s.claims}`),i={name:St,hash:{name:"SHA-256"}},c=sr(new Uint8Array(yield t.sign(i,e,a)));return`${s.protected}.${s.claims}.${c}`})}function er(){return f(this,null,function*(){if(!ee()){console.info("webcrypto is not supported");return}return(yield R(ue))||(yield tr()),R(ue)})}function tr(){return f(this,null,function*(){let{subtle:n}=window.crypto,t=yield n.generateKey(Zn,!1,["sign"]),e=yield n.exportKey("jwk",t.publicKey);yield N(Pe,t.privateKey),yield N(ue,e)})}function At(n){return Lt(rr(n))}function nr(n){return new TextEncoder().encode(n)}function Lt(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function rr(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,(e,r)=>String.fromCharCode(parseInt(r,16)))}function sr(n){let t="";return n.forEach(e=>{t+=String.fromCharCode(e)}),Lt(t)}var et="ds",tt="ek",nt="iv",rt="AES-GCM",or=256;function te(){return f(this,null,function*(){let n=[];yield Ye((t,e,r)=>{e.startsWith(`${et}_`)&&n.push(e)});for(let t of n)yield A(t)})}function Ot(n){let t="",e=new Uint8Array(n),r=e.byteLength;for(let o=0;o<r;o++)t+=String.fromCharCode(e[o]);return window.btoa(t)}function _t(n){let t=window.atob(n),e=t.length,r=new Uint8Array(e);for(let o=0;o<e;o++)r[o]=t.charCodeAt(o);return r.buffer}function ir(){return f(this,null,function*(){if(!ee()){console.info("webcrypto is not supported");return}let{crypto:n}=window,t=yield R(nt);return t||n.getRandomValues(new Uint8Array(12))})}function ar(){return f(this,null,function*(){if(!ee()){console.info("webcrypto is not supported");return}let{subtle:n}=window.crypto,t=yield R(tt);return t||(yield n.generateKey({name:rt,length:or},!1,["encrypt","decrypt"]))})}function kt(n,t){return f(this,null,function*(){let e=yield ir(),r=yield ar();if(!e||!r||!n)return;let o=_t(n),{subtle:s}=window.crypto,a=yield s.encrypt({name:rt,iv:e},r,o),i=Ot(a);yield N(`${et}_${t}`,i),yield N(tt,r),yield N(nt,e)})}function qt(n){return f(this,null,function*(){let t=yield R(`${et}_${n}`),e=yield R(nt),r=yield R(tt);if(!e||!t||!r||!ee())return;let{subtle:o}=window.crypto,s=yield o.decrypt({name:rt,iv:e},r,_t(t));return Ot(s)})}function Me(n,t){return t?new URL(n,t):new URL(n)}var xe=class extends x{constructor(){super(...arguments);this.localForageKey="mc_active_wallet";this.localForageIsLoggedInKey="magic_auth_is_logged_in";this.userLoggedOutCallbacks=[]}getIdToken(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.GetIdTokenTestMode:v.MagicPayloadMethod.GetIdToken,[e]);return this.request(r)}generateIdToken(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.GenerateIdTokenTestMode:v.MagicPayloadMethod.GenerateIdToken,[e]);return this.request(r)}getInfo(){return f(this,null,function*(){let e=yield R(this.localForageKey),r=d(v.MagicPayloadMethod.GetInfo,[{walletType:e}]);return this.request(r)})}isLoggedIn(){return O((e,r)=>f(this,null,function*(){try{let o=!1;this.sdk.useStorageCache&&(o=(yield R(this.localForageIsLoggedInKey))==="true",o&&e(!0));let s=d(this.sdk.testMode?v.MagicPayloadMethod.IsLoggedInTestMode:v.MagicPayloadMethod.IsLoggedIn),a=yield this.request(s);this.sdk.useStorageCache&&(a?N(this.localForageIsLoggedInKey,!0):A(this.localForageIsLoggedInKey),o&&!a&&this.emitUserLoggedOut(!0)),e(a)}catch(o){r(o)}}))}logout(){return A(this.localForageKey),A(this.localForageIsLoggedInKey),te(),O((e,r)=>f(this,null,function*(){try{let o=d(this.sdk.testMode?v.MagicPayloadMethod.LogoutTestMode:v.MagicPayloadMethod.Logout),s=yield this.request(o);this.sdk.useStorageCache&&this.emitUserLoggedOut(s),e(s)}catch(o){r(o)}}))}requestInfoWithUI(e){let r=d(v.MagicPayloadMethod.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}showSettings(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.UserSettingsTestMode:v.MagicPayloadMethod.UserSettings,[e]);return this.request(r)}recoverAccount(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.RecoverAccountTestMode:v.MagicPayloadMethod.RecoverAccount,[e]);return this.request(r)}revealPrivateKey(){let e=d(v.MagicPayloadMethod.RevealPK);return this.request(e)}getMetadata(){W({method:"user.getMetadata()",removalVersions:B,useInstead:"user.getInfo()"}).log();let e=d(this.sdk.testMode?v.MagicPayloadMethod.GetMetadataTestMode:v.MagicPayloadMethod.GetMetadata);return this.request(e)}onUserLoggedOut(e){this.userLoggedOutCallbacks.push(e)}emitUserLoggedOut(e){this.userLoggedOutCallbacks.forEach(r=>{r(e)})}};var y=require("@magic-sdk/types");var Ne=class extends x{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}connectWithUI(){let e=O((r,o)=>f(this,null,function*(){try{if(this.isMetaMaskBrowser()&&(yield this.isWalletEnabled(y.Wallets.MetaMask))){let u=yield this.autoConnectIfWalletBrowser(y.Wallets.MetaMask);r(u);return}if(this.isCoinbaseWalletBrowser()&&(yield this.isWalletEnabled(y.Wallets.CoinbaseWallet))){let u=yield this.autoConnectIfWalletBrowser(y.Wallets.CoinbaseWallet);r(u);return}let s=this.getUserEnv(),a=d(y.MagicPayloadMethod.Login,[s]),i=this.request(a);i.on(y.Events.WalletSelected,u=>this.handleWalletSelected(V(H({},u),{payloadId:a.id}))),i.on("id-token-created",u=>{e.emit("id-token-created",u)});let c=yield i;c.error&&o(c),r(c)}catch(s){o(s)}}));return e}showUI(){return this.request(d(y.MagicPayloadMethod.ShowUI))}showAddress(){return this.request(d(y.MagicPayloadMethod.ShowAddress))}showSendTokensUI(){return this.request(d(y.MagicPayloadMethod.ShowSendTokensUI))}showOnRamp(){return this.request(d(y.MagicPayloadMethod.ShowOnRamp))}showNFTs(){return this.request(d(y.MagicPayloadMethod.ShowNFTs))}showBalances(){return this.request(d(y.MagicPayloadMethod.ShowBalances))}sendGaslessTransaction(e,r){return this.request(d(y.MagicPayloadMethod.SendGaslessTransaction,[e,r]))}getInfo(){return f(this,null,function*(){W({method:"wallet.getInfo()",removalVersions:B,useInstead:"user.getInfo()"}).log();let e=yield R(this.localForageKey),r=d(y.MagicPayloadMethod.GetInfo,[{walletType:e}]);return this.request(r)})}disconnect(){W({method:"wallet.disconnect()",removalVersions:B,useInstead:"user.logout()"}).log(),A(this.localForageKey),te();let e=d(y.MagicPayloadMethod.Disconnect);return this.request(e)}requestUserInfoWithUI(e){W({method:"wallet.requestUserInfoWithUI()",removalVersions:B,useInstead:"user.requestUserInfoWithUI()"}).log();let r=d(y.MagicPayloadMethod.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}getProvider(){return f(this,null,function*(){switch(yield R(this.localForageKey)){case y.Wallets.MetaMask:return this.getMetaMaskProvider();case y.Wallets.CoinbaseWallet:return this.getCoinbaseProvider();default:return this.sdk.rpcProvider}})}isMetaMaskInstalled(){var e,r,o;return((e=window.ethereum)==null?void 0:e.isMetaMask)||!!((o=(r=window.ethereum)==null?void 0:r.providers)!=null&&o.find(s=>s==null?void 0:s.isMetaMask))}isMetaMaskBrowser(){return this.isMobile()&&this.isMetaMaskInstalled()}getMetaMaskProvider(){var e,r;return((r=(e=window.ethereum)==null?void 0:e.providers)==null?void 0:r.find(o=>o==null?void 0:o.isMetaMask))||window.ethereum}connectToMetaMask(){if(this.isMobile()&&!this.isMetaMaskInstalled()){let e=`https://metamask.app.link/dapp/${window.location.href.replace(/(^\w+:|^)\/\//,"")}`;window.location.href=e}return this.getMetaMaskProvider().request({method:"eth_requestAccounts"})}isCoinbaseWalletInstalled(){var e,r,o;return((e=window.ethereum)==null?void 0:e.isCoinbaseWallet)||!!((o=(r=window.ethereum)==null?void 0:r.providers)!=null&&o.find(s=>s==null?void 0:s.isCoinbaseWallet))}isCoinbaseWalletBrowser(){var e;return!!((e=window.ethereum)!=null&&e.isCoinbaseBrowser)}getCoinbaseProvider(){var e,r;return((r=(e=window.ethereum)==null?void 0:e.providers)==null?void 0:r.find(o=>o==null?void 0:o.isCoinbaseWallet))||window.ethereum}connectToCoinbaseWallet(){if(this.isMobile()&&!this.isCoinbaseWalletBrowser()){let r=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(window.location.href)}`;window.location.href=r}return this.getCoinbaseProvider().request({method:"eth_requestAccounts"})}isMobile(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Silk|Opera Mini/i.test(navigator.userAgent)}getUserEnv(){return{env:{isMetaMaskInstalled:this.isMetaMaskInstalled(),isCoinbaseWalletInstalled:this.isCoinbaseWalletInstalled()}}}connectToThirdPartyWallet(e){switch(e){case y.Wallets.MetaMask:return this.connectToMetaMask();case y.Wallets.CoinbaseWallet:return this.connectToCoinbaseWallet();default:throw new Error(`Invalid provider: ${e}. Must be one of "metamask" or "coinbase_wallet".`)}}isWalletEnabled(e){let r=d("mc_is_wallet_enabled",[{wallet:e}]);return this.request(r)}handleWalletSelected(e){return f(this,null,function*(){try{let r=yield this.connectToThirdPartyWallet(e.wallet);yield N(this.localForageKey,e.wallet),this.createIntermediaryEvent(y.Events.WalletConnected,e.payloadId)(r)}catch(r){console.error(r),this.createIntermediaryEvent(y.Events.WalletRejected,e.payloadId)()}})}autoConnectIfWalletBrowser(e){return f(this,null,function*(){let r;e===y.Wallets.MetaMask&&(r=yield this.getMetaMaskProvider().request({method:"eth_requestAccounts"})),e===y.Wallets.CoinbaseWallet&&(r=yield this.getCoinbaseProvider().request({method:"eth_requestAccounts"})),yield N(this.localForageKey,e);let o=d(y.MagicPayloadMethod.AutoConnect,[{wallet:e,address:r}]);return this.request(o)})}};var de=require("@magic-sdk/types");var{createBoundEmitterMethod:$e,createChainingEmitterMethod:ne}=le(),Ce=class extends x{constructor(){super(...arguments);this.isMagic=!0;this.on=ne("on",this);this.once=ne("once",this);this.addListener=ne("addListener",this);this.off=ne("off",this);this.removeListener=ne("removeListener",this);this.removeAllListeners=ne("removeAllListeners",this);this.emit=$e("emit");this.eventNames=$e("eventNames");this.listeners=$e("listeners");this.listenerCount=$e("listenerCount")}sendAsync(e,r){if(!r)throw je({procedure:"Magic.rpcProvider.sendAsync",argument:1,expected:"function",received:r===null?"null":typeof r});if(Array.isArray(e))this.overlay.post(de.MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST,e.map(o=>{let s=j(o);return this.prefixPayloadMethodForTestMode(s),s})).then(o=>{r(null,o.map(s=>V(H({},s.payload),{error:s.hasError?new L(s.payload.error):null})))});else{let o=j(e);this.prefixPayloadMethodForTestMode(o),this.overlay.post(de.MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST,o).then(s=>{r(s.hasError?new L(s.payload.error):null,s.payload)})}}send(e,r){if(typeof e=="string"){let s=d(e,Array.isArray(r)?r:[]);return this.request(s)}if(Array.isArray(e)||!!r){this.sendAsync(e,r);return}let o=Be();return o.log(),new F(e).applyError({code:-32603,message:o.rawMessage}).payload}enable(){let e=d(de.MagicPayloadMethod.Login);return this.request(e)}request(e){return this.prefixPayloadMethodForTestMode(e),super.request(e)}prefixPayloadMethodForTestMode(e){let r="testMode/eth/";this.sdk.testMode&&(e.method=`${r}${e.method}`)}};var Dt=["request","overlay","sdk"];function cr(n){let t=Object.getPrototypeOf(n),e=[t];for(;t!==x.prototype;)t=Object.getPrototypeOf(t),e.push(t);return e}var Ae=class extends x{constructor(){super(void 0);this.__sdk_access_field_descriptors__=new Map;this.__is_initialized__=!1;this.utils={createPromiEvent:O,isPromiEvent:Xe,encodeJSON:ae,decodeJSON:qe,createJsonRpcRequestPayload:d,standardizeJsonRpcRequestPayload:j,storage:Q};let e=[this,...cr(this)];Dt.forEach(r=>{let o=e.map(c=>Object.getOwnPropertyDescriptor(c,r)),s=o.findIndex(c=>!!c),a=s>0,i=o[s];i&&(this.__sdk_access_field_descriptors__.set(r,{descriptor:i,isPrototypeField:a}),Object.defineProperty(this,r,{configurable:!0,get:()=>{throw Ge(r)}}))})}init(e){this.__is_initialized__||(Dt.forEach(r=>{if(this.__sdk_access_field_descriptors__.has(r)){let{descriptor:o,isPrototypeField:s}=this.__sdk_access_field_descriptors__.get(r);s?delete this[r]:Object.defineProperty(this,r,o)}}),this.sdk=e,this.__is_initialized__=!0)}createDeprecationWarning(e){let{method:r,removalVersion:o,useInstead:s}=e,a=s?` Use \`${s}\` instead.`:"",i=`\`${r}\` will be removed from this Extension in version \`${o}\`.${a}`;return new Y(this,"DEPRECATION_NOTICE",i)}createWarning(e,r){return new Y(this,e,r)}createError(e,r,o){return new K(this,e,r,o)}},st=class extends Ae{},_=class extends Ae{};_.Internal=st,_.Anonymous="anonymous extension";var Se=require("@magic-sdk/types");var Le=class extends x{purchase(t){let e=d(Se.MagicPayloadMethod.NFTPurchase,[t]);return this.request(e)}checkout(t){let e=d(Se.MagicPayloadMethod.NFTCheckout,[t]);return this.request(e)}transfer(t){let e=d(Se.MagicPayloadMethod.NFTTransfer,[t]);return this.request(e)}};function Wt(n){return n.compat&&n.compat[m.sdkName]!=null?typeof n.compat[m.sdkName]=="string"?Tt(It(m.version),n.compat[m.sdkName]):!!n.compat[m.sdkName]:!0}function lr(n,t,e){return!t&&!e?`${n}_eth_mainnet`:e?`${n}_${JSON.stringify(e)}`:t?typeof t=="string"?`${n}_eth_${t}`:`${n}_${t.rpcUrl}_${t.chainId}_${t.chainType}`:`${n}_unknown`}function ur(n){var o;let t=(o=n==null?void 0:n.extensions)!=null?o:[],e={},r=[];if(Array.isArray(t)?t.forEach(s=>{Wt(s)?(s.init(this),(s.name||s.name!==_.Anonymous)&&(this[s.name]=s),s instanceof _.Internal&&(z(s.config)||(e[s.name]=s.config))):r.push(s)}):Object.keys(t).forEach(s=>{if(Wt(t[s])){t[s].init(this);let a=t[s];this[s]=a,a instanceof _.Internal&&(z(a.config)||(e[t[s].name]=a.config))}else r.push(t[s])}),r.length)throw Ke(r);return e}var he=class{constructor(t,e){this.apiKey=t;var a;if(!t)throw Ue();m.platform==="react-native"&&(e==null?void 0:e.endpoint)&&He().log();let{defaultEndpoint:r,version:o}=m;this.testMode=!!(e!=null&&e.testMode),this.useStorageCache=!!(e!=null&&e.useStorageCache),this.endpoint=Me((a=e==null?void 0:e.endpoint)!=null?a:r).origin,this.auth=new be(this),this.user=new xe(this),this.wallet=new Ne(this),this.nft=new Le(this),this.rpcProvider=new Ce(this);let s=ur.call(this,e);this.parameters=ae(V(H({API_KEY:this.apiKey,DOMAIN_ORIGIN:window.location?window.location.origin:"",ETH_NETWORK:e==null?void 0:e.network,host:Me(this.endpoint).host,sdk:wt[m.sdkName],version:o,ext:z(s)?void 0:s,locale:(e==null?void 0:e.locale)||"en_US"},m.bundleId?{bundleId:m.bundleId}:{}),{meta:e==null?void 0:e.meta})),this.networkHash=lr(this.apiKey,e==null?void 0:e.network,z(s)?void 0:s),e!=null&&e.deferPreload||this.preload()}get overlay(){if(!he.__overlays__.has(this.parameters)){let t=new m.ViewController(this.endpoint,this.parameters,this.networkHash);t.init(),he.__overlays__.set(this.parameters,t)}return he.__overlays__.get(this.parameters)}preload(){return f(this,null,function*(){yield this.overlay.checkIsReadyForRequest})}},pe=he;pe.__overlays__=new Map;var G=require("@magic-sdk/types");function dr(n,t){return t&&Array.isArray(n)?n.find(e=>e.id===t):n}function pr(n,t){var o;let e=(o=t.data.response)==null?void 0:o.id,r=dr(n,e);if(e&&r){let s=new F(r).applyResult(t.data.response.result).applyError(t.data.response.error);return{id:e,response:s}}return{}}function hr(n,t,e){return f(this,null,function*(){var i;let r=yield R("rt"),o;if(m.platform==="web")try{o=(i=yield R("jwt"))!=null?i:yield Qe()}catch(c){console.error("webcrypto error",c)}let s={msgType:n,payload:t};o&&(s.jwt=o),o&&r&&(s.rt=r);let a=yield qt(e);return a&&(s.deviceShare=a),s})}function mr(n){return f(this,null,function*(){!n.data.rt||(yield N("rt",n.data.rt))})}var Oe=class{constructor(t,e,r){this.endpoint=t;this.parameters=e;this.networkHash=r;this.messageHandlers=new Set;this.isConnectedToInternet=!0;this.checkIsReadyForRequest=this.waitForReady(),this.isReadyForRequest=!1,this.listen()}post(t,e){return f(this,null,function*(){return Ie((r,o)=>f(this,null,function*(){if(!this.isConnectedToInternet){let l=Fe();o(l)}this.isReadyForRequest||(yield this.waitForReady());let s=[],a=Array.isArray(e)?e.map(l=>l.id):[],i=yield hr(`${t}-${this.parameters}`,e,this.networkHash);yield this._post(i);let c=l=>p=>{var ot;let{id:$,response:I}=pr(e,p);if(mr(p),((ot=I==null?void 0:I.payload.error)==null?void 0:ot.message)==="User denied account access.")te();else if(p.data.deviceShare){let{deviceShare:Ut}=p.data;kt(Ut,this.networkHash)}$&&I&&Array.isArray(e)&&a.includes($)?(s.push(I),s.length===e.length&&(l(),r(s))):$&&I&&!Array.isArray(e)&&$===e.id&&(l(),r(I))},u=this.on(G.MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE,c(()=>u()))}))})}on(t,e){let r=e.bind(window),o=s=>{s.data.msgType===`${t}-${this.parameters}`&&r(s)};return this.messageHandlers.add(o),()=>this.messageHandlers.delete(o)}waitForReady(){return new Promise(t=>{let e=this.on(G.MagicIncomingWindowMessage.MAGIC_OVERLAY_READY,()=>{this.isReadyForRequest=!0,t(),e()})})}listen(){this.on(G.MagicIncomingWindowMessage.MAGIC_HIDE_OVERLAY,()=>{this.hideOverlay()}),this.on(G.MagicIncomingWindowMessage.MAGIC_SHOW_OVERLAY,()=>{this.showOverlay()}),this.on(G.MagicIncomingWindowMessage.MAGIC_SEND_PRODUCT_ANNOUNCEMENT,t=>{t.data.response.result.product_announcement&&new D(G.SDKWarningCode.ProductAnnouncement,t.data.response.result.product_announcement).log()})}};
5
+ Received: \`${n.received}\``)}function Fn(){return new D(C.SDKWarningCode.DuplicateIframe,"Duplicate iframes found.")}function Be(){return new D(C.SDKWarningCode.SyncWeb3Method,"Non-async web3 methods are deprecated in web3 > 1.0 and are not supported by the Magic web3 provider. Please use an async method instead.")}function He(){return new D(C.SDKWarningCode.ReactNativeEndpointConfiguration,`CUSTOM DOMAINS ARE NOT SUPPORTED WHEN USING MAGIC SDK WITH REACT NATIVE! The \`endpoint\` parameter SHOULD NOT be provided. The Magic \`<iframe>\` is automatically wrapped by a WebView pointed at \`${m.defaultEndpoint}\`. Changing this default behavior will lead to unexpected results and potentially security-threatening bugs.`)}function W(n){let{method:t,removalVersions:e,useInstead:r}=n,o=e[m.sdkName],s=r?` Use \`${r}\` instead.`:"",a=`\`${t}\` will be removed from \`${m.sdkName}\` in version \`${o}\`.${s}`;return new D(C.SDKWarningCode.DeprecationNotice,a)}var h=require("@magic-sdk/types");var Z=require("@magic-sdk/types");function*Jn(){let n=0;for(;;)n<Number.MAX_SAFE_INTEGER?yield++n:n=0}var Gn=Jn();function Re(){return Gn.next().value}var Pt=Symbol("Payload pre-processed by Magic SDK");function Mt(n){return Object.defineProperty(n,Pt,{value:!0,enumerable:!1}),n}function Kn(n){return!!n[Pt]}function j(n){var t,e,r;return Kn(n)||(n.jsonrpc=(t=n.jsonrpc)!=null?t:"2.0",n.id=Re(),n.method=(e=n.method)!=null?e:"noop",n.params=(r=n.params)!=null?r:[],Mt(n)),n}function d(n,t=[]){return Mt({params:t,method:n,jsonrpc:"2.0",id:Re()})}var F=class{constructor(t){t instanceof F?(this._jsonrpc=t.payload.jsonrpc,this._id=t.payload.id,this._result=t.payload.result,this._error=t.payload.error):De(t)?(this._jsonrpc=t.jsonrpc,this._id=t.id,this._result=t.result,this._error=t.error):(this._jsonrpc=t.jsonrpc,this._id=t.id,this._result=void 0,this._error=void 0)}applyError(t){return this._error=t,this}applyResult(t){return this._result=t,this}get hasError(){return typeof this._error!="undefined"&&this._error!==null}get hasResult(){return typeof this._result!="undefined"}get payload(){return{jsonrpc:this._jsonrpc,id:this._id,result:this._result,error:this._error}}};var $t=Xt(Nt()),Te=class extends $t.default{};function le(){let n=new Te;return{emitter:n,createChainingEmitterMethod:(r,o)=>(...s)=>(n[r].apply(n,s),o),createBoundEmitterMethod:r=>(...o)=>n[r].apply(n,o)}}var Ct=Symbol("isPromiEvent");function Xe(n){return!!n[Ct]}function O(n){let t=Ie(n),{createBoundEmitterMethod:e,createChainingEmitterMethod:r}=le(),o=Symbol("Promise.then"),s=Symbol("Promise.catch"),a=Symbol("Promise.finally"),i=(l,p)=>(...$)=>{let I=p[l].apply(p,$);return c(I)},c=l=>Object.assign(l,{[Ct]:!0,[o]:l[o]||l.then,[s]:l[s]||l.catch,[a]:l[a]||l.finally,then:i(o,l),catch:i(s,l),finally:i(a,l),on:r("on",l),once:r("once",l),addListener:r("addListener",l),off:r("off",l),removeListener:r("removeListener",l),removeAllListeners:r("removeAllListeners",l),emit:e("emit"),eventNames:e("eventNames"),listeners:e("listeners"),listenerCount:e("listenerCount")}),u=c(t.then(l=>(u.emit("done",l),u.emit("settled"),l),l=>{throw u.emit("error",l),u.emit("settled"),l}));return u}function Ie(n){return new Promise((t,e)=>{let r=n(t,e);Promise.resolve(r).catch(e)})}var x=class{constructor(t){this.sdk=t}get overlay(){return this.sdk.overlay}request(t){let e=this.overlay.post(Z.MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST,j(t)),r=O((s,a)=>{e.then(i=>{if(o(),i.hasError)a(new L(i.payload.error));else if(i.hasResult)s(i.payload.result);else throw Je()}).catch(i=>{o(),a(i)})}),o=this.overlay.on(Z.MagicIncomingWindowMessage.MAGIC_HANDLE_EVENT,s=>{var i;let{response:a}=s.data;if(a.id===t.id&&((i=a.result)==null?void 0:i.event)){let{event:c,params:u=[]}=a.result;r.emit(c,...u)}});return r}createIntermediaryEvent(t,e){return o=>{let s=d(Z.MagicPayloadMethod.IntermediaryEvent,[{payloadId:e,eventType:t,args:o}]);this.request(s)}}};function ze(n,t){let[e]=n.split(".").map(Number);return e>=t}var B={"magic-sdk":"v18.0.0","@magic-sdk/react-native":"v14.0.0","@magic-sdk/react-native-bare":"v19.0.0","@magic-sdk/react-native-expo":"v19.0.0"},be=class extends x{loginWithMagicLink(t){let e=m.sdkName==="@magic-sdk/react-native"||m.sdkName==="@magic-sdk/react-native-bare"||m.sdkName==="@magic-sdk/react-native-expo";if(e&&ze(m.version,19))throw new Error("loginWithMagicLink() is deprecated for this package, please utlize a passcode method like loginWithSMS or loginWithEmailOTP instead.");e&&W({method:"auth.loginWithMagicLink()",removalVersions:B,useInstead:"auth.loginWithEmailOTP()"}).log();let{email:r,showUI:o=!0,redirectURI:s,overrides:a}=t,i=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithMagicLinkTestMode:h.MagicPayloadMethod.LoginWithMagicLink,[{email:r,showUI:o,redirectURI:s,overrides:a}]);return this.request(i)}loginWithSMS(t){let{phoneNumber:e}=t,r=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithSmsTestMode:h.MagicPayloadMethod.LoginWithSms,[{phoneNumber:e,showUI:!0}]);return this.request(r)}loginWithEmailOTP(t){let{email:e,showUI:r,deviceCheckUI:o,overrides:s}=t,a=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithEmailOTPTestMode:h.MagicPayloadMethod.LoginWithEmailOTP,[{email:e,showUI:r,deviceCheckUI:o,overrides:s}]),i=this.request(a);return!o&&i&&i.on(h.DeviceVerificationEventEmit.Retry,()=>{this.createIntermediaryEvent(h.DeviceVerificationEventEmit.Retry,a.id)()}),!r&&i&&(i.on(h.LoginWithEmailOTPEventEmit.VerifyEmailOtp,c=>{this.createIntermediaryEvent(h.LoginWithEmailOTPEventEmit.VerifyEmailOtp,a.id)(c)}),i.on(h.LoginWithEmailOTPEventEmit.Cancel,()=>{this.createIntermediaryEvent(h.LoginWithEmailOTPEventEmit.Cancel,a.id)()})),i}loginWithCredential(t){let e=t!=null?t:"";if(!t&&m.platform==="web"){e=window.location.search;let o=window.location.origin+window.location.pathname;window.history.replaceState(null,"",o)}let r=d(this.sdk.testMode?h.MagicPayloadMethod.LoginWithCredentialTestMode:h.MagicPayloadMethod.LoginWithCredential,[e]);return this.request(r)}setAuthorizationToken(t){let e=d(h.MagicPayloadMethod.SetAuthorizationToken,[{jwt:t}]);return this.request(e)}updateEmailWithUI(t){let{email:e,showUI:r=!0}=t,o=d(this.sdk.testMode?h.MagicPayloadMethod.UpdateEmailTestMode:h.MagicPayloadMethod.UpdateEmail,[{email:e,showUI:r}]),s=this.request(o);return r||(s.on(h.RecencyCheckEventEmit.Retry,()=>{this.createIntermediaryEvent(h.RecencyCheckEventEmit.Retry,o.id)()}),s.on(h.RecencyCheckEventEmit.Cancel,()=>{this.createIntermediaryEvent(h.RecencyCheckEventEmit.Cancel,o.id)()}),s.on(h.RecencyCheckEventEmit.VerifyEmailOtp,a=>{this.createIntermediaryEvent(h.RecencyCheckEventEmit.VerifyEmailOtp,o.id)(a)}),s.on(h.UpdateEmailEventEmit.RetryWithNewEmail,a=>{this.createIntermediaryEvent(h.UpdateEmailEventEmit.RetryWithNewEmail,o.id)(a)}),s.on(h.UpdateEmailEventEmit.Cancel,()=>{this.createIntermediaryEvent(h.UpdateEmailEventEmit.Cancel,o.id)()}),s.on(h.UpdateEmailEventEmit.VerifyEmailOtp,a=>{this.createIntermediaryEvent(h.UpdateEmailEventEmit.VerifyEmailOtp,o.id)(a)})),s}};var v=require("@magic-sdk/types");var Q={};lt(Q,{clear:()=>Hn,getItem:()=>R,iterate:()=>Ye,key:()=>Xn,keys:()=>zn,length:()=>Vn,removeItem:()=>A,setItem:()=>N});var we;function J(n){return(...t)=>f(this,null,function*(){return we||(we=yield m.configureStorage()),yield we.ready(),we[n](...t)})}var R=J("getItem"),N=J("setItem"),A=J("removeItem"),Hn=J("clear"),Vn=J("length"),Xn=J("key"),zn=J("keys"),Ye=J("iterate");function Ze(){let n=window.crypto.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&191|128;let t="";return t+=n[0].toString(16),t+=n[1].toString(16),t+=n[2].toString(16),t+=n[3].toString(16),t+="-",t+=n[4].toString(16),t+=n[5].toString(16),t+="-",t+=n[6].toString(16),t+=n[7].toString(16),t+="-",t+=n[8].toString(16),t+=n[9].toString(16),t+="-",t+=n[10].toString(16),t+=n[11].toString(16),t+=n[12].toString(16),t+=n[13].toString(16),t+=n[14].toString(16),t+=n[15].toString(16),t}var Pe="STORE_KEY_PRIVATE_KEY",ue="STORE_KEY_PUBLIC_JWK",St="ECDSA",Yn="P-256",Zn={name:St,namedCurve:Yn};function ee(){let n=typeof window!="undefined"&&!!window.crypto,t=n&&!!window.crypto.subtle;return n&&t}function Qn(){A(ue),A(Pe)}function Qe(){return f(this,null,function*(){let n=yield er();if(!n){console.info("unable to create public key or webcrypto is unsupported");return}let{subtle:t}=window.crypto,e=yield R(Pe);if(!e||!t){console.info("unable to find private key or webcrypto unsupported");return}let r={iat:Math.floor(new Date().getTime()/1e3),jti:Ze()},o={typ:"dpop+jwt",alg:"ES256",jwk:n},s={protected:At(JSON.stringify(o)),claims:At(JSON.stringify(r))},a=nr(`${s.protected}.${s.claims}`),i={name:St,hash:{name:"SHA-256"}},c=sr(new Uint8Array(yield t.sign(i,e,a)));return`${s.protected}.${s.claims}.${c}`})}function er(){return f(this,null,function*(){if(!ee()){console.info("webcrypto is not supported");return}return(yield R(ue))||(yield tr()),R(ue)})}function tr(){return f(this,null,function*(){let{subtle:n}=window.crypto,t=yield n.generateKey(Zn,!1,["sign"]),e=yield n.exportKey("jwk",t.publicKey);yield N(Pe,t.privateKey),yield N(ue,e)})}function At(n){return Lt(rr(n))}function nr(n){return new TextEncoder().encode(n)}function Lt(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function rr(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,(e,r)=>String.fromCharCode(parseInt(r,16)))}function sr(n){let t="";return n.forEach(e=>{t+=String.fromCharCode(e)}),Lt(t)}var et="ds",tt="ek",nt="iv",rt="AES-GCM",or=256;function te(){return f(this,null,function*(){let n=[];yield Ye((t,e,r)=>{e.startsWith(`${et}_`)&&n.push(e)});for(let t of n)yield A(t)})}function Ot(n){let t="",e=new Uint8Array(n),r=e.byteLength;for(let o=0;o<r;o++)t+=String.fromCharCode(e[o]);return window.btoa(t)}function _t(n){let t=window.atob(n),e=t.length,r=new Uint8Array(e);for(let o=0;o<e;o++)r[o]=t.charCodeAt(o);return r.buffer}function ir(){return f(this,null,function*(){if(!ee()){console.info("webcrypto is not supported");return}let{crypto:n}=window,t=yield R(nt);return t||n.getRandomValues(new Uint8Array(12))})}function ar(){return f(this,null,function*(){if(!ee()){console.info("webcrypto is not supported");return}let{subtle:n}=window.crypto,t=yield R(tt);return t||(yield n.generateKey({name:rt,length:or},!1,["encrypt","decrypt"]))})}function kt(n,t){return f(this,null,function*(){let e=yield ir(),r=yield ar();if(!e||!r||!n)return;let o=_t(n),{subtle:s}=window.crypto,a=yield s.encrypt({name:rt,iv:e},r,o),i=Ot(a);yield N(`${et}_${t}`,i),yield N(tt,r),yield N(nt,e)})}function qt(n){return f(this,null,function*(){let t=yield R(`${et}_${n}`),e=yield R(nt),r=yield R(tt);if(!e||!t||!r||!ee())return;let{subtle:o}=window.crypto,s=yield o.decrypt({name:rt,iv:e},r,_t(t));return Ot(s)})}function Me(n,t){return t?new URL(n,t):new URL(n)}var xe=class extends x{constructor(){super(...arguments);this.localForageKey="mc_active_wallet";this.localForageIsLoggedInKey="magic_auth_is_logged_in";this.userLoggedOutCallbacks=[]}getIdToken(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.GetIdTokenTestMode:v.MagicPayloadMethod.GetIdToken,[e]);return this.request(r)}generateIdToken(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.GenerateIdTokenTestMode:v.MagicPayloadMethod.GenerateIdToken,[e]);return this.request(r)}getInfo(){return f(this,null,function*(){let e=yield R(this.localForageKey),r=d(v.MagicPayloadMethod.GetInfo,[{walletType:e}]);return this.request(r)})}isLoggedIn(){return O((e,r)=>f(this,null,function*(){try{let o=!1;this.sdk.useStorageCache&&(o=(yield R(this.localForageIsLoggedInKey))==="true",o&&e(!0));let s=d(this.sdk.testMode?v.MagicPayloadMethod.IsLoggedInTestMode:v.MagicPayloadMethod.IsLoggedIn),a=yield this.request(s);this.sdk.useStorageCache&&(a?N(this.localForageIsLoggedInKey,!0):A(this.localForageIsLoggedInKey),o&&!a&&this.emitUserLoggedOut(!0)),e(a)}catch(o){r(o)}}))}logout(){return A(this.localForageKey),A(this.localForageIsLoggedInKey),te(),O((e,r)=>f(this,null,function*(){try{let o=d(this.sdk.testMode?v.MagicPayloadMethod.LogoutTestMode:v.MagicPayloadMethod.Logout),s=yield this.request(o);this.sdk.useStorageCache&&this.emitUserLoggedOut(s),e(s)}catch(o){r(o)}}))}requestInfoWithUI(e){let r=d(v.MagicPayloadMethod.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}showSettings(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.UserSettingsTestMode:v.MagicPayloadMethod.UserSettings,[e]);return this.request(r)}recoverAccount(e){let r=d(this.sdk.testMode?v.MagicPayloadMethod.RecoverAccountTestMode:v.MagicPayloadMethod.RecoverAccount,[e]);return this.request(r)}revealPrivateKey(){let e=d(v.MagicPayloadMethod.RevealPK);return this.request(e)}getMetadata(){W({method:"user.getMetadata()",removalVersions:B,useInstead:"user.getInfo()"}).log();let e=d(this.sdk.testMode?v.MagicPayloadMethod.GetMetadataTestMode:v.MagicPayloadMethod.GetMetadata);return this.request(e)}onUserLoggedOut(e){this.userLoggedOutCallbacks.push(e)}emitUserLoggedOut(e){this.userLoggedOutCallbacks.forEach(r=>{r(e)})}};var y=require("@magic-sdk/types");var Ne=class extends x{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}connectWithUI(){let e=O((r,o)=>f(this,null,function*(){try{if(this.isMetaMaskBrowser()&&(yield this.isWalletEnabled(y.Wallets.MetaMask))){let u=yield this.autoConnectIfWalletBrowser(y.Wallets.MetaMask);r(u);return}if(this.isCoinbaseWalletBrowser()&&(yield this.isWalletEnabled(y.Wallets.CoinbaseWallet))){let u=yield this.autoConnectIfWalletBrowser(y.Wallets.CoinbaseWallet);r(u);return}let s=this.getUserEnv(),a=d(y.MagicPayloadMethod.Login,[s]),i=this.request(a);i.on(y.Events.WalletSelected,u=>this.handleWalletSelected(V(H({},u),{payloadId:a.id}))),i.on("id-token-created",u=>{e.emit("id-token-created",u)});let c=yield i;c.error&&o(c),r(c)}catch(s){o(s)}}));return e}showUI(){return this.request(d(y.MagicPayloadMethod.ShowUI))}showAddress(){return this.request(d(y.MagicPayloadMethod.ShowAddress))}showSendTokensUI(){return this.request(d(y.MagicPayloadMethod.ShowSendTokensUI))}showOnRamp(){return this.request(d(y.MagicPayloadMethod.ShowOnRamp))}showNFTs(){return this.request(d(y.MagicPayloadMethod.ShowNFTs))}showBalances(){return this.request(d(y.MagicPayloadMethod.ShowBalances))}sendGaslessTransaction(e,r){return this.request(d(y.MagicPayloadMethod.SendGaslessTransaction,[e,r]))}getInfo(){return f(this,null,function*(){W({method:"wallet.getInfo()",removalVersions:B,useInstead:"user.getInfo()"}).log();let e=yield R(this.localForageKey),r=d(y.MagicPayloadMethod.GetInfo,[{walletType:e}]);return this.request(r)})}disconnect(){W({method:"wallet.disconnect()",removalVersions:B,useInstead:"user.logout()"}).log(),A(this.localForageKey),te();let e=d(y.MagicPayloadMethod.Disconnect);return this.request(e)}requestUserInfoWithUI(e){W({method:"wallet.requestUserInfoWithUI()",removalVersions:B,useInstead:"user.requestUserInfoWithUI()"}).log();let r=d(y.MagicPayloadMethod.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}getProvider(){return f(this,null,function*(){switch(yield R(this.localForageKey)){case y.Wallets.MetaMask:return this.getMetaMaskProvider();case y.Wallets.CoinbaseWallet:return this.getCoinbaseProvider();default:return this.sdk.rpcProvider}})}isMetaMaskInstalled(){var e,r,o;return((e=window.ethereum)==null?void 0:e.isMetaMask)||!!((o=(r=window.ethereum)==null?void 0:r.providers)!=null&&o.find(s=>s==null?void 0:s.isMetaMask))}isMetaMaskBrowser(){return this.isMobile()&&this.isMetaMaskInstalled()}getMetaMaskProvider(){var e,r;return((r=(e=window.ethereum)==null?void 0:e.providers)==null?void 0:r.find(o=>o==null?void 0:o.isMetaMask))||window.ethereum}connectToMetaMask(){if(this.isMobile()&&!this.isMetaMaskInstalled()){let e=`https://metamask.app.link/dapp/${window.location.href.replace(/(^\w+:|^)\/\//,"")}`;window.location.href=e}return this.getMetaMaskProvider().request({method:"eth_requestAccounts"})}isCoinbaseWalletInstalled(){var e,r,o;return((e=window.ethereum)==null?void 0:e.isCoinbaseWallet)||!!((o=(r=window.ethereum)==null?void 0:r.providers)!=null&&o.find(s=>s==null?void 0:s.isCoinbaseWallet))}isCoinbaseWalletBrowser(){var e;return!!((e=window.ethereum)!=null&&e.isCoinbaseBrowser)}getCoinbaseProvider(){var e,r;return((r=(e=window.ethereum)==null?void 0:e.providers)==null?void 0:r.find(o=>o==null?void 0:o.isCoinbaseWallet))||window.ethereum}connectToCoinbaseWallet(){if(this.isMobile()&&!this.isCoinbaseWalletBrowser()){let r=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(window.location.href)}`;window.location.href=r}return this.getCoinbaseProvider().request({method:"eth_requestAccounts"})}isMobile(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Silk|Opera Mini/i.test(navigator.userAgent)}getUserEnv(){return{env:{isMetaMaskInstalled:this.isMetaMaskInstalled(),isCoinbaseWalletInstalled:this.isCoinbaseWalletInstalled()}}}connectToThirdPartyWallet(e){switch(e){case y.Wallets.MetaMask:return this.connectToMetaMask();case y.Wallets.CoinbaseWallet:return this.connectToCoinbaseWallet();default:throw new Error(`Invalid provider: ${e}. Must be one of "metamask" or "coinbase_wallet".`)}}isWalletEnabled(e){let r=d("mc_is_wallet_enabled",[{wallet:e}]);return this.request(r)}handleWalletSelected(e){return f(this,null,function*(){try{let r=yield this.connectToThirdPartyWallet(e.wallet);yield N(this.localForageKey,e.wallet),this.createIntermediaryEvent(y.Events.WalletConnected,e.payloadId)(r)}catch(r){console.error(r),this.createIntermediaryEvent(y.Events.WalletRejected,e.payloadId)()}})}autoConnectIfWalletBrowser(e){return f(this,null,function*(){let r;e===y.Wallets.MetaMask&&(r=yield this.getMetaMaskProvider().request({method:"eth_requestAccounts"})),e===y.Wallets.CoinbaseWallet&&(r=yield this.getCoinbaseProvider().request({method:"eth_requestAccounts"})),yield N(this.localForageKey,e);let o=d(y.MagicPayloadMethod.AutoConnect,[{wallet:e,address:r}]);return this.request(o)})}};var de=require("@magic-sdk/types");var{createBoundEmitterMethod:$e,createChainingEmitterMethod:ne}=le(),Ce=class extends x{constructor(){super(...arguments);this.isMagic=!0;this.on=ne("on",this);this.once=ne("once",this);this.addListener=ne("addListener",this);this.off=ne("off",this);this.removeListener=ne("removeListener",this);this.removeAllListeners=ne("removeAllListeners",this);this.emit=$e("emit");this.eventNames=$e("eventNames");this.listeners=$e("listeners");this.listenerCount=$e("listenerCount")}sendAsync(e,r){if(!r)throw je({procedure:"Magic.rpcProvider.sendAsync",argument:1,expected:"function",received:r===null?"null":typeof r});if(Array.isArray(e))this.overlay.post(de.MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST,e.map(o=>{let s=j(o);return this.prefixPayloadMethodForTestMode(s),s})).then(o=>{r(null,o.map(s=>V(H({},s.payload),{error:s.hasError?new L(s.payload.error):null})))});else{let o=j(e);this.prefixPayloadMethodForTestMode(o),this.overlay.post(de.MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST,o).then(s=>{r(s.hasError?new L(s.payload.error):null,s.payload)})}}send(e,r){if(typeof e=="string"){let s=d(e,Array.isArray(r)?r:[]);return this.request(s)}if(Array.isArray(e)||!!r){this.sendAsync(e,r);return}let o=Be();return o.log(),new F(e).applyError({code:-32603,message:o.rawMessage}).payload}enable(){let e=d(de.MagicPayloadMethod.Login);return this.request(e)}request(e){return this.prefixPayloadMethodForTestMode(e),super.request(e)}prefixPayloadMethodForTestMode(e){let r="testMode/eth/";this.sdk.testMode&&(e.method=`${r}${e.method}`)}};var Dt=["request","overlay","sdk"];function cr(n){let t=Object.getPrototypeOf(n),e=[t];for(;t!==x.prototype;)t=Object.getPrototypeOf(t),e.push(t);return e}var Ae=class extends x{constructor(){super(void 0);this.__sdk_access_field_descriptors__=new Map;this.__is_initialized__=!1;this.utils={createPromiEvent:O,isPromiEvent:Xe,encodeJSON:ae,decodeJSON:qe,createJsonRpcRequestPayload:d,standardizeJsonRpcRequestPayload:j,storage:Q};let e=[this,...cr(this)];Dt.forEach(r=>{let o=e.map(c=>Object.getOwnPropertyDescriptor(c,r)),s=o.findIndex(c=>!!c),a=s>0,i=o[s];i&&(this.__sdk_access_field_descriptors__.set(r,{descriptor:i,isPrototypeField:a}),Object.defineProperty(this,r,{configurable:!0,get:()=>{throw Ge(r)}}))})}init(e){this.__is_initialized__||(Dt.forEach(r=>{if(this.__sdk_access_field_descriptors__.has(r)){let{descriptor:o,isPrototypeField:s}=this.__sdk_access_field_descriptors__.get(r);s?delete this[r]:Object.defineProperty(this,r,o)}}),this.sdk=e,this.__is_initialized__=!0)}createDeprecationWarning(e){let{method:r,removalVersion:o,useInstead:s}=e,a=s?` Use \`${s}\` instead.`:"",i=`\`${r}\` will be removed from this Extension in version \`${o}\`.${a}`;return new Y(this,"DEPRECATION_NOTICE",i)}createWarning(e,r){return new Y(this,e,r)}createError(e,r,o){return new K(this,e,r,o)}},st=class extends Ae{},_=class extends Ae{};_.Internal=st,_.Anonymous="anonymous extension";var Se=require("@magic-sdk/types");var Le=class extends x{purchase(t){let e=d(Se.MagicPayloadMethod.NFTPurchase,[t]);return this.request(e)}checkout(t){let e=d(Se.MagicPayloadMethod.NFTCheckout,[t]);return this.request(e)}transfer(t){let e=d(Se.MagicPayloadMethod.NFTTransfer,[t]);return this.request(e)}};function Wt(n){return n.compat&&n.compat[m.sdkName]!=null?typeof n.compat[m.sdkName]=="string"?Tt(It(m.version),n.compat[m.sdkName]):!!n.compat[m.sdkName]:!0}function lr(n,t,e){return!t&&!e?`${n}_eth_mainnet`:e?`${n}_${JSON.stringify(e)}`:t?typeof t=="string"?`${n}_eth_${t}`:`${n}_${t.rpcUrl}_${t.chainId}_${t.chainType}`:`${n}_unknown`}function ur(n){var o;let t=(o=n==null?void 0:n.extensions)!=null?o:[],e={},r=[];if(Array.isArray(t)?t.forEach(s=>{Wt(s)?(s.init(this),(s.name||s.name!==_.Anonymous)&&(this[s.name]=s),s instanceof _.Internal&&(z(s.config)||(e[s.name]=s.config))):r.push(s)}):Object.keys(t).forEach(s=>{if(Wt(t[s])){t[s].init(this);let a=t[s];this[s]=a,a instanceof _.Internal&&(z(a.config)||(e[t[s].name]=a.config))}else r.push(t[s])}),r.length)throw Ke(r);return e}var he=class{constructor(t,e){this.apiKey=t;var a;if(!t)throw Ue();m.platform==="react-native"&&(e==null?void 0:e.endpoint)&&He().log();let{defaultEndpoint:r,version:o}=m;this.testMode=!!(e!=null&&e.testMode),this.useStorageCache=!!(e!=null&&e.useStorageCache),this.endpoint=Me((a=e==null?void 0:e.endpoint)!=null?a:r).origin,this.auth=new be(this),this.user=new xe(this),this.wallet=new Ne(this),this.nft=new Le(this),this.rpcProvider=new Ce(this);let s=ur.call(this,e);this.parameters=ae(V(H({API_KEY:this.apiKey,DOMAIN_ORIGIN:window.location?window.location.origin:"",ETH_NETWORK:e==null?void 0:e.network,host:Me(this.endpoint).host,sdk:wt[m.sdkName],version:o,ext:z(s)?void 0:s,locale:(e==null?void 0:e.locale)||"en_US"},m.bundleId?{bundleId:m.bundleId}:{}),{meta:e==null?void 0:e.meta})),this.networkHash=lr(this.apiKey,e==null?void 0:e.network,z(s)?void 0:s),e!=null&&e.deferPreload||this.preload()}get overlay(){if(!he.__overlays__.has(this.parameters)){let t=new m.ViewController(this.endpoint,this.parameters,this.networkHash);t.init(),he.__overlays__.set(this.parameters,t)}return he.__overlays__.get(this.parameters)}preload(){return f(this,null,function*(){yield this.overlay.checkIsReadyForRequest})}},pe=he;pe.__overlays__=new Map;var G=require("@magic-sdk/types");function dr(n,t){return t&&Array.isArray(n)?n.find(e=>e.id===t):n}function pr(n,t){var o;let e=(o=t.data.response)==null?void 0:o.id,r=dr(n,e);if(e&&r){let s=new F(r).applyResult(t.data.response.result).applyError(t.data.response.error);return{id:e,response:s}}return{}}function hr(n,t,e){return f(this,null,function*(){var i;let r=yield R("rt"),o;if(m.platform==="web")try{o=(i=yield R("jwt"))!=null?i:yield Qe()}catch(c){console.error("webcrypto error",c)}let s={msgType:n,payload:t};o&&(s.jwt=o),o&&r&&(s.rt=r);let a=yield qt(e);return a&&(s.deviceShare=a),s})}function mr(n){return f(this,null,function*(){!n.data.rt||(yield N("rt",n.data.rt))})}var Oe=class{constructor(t,e,r){this.endpoint=t;this.parameters=e;this.networkHash=r;this.messageHandlers=new Set;this.isConnectedToInternet=!0;this.checkIsReadyForRequest=this.waitForReady(),this.isReadyForRequest=!1,this.listen()}post(t,e){return f(this,null,function*(){return Ie((r,o)=>f(this,null,function*(){if(!this.isConnectedToInternet){let l=Fe();o(l)}this.isReadyForRequest||(yield this.waitForReady());let s=[],a=Array.isArray(e)?e.map(l=>l.id):[],i=yield hr(`${t}-${this.parameters}`,e,this.networkHash);yield this._post(i);let c=l=>p=>{var ot;let{id:$,response:I}=pr(e,p);if(mr(p),((ot=I==null?void 0:I.payload.error)==null?void 0:ot.message)==="User denied account access.")te();else if(p.data.deviceShare){let{deviceShare:Ut}=p.data;kt(Ut,this.networkHash)}$&&I&&Array.isArray(e)&&a.includes($)?(s.push(I),s.length===e.length&&(l(),r(s))):$&&I&&!Array.isArray(e)&&$===e.id&&(l(),r(I))},u=this.on(G.MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE,c(()=>u()))}))})}on(t,e){let r=e.bind(window),o=s=>{s.data.msgType===`${t}-${this.parameters}`&&r(s)};return this.messageHandlers.add(o),()=>this.messageHandlers.delete(o)}waitForReady(){return new Promise(t=>{setTimeout(()=>{this.isReadyForRequest=!0,t()},3e3);let e=this.on(G.MagicIncomingWindowMessage.MAGIC_OVERLAY_READY,()=>{this.isReadyForRequest=!0,t(),e()})})}listen(){this.on(G.MagicIncomingWindowMessage.MAGIC_HIDE_OVERLAY,()=>{this.hideOverlay()}),this.on(G.MagicIncomingWindowMessage.MAGIC_SHOW_OVERLAY,()=>{this.showOverlay()}),this.on(G.MagicIncomingWindowMessage.MAGIC_SEND_PRODUCT_ANNOUNCEMENT,t=>{t.data.response.result.product_announcement&&new D(G.SDKWarningCode.ProductAnnouncement,t.data.response.result.product_announcement).log()})}};
6
6
  //# sourceMappingURL=index.js.map