@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/es/index.js CHANGED
@@ -2,5 +2,5 @@ var Gt=Object.create;var ue=Object.defineProperty,Kt=Object.defineProperties,jt=
2
2
  - Extension \`${e.name}\` supports version(s) \`${r}\``:r||(t+=`
3
3
  - Extension \`${e.name}\` does not support ${h.platform} environments.`)}),new A(X.IncompatibleExtensions,t)}function gt(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 A(X.InvalidArgument,`Invalid ${t(n.argument)} argument given to \`${n.procedure}\`.
4
4
  Expected: \`${n.expected}\`
5
- Received: \`${n.received}\``)}function qr(){return new W(Ee.DuplicateIframe,"Duplicate iframes found.")}function Rt(){return new W(Ee.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 vt(){return new W(Ee.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 \`${h.defaultEndpoint}\`. Changing this default behavior will lead to unexpected results and potentially security-threatening bugs.`)}function U(n){let{method:t,removalVersions:e,useInstead:r}=n,o=e[h.sdkName],s=r?` Use \`${r}\` instead.`:"",a=`\`${t}\` will be removed from \`${h.sdkName}\` in version \`${o}\`.${s}`;return new W(Ee.DeprecationNotice,a)}import{MagicPayloadMethod as C,DeviceVerificationEventEmit as $t,LoginWithEmailOTPEventEmit as Re,UpdateEmailEventEmit as z,RecencyCheckEventEmit as Y}from"@magic-sdk/types";import{MagicOutgoingWindowMessage as Yn,MagicIncomingWindowMessage as Zn,MagicPayloadMethod as Qn}from"@magic-sdk/types";function*Bn(){let n=0;for(;;)n<Number.MAX_SAFE_INTEGER?yield++n:n=0}var Hn=Bn();function Se(){return Hn.next().value}var Tt=Symbol("Payload pre-processed by Magic SDK");function It(n){return Object.defineProperty(n,Tt,{value:!0,enumerable:!1}),n}function Vn(n){return!!n[Tt]}function G(n){var t,e,r;return Vn(n)||(n.jsonrpc=(t=n.jsonrpc)!=null?t:"2.0",n.id=Se(),n.method=(e=n.method)!=null?e:"noop",n.params=(r=n.params)!=null?r:[],It(n)),n}function d(n,t=[]){return It({params:t,method:n,jsonrpc:"2.0",id:Se()})}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):ut(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 Pt=Qt(wt()),Oe=class extends Pt.default{};function ge(){let n=new Oe;return{emitter:n,createChainingEmitterMethod:(r,o)=>(...s)=>(n[r].apply(n,s),o),createBoundEmitterMethod:r=>(...o)=>n[r].apply(n,o)}}var Mt=Symbol("isPromiEvent");function xt(n){return!!n[Mt]}function k(n){let t=_e(n),{createBoundEmitterMethod:e,createChainingEmitterMethod:r}=ge(),o=Symbol("Promise.then"),s=Symbol("Promise.catch"),a=Symbol("Promise.finally"),i=(l,p)=>(...x)=>{let v=p[l].apply(p,x);return c(v)},c=l=>Object.assign(l,{[Mt]:!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 _e(n){return new Promise((t,e)=>{let r=n(t,e);Promise.resolve(r).catch(e)})}var P=class{constructor(t){this.sdk=t}get overlay(){return this.sdk.overlay}request(t){let e=this.overlay.post(Yn.MAGIC_HANDLE_REQUEST,G(t)),r=k((s,a)=>{e.then(i=>{if(o(),i.hasError)a(new _(i.payload.error));else if(i.hasResult)s(i.payload.result);else throw ft()}).catch(i=>{o(),a(i)})}),o=this.overlay.on(Zn.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(Qn.IntermediaryEvent,[{payloadId:e,eventType:t,args:o}]);this.request(s)}}};function Nt(n,t){let[e]=n.split(".").map(Number);return e>=t}var K={"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"},ve=class extends P{loginWithMagicLink(t){let e=h.sdkName==="@magic-sdk/react-native"||h.sdkName==="@magic-sdk/react-native-bare"||h.sdkName==="@magic-sdk/react-native-expo";if(e&&Nt(h.version,19))throw new Error("loginWithMagicLink() is deprecated for this package, please utlize a passcode method like loginWithSMS or loginWithEmailOTP instead.");e&&U({method:"auth.loginWithMagicLink()",removalVersions:K,useInstead:"auth.loginWithEmailOTP()"}).log();let{email:r,showUI:o=!0,redirectURI:s,overrides:a}=t,i=d(this.sdk.testMode?C.LoginWithMagicLinkTestMode:C.LoginWithMagicLink,[{email:r,showUI:o,redirectURI:s,overrides:a}]);return this.request(i)}loginWithSMS(t){let{phoneNumber:e}=t,r=d(this.sdk.testMode?C.LoginWithSmsTestMode:C.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?C.LoginWithEmailOTPTestMode:C.LoginWithEmailOTP,[{email:e,showUI:r,deviceCheckUI:o,overrides:s}]),i=this.request(a);return!o&&i&&i.on($t.Retry,()=>{this.createIntermediaryEvent($t.Retry,a.id)()}),!r&&i&&(i.on(Re.VerifyEmailOtp,c=>{this.createIntermediaryEvent(Re.VerifyEmailOtp,a.id)(c)}),i.on(Re.Cancel,()=>{this.createIntermediaryEvent(Re.Cancel,a.id)()})),i}loginWithCredential(t){let e=t!=null?t:"";if(!t&&h.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?C.LoginWithCredentialTestMode:C.LoginWithCredential,[e]);return this.request(r)}setAuthorizationToken(t){let e=d(C.SetAuthorizationToken,[{jwt:t}]);return this.request(e)}updateEmailWithUI(t){let{email:e,showUI:r=!0}=t,o=d(this.sdk.testMode?C.UpdateEmailTestMode:C.UpdateEmail,[{email:e,showUI:r}]),s=this.request(o);return r||(s.on(Y.Retry,()=>{this.createIntermediaryEvent(Y.Retry,o.id)()}),s.on(Y.Cancel,()=>{this.createIntermediaryEvent(Y.Cancel,o.id)()}),s.on(Y.VerifyEmailOtp,a=>{this.createIntermediaryEvent(Y.VerifyEmailOtp,o.id)(a)}),s.on(z.RetryWithNewEmail,a=>{this.createIntermediaryEvent(z.RetryWithNewEmail,o.id)(a)}),s.on(z.Cancel,()=>{this.createIntermediaryEvent(z.Cancel,o.id)()}),s.on(z.VerifyEmailOtp,a=>{this.createIntermediaryEvent(z.VerifyEmailOtp,o.id)(a)})),s}};import{MagicPayloadMethod as R}from"@magic-sdk/types";var ie={};Yt(ie,{clear:()=>er,getItem:()=>y,iterate:()=>ke,key:()=>nr,keys:()=>rr,length:()=>tr,removeItem:()=>N,setItem:()=>M});var Te;function J(n){return(...t)=>m(this,null,function*(){return Te||(Te=yield h.configureStorage()),yield Te.ready(),Te[n](...t)})}var y=J("getItem"),M=J("setItem"),N=J("removeItem"),er=J("clear"),tr=J("length"),nr=J("key"),rr=J("keys"),ke=J("iterate");function Ct(){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 qe="STORE_KEY_PRIVATE_KEY",Ie="STORE_KEY_PUBLIC_JWK",St="ECDSA",sr="P-256",or={name:St,namedCurve:sr};function ae(){let n=typeof window!="undefined"&&!!window.crypto,t=n&&!!window.crypto.subtle;return n&&t}function Ts(){N(Ie),N(qe)}function Lt(){return m(this,null,function*(){let n=yield ir();if(!n){console.info("unable to create public key or webcrypto is unsupported");return}let{subtle:t}=window.crypto,e=yield y(qe);if(!e||!t){console.info("unable to find private key or webcrypto unsupported");return}let r={iat:Math.floor(new Date().getTime()/1e3),jti:Ct()},o={typ:"dpop+jwt",alg:"ES256",jwk:n},s={protected:At(JSON.stringify(o)),claims:At(JSON.stringify(r))},a=cr(`${s.protected}.${s.claims}`),i={name:St,hash:{name:"SHA-256"}},c=ur(new Uint8Array(yield t.sign(i,e,a)));return`${s.protected}.${s.claims}.${c}`})}function ir(){return m(this,null,function*(){if(!ae()){console.info("webcrypto is not supported");return}return(yield y(Ie))||(yield ar()),y(Ie)})}function ar(){return m(this,null,function*(){let{subtle:n}=window.crypto,t=yield n.generateKey(or,!1,["sign"]),e=yield n.exportKey("jwk",t.publicKey);yield M(qe,t.privateKey),yield M(Ie,e)})}function At(n){return Ot(lr(n))}function cr(n){return new TextEncoder().encode(n)}function Ot(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function lr(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,(e,r)=>String.fromCharCode(parseInt(r,16)))}function ur(n){let t="";return n.forEach(e=>{t+=String.fromCharCode(e)}),Ot(t)}var De="ds",We="ek",Ue="iv",Fe="AES-GCM",dr=256;function Z(){return m(this,null,function*(){let n=[];yield ke((t,e,r)=>{e.startsWith(`${De}_`)&&n.push(e)});for(let t of n)yield N(t)})}function _t(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 kt(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 pr(){return m(this,null,function*(){if(!ae()){console.info("webcrypto is not supported");return}let{crypto:n}=window,t=yield y(Ue);return t||n.getRandomValues(new Uint8Array(12))})}function hr(){return m(this,null,function*(){if(!ae()){console.info("webcrypto is not supported");return}let{subtle:n}=window.crypto,t=yield y(We);return t||(yield n.generateKey({name:Fe,length:dr},!1,["encrypt","decrypt"]))})}function qt(n,t){return m(this,null,function*(){let e=yield pr(),r=yield hr();if(!e||!r||!n)return;let o=kt(n),{subtle:s}=window.crypto,a=yield s.encrypt({name:Fe,iv:e},r,o),i=_t(a);yield M(`${De}_${t}`,i),yield M(We,r),yield M(Ue,e)})}function Dt(n){return m(this,null,function*(){let t=yield y(`${De}_${n}`),e=yield y(Ue),r=yield y(We);if(!e||!t||!r||!ae())return;let{subtle:o}=window.crypto,s=yield o.decrypt({name:Fe,iv:e},r,kt(t));return _t(s)})}function Je(n,t){return t?new URL(n,t):new URL(n)}var be=class extends P{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?R.GetIdTokenTestMode:R.GetIdToken,[e]);return this.request(r)}generateIdToken(e){let r=d(this.sdk.testMode?R.GenerateIdTokenTestMode:R.GenerateIdToken,[e]);return this.request(r)}getInfo(){return m(this,null,function*(){let e=yield y(this.localForageKey),r=d(R.GetInfo,[{walletType:e}]);return this.request(r)})}isLoggedIn(){return k((e,r)=>m(this,null,function*(){try{let o=!1;this.sdk.useStorageCache&&(o=(yield y(this.localForageIsLoggedInKey))==="true",o&&e(!0));let s=d(this.sdk.testMode?R.IsLoggedInTestMode:R.IsLoggedIn),a=yield this.request(s);this.sdk.useStorageCache&&(a?M(this.localForageIsLoggedInKey,!0):N(this.localForageIsLoggedInKey),o&&!a&&this.emitUserLoggedOut(!0)),e(a)}catch(o){r(o)}}))}logout(){return N(this.localForageKey),N(this.localForageIsLoggedInKey),Z(),k((e,r)=>m(this,null,function*(){try{let o=d(this.sdk.testMode?R.LogoutTestMode:R.Logout),s=yield this.request(o);this.sdk.useStorageCache&&this.emitUserLoggedOut(s),e(s)}catch(o){r(o)}}))}requestInfoWithUI(e){let r=d(R.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}showSettings(e){let r=d(this.sdk.testMode?R.UserSettingsTestMode:R.UserSettings,[e]);return this.request(r)}recoverAccount(e){let r=d(this.sdk.testMode?R.RecoverAccountTestMode:R.RecoverAccount,[e]);return this.request(r)}revealPrivateKey(){let e=d(R.RevealPK);return this.request(e)}getMetadata(){U({method:"user.getMetadata()",removalVersions:K,useInstead:"user.getInfo()"}).log();let e=d(this.sdk.testMode?R.GetMetadataTestMode:R.GetMetadata);return this.request(e)}onUserLoggedOut(e){this.userLoggedOutCallbacks.push(e)}emitUserLoggedOut(e){this.userLoggedOutCallbacks.forEach(r=>{r(e)})}};import{Events as Ge,MagicPayloadMethod as $,Wallets as S}from"@magic-sdk/types";var we=class extends P{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}connectWithUI(){let e=k((r,o)=>m(this,null,function*(){try{if(this.isMetaMaskBrowser()&&(yield this.isWalletEnabled(S.MetaMask))){let u=yield this.autoConnectIfWalletBrowser(S.MetaMask);r(u);return}if(this.isCoinbaseWalletBrowser()&&(yield this.isWalletEnabled(S.CoinbaseWallet))){let u=yield this.autoConnectIfWalletBrowser(S.CoinbaseWallet);r(u);return}let s=this.getUserEnv(),a=d($.Login,[s]),i=this.request(a);i.on(Ge.WalletSelected,u=>this.handleWalletSelected(B(j({},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($.ShowUI))}showAddress(){return this.request(d($.ShowAddress))}showSendTokensUI(){return this.request(d($.ShowSendTokensUI))}showOnRamp(){return this.request(d($.ShowOnRamp))}showNFTs(){return this.request(d($.ShowNFTs))}showBalances(){return this.request(d($.ShowBalances))}sendGaslessTransaction(e,r){return this.request(d($.SendGaslessTransaction,[e,r]))}getInfo(){return m(this,null,function*(){U({method:"wallet.getInfo()",removalVersions:K,useInstead:"user.getInfo()"}).log();let e=yield y(this.localForageKey),r=d($.GetInfo,[{walletType:e}]);return this.request(r)})}disconnect(){U({method:"wallet.disconnect()",removalVersions:K,useInstead:"user.logout()"}).log(),N(this.localForageKey),Z();let e=d($.Disconnect);return this.request(e)}requestUserInfoWithUI(e){U({method:"wallet.requestUserInfoWithUI()",removalVersions:K,useInstead:"user.requestUserInfoWithUI()"}).log();let r=d($.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}getProvider(){return m(this,null,function*(){switch(yield y(this.localForageKey)){case S.MetaMask:return this.getMetaMaskProvider();case S.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 S.MetaMask:return this.connectToMetaMask();case S.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 m(this,null,function*(){try{let r=yield this.connectToThirdPartyWallet(e.wallet);yield M(this.localForageKey,e.wallet),this.createIntermediaryEvent(Ge.WalletConnected,e.payloadId)(r)}catch(r){console.error(r),this.createIntermediaryEvent(Ge.WalletRejected,e.payloadId)()}})}autoConnectIfWalletBrowser(e){return m(this,null,function*(){let r;e===S.MetaMask&&(r=yield this.getMetaMaskProvider().request({method:"eth_requestAccounts"})),e===S.CoinbaseWallet&&(r=yield this.getCoinbaseProvider().request({method:"eth_requestAccounts"})),yield M(this.localForageKey,e);let o=d($.AutoConnect,[{wallet:e,address:r}]);return this.request(o)})}};import{MagicOutgoingWindowMessage as Wt,MagicPayloadMethod as mr}from"@magic-sdk/types";var{createBoundEmitterMethod:Pe,createChainingEmitterMethod:Q}=ge(),Me=class extends P{constructor(){super(...arguments);this.isMagic=!0;this.on=Q("on",this);this.once=Q("once",this);this.addListener=Q("addListener",this);this.off=Q("off",this);this.removeListener=Q("removeListener",this);this.removeAllListeners=Q("removeAllListeners",this);this.emit=Pe("emit");this.eventNames=Pe("eventNames");this.listeners=Pe("listeners");this.listenerCount=Pe("listenerCount")}sendAsync(e,r){if(!r)throw gt({procedure:"Magic.rpcProvider.sendAsync",argument:1,expected:"function",received:r===null?"null":typeof r});if(Array.isArray(e))this.overlay.post(Wt.MAGIC_HANDLE_REQUEST,e.map(o=>{let s=G(o);return this.prefixPayloadMethodForTestMode(s),s})).then(o=>{r(null,o.map(s=>B(j({},s.payload),{error:s.hasError?new _(s.payload.error):null})))});else{let o=G(e);this.prefixPayloadMethodForTestMode(o),this.overlay.post(Wt.MAGIC_HANDLE_REQUEST,o).then(s=>{r(s.hasError?new _(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=Rt();return o.log(),new F(e).applyError({code:-32603,message:o.rawMessage}).payload}enable(){let e=d(mr.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 Ut=["request","overlay","sdk"];function fr(n){let t=Object.getPrototypeOf(n),e=[t];for(;t!==P.prototype;)t=Object.getPrototypeOf(t),e.push(t);return e}var xe=class extends P{constructor(){super(void 0);this.__sdk_access_field_descriptors__=new Map;this.__is_initialized__=!1;this.utils={createPromiEvent:k,isPromiEvent:xt,encodeJSON:me,decodeJSON:lt,createJsonRpcRequestPayload:d,standardizeJsonRpcRequestPayload:G,storage:ie};let e=[this,...fr(this)];Ut.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 Et(r)}}))})}init(e){this.__is_initialized__||(Ut.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 se(this,"DEPRECATION_NOTICE",i)}createWarning(e,r){return new se(this,e,r)}createError(e,r,o){return new V(this,e,r,o)}},Ke=class extends xe{},q=class extends xe{};q.Internal=Ke,q.Anonymous="anonymous extension";import{MagicPayloadMethod as je}from"@magic-sdk/types";var Ne=class extends P{purchase(t){let e=d(je.NFTPurchase,[t]);return this.request(e)}checkout(t){let e=d(je.NFTCheckout,[t]);return this.request(e)}transfer(t){let e=d(je.NFTTransfer,[t]);return this.request(e)}};function Ft(n){return n.compat&&n.compat[h.sdkName]!=null?typeof n.compat[h.sdkName]=="string"?at(ct(h.version),n.compat[h.sdkName]):!!n.compat[h.sdkName]:!0}function Er(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 yr(n){var o;let t=(o=n==null?void 0:n.extensions)!=null?o:[],e={},r=[];if(Array.isArray(t)?t.forEach(s=>{Ft(s)?(s.init(this),(s.name||s.name!==q.Anonymous)&&(this[s.name]=s),s instanceof q.Internal&&(re(s.config)||(e[s.name]=s.config))):r.push(s)}):Object.keys(t).forEach(s=>{if(Ft(t[s])){t[s].init(this);let a=t[s];this[s]=a,a instanceof q.Internal&&(re(a.config)||(e[t[s].name]=a.config))}else r.push(t[s])}),r.length)throw yt(r);return e}var ce=class{constructor(t,e){this.apiKey=t;var a;if(!t)throw ht();h.platform==="react-native"&&(e==null?void 0:e.endpoint)&&vt().log();let{defaultEndpoint:r,version:o}=h;this.testMode=!!(e!=null&&e.testMode),this.useStorageCache=!!(e!=null&&e.useStorageCache),this.endpoint=Je((a=e==null?void 0:e.endpoint)!=null?a:r).origin,this.auth=new ve(this),this.user=new be(this),this.wallet=new we(this),this.nft=new Ne(this),this.rpcProvider=new Me(this);let s=yr.call(this,e);this.parameters=me(B(j({API_KEY:this.apiKey,DOMAIN_ORIGIN:window.location?window.location.origin:"",ETH_NETWORK:e==null?void 0:e.network,host:Je(this.endpoint).host,sdk:pt[h.sdkName],version:o,ext:re(s)?void 0:s,locale:(e==null?void 0:e.locale)||"en_US"},h.bundleId?{bundleId:h.bundleId}:{}),{meta:e==null?void 0:e.meta})),this.networkHash=Er(this.apiKey,e==null?void 0:e.network,re(s)?void 0:s),e!=null&&e.deferPreload||this.preload()}get overlay(){if(!ce.__overlays__.has(this.parameters)){let t=new h.ViewController(this.endpoint,this.parameters,this.networkHash);t.init(),ce.__overlays__.set(this.parameters,t)}return ce.__overlays__.get(this.parameters)}preload(){return m(this,null,function*(){yield this.overlay.checkIsReadyForRequest})}},$e=ce;$e.__overlays__=new Map;import{MagicIncomingWindowMessage as le,SDKWarningCode as gr}from"@magic-sdk/types";function Rr(n,t){return t&&Array.isArray(n)?n.find(e=>e.id===t):n}function vr(n,t){var o;let e=(o=t.data.response)==null?void 0:o.id,r=Rr(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 Tr(n,t,e){return m(this,null,function*(){var i;let r=yield y("rt"),o;if(h.platform==="web")try{o=(i=yield y("jwt"))!=null?i:yield Lt()}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 Dt(e);return a&&(s.deviceShare=a),s})}function Ir(n){return m(this,null,function*(){!n.data.rt||(yield M("rt",n.data.rt))})}var Be=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 m(this,null,function*(){return _e((r,o)=>m(this,null,function*(){if(!this.isConnectedToInternet){let l=mt();o(l)}this.isReadyForRequest||(yield this.waitForReady());let s=[],a=Array.isArray(e)?e.map(l=>l.id):[],i=yield Tr(`${t}-${this.parameters}`,e,this.networkHash);yield this._post(i);let c=l=>p=>{var He;let{id:x,response:v}=vr(e,p);if(Ir(p),((He=v==null?void 0:v.payload.error)==null?void 0:He.message)==="User denied account access.")Z();else if(p.data.deviceShare){let{deviceShare:Jt}=p.data;qt(Jt,this.networkHash)}x&&v&&Array.isArray(e)&&a.includes(x)?(s.push(v),s.length===e.length&&(l(),r(s))):x&&v&&!Array.isArray(e)&&x===e.id&&(l(),r(v))},u=this.on(le.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(le.MAGIC_OVERLAY_READY,()=>{this.isReadyForRequest=!0,t(),e()})})}listen(){this.on(le.MAGIC_HIDE_OVERLAY,()=>{this.hideOverlay()}),this.on(le.MAGIC_SHOW_OVERLAY,()=>{this.showOverlay()}),this.on(le.MAGIC_SEND_PRODUCT_ANNOUNCEMENT,t=>{t.data.response.result.product_announcement&&new W(gr.ProductAnnouncement,t.data.response.result.product_announcement).log()})}};export{q as Extension,V as MagicExtensionError,se as MagicExtensionWarning,_ as MagicRPCError,A as MagicSDKError,W as MagicSDKWarning,$e as SDKBase,qe as STORE_KEY_PRIVATE_KEY,Ie as STORE_KEY_PUBLIC_JWK,Oe as TypedEmitter,Be as ViewController,Ts as clearKeys,U as createDeprecationWarning,qr as createDuplicateIframeWarning,Et as createExtensionNotInitializedError,yt as createIncompatibleExtensionsError,gt as createInvalidArgumentError,Lt as createJwt,ft as createMalformedResponseError,ht as createMissingApiKeyError,mt as createModalNotReadyError,k as createPromiEvent,_e as createPromise,vt as createReactNativeEndpointConfigurationWarning,Kn as createSDK,Rt as createSynchronousWeb3MethodWarning,ge as createTypedEmitter,Je as createURL,lt as decodeJSON,me as encodeJSON,Se as getPayloadId,re as isEmpty,dt as isJsonRpcErrorCode,$r as isJsonRpcRequestPayload,ut as isJsonRpcResponsePayload,Cr as isMagicPayloadMethod,Nt as isMajorVersionAtLeast,xt as isPromiEvent,ae as isWebCryptoSupported,ie as storage,Ct as uuid};
5
+ Received: \`${n.received}\``)}function qr(){return new W(Ee.DuplicateIframe,"Duplicate iframes found.")}function Rt(){return new W(Ee.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 vt(){return new W(Ee.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 \`${h.defaultEndpoint}\`. Changing this default behavior will lead to unexpected results and potentially security-threatening bugs.`)}function U(n){let{method:t,removalVersions:e,useInstead:r}=n,o=e[h.sdkName],s=r?` Use \`${r}\` instead.`:"",a=`\`${t}\` will be removed from \`${h.sdkName}\` in version \`${o}\`.${s}`;return new W(Ee.DeprecationNotice,a)}import{MagicPayloadMethod as C,DeviceVerificationEventEmit as $t,LoginWithEmailOTPEventEmit as Re,UpdateEmailEventEmit as z,RecencyCheckEventEmit as Y}from"@magic-sdk/types";import{MagicOutgoingWindowMessage as Yn,MagicIncomingWindowMessage as Zn,MagicPayloadMethod as Qn}from"@magic-sdk/types";function*Bn(){let n=0;for(;;)n<Number.MAX_SAFE_INTEGER?yield++n:n=0}var Hn=Bn();function Se(){return Hn.next().value}var Tt=Symbol("Payload pre-processed by Magic SDK");function It(n){return Object.defineProperty(n,Tt,{value:!0,enumerable:!1}),n}function Vn(n){return!!n[Tt]}function G(n){var t,e,r;return Vn(n)||(n.jsonrpc=(t=n.jsonrpc)!=null?t:"2.0",n.id=Se(),n.method=(e=n.method)!=null?e:"noop",n.params=(r=n.params)!=null?r:[],It(n)),n}function d(n,t=[]){return It({params:t,method:n,jsonrpc:"2.0",id:Se()})}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):ut(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 Pt=Qt(wt()),Oe=class extends Pt.default{};function ge(){let n=new Oe;return{emitter:n,createChainingEmitterMethod:(r,o)=>(...s)=>(n[r].apply(n,s),o),createBoundEmitterMethod:r=>(...o)=>n[r].apply(n,o)}}var Mt=Symbol("isPromiEvent");function xt(n){return!!n[Mt]}function k(n){let t=_e(n),{createBoundEmitterMethod:e,createChainingEmitterMethod:r}=ge(),o=Symbol("Promise.then"),s=Symbol("Promise.catch"),a=Symbol("Promise.finally"),i=(l,p)=>(...x)=>{let v=p[l].apply(p,x);return c(v)},c=l=>Object.assign(l,{[Mt]:!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 _e(n){return new Promise((t,e)=>{let r=n(t,e);Promise.resolve(r).catch(e)})}var P=class{constructor(t){this.sdk=t}get overlay(){return this.sdk.overlay}request(t){let e=this.overlay.post(Yn.MAGIC_HANDLE_REQUEST,G(t)),r=k((s,a)=>{e.then(i=>{if(o(),i.hasError)a(new _(i.payload.error));else if(i.hasResult)s(i.payload.result);else throw ft()}).catch(i=>{o(),a(i)})}),o=this.overlay.on(Zn.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(Qn.IntermediaryEvent,[{payloadId:e,eventType:t,args:o}]);this.request(s)}}};function Nt(n,t){let[e]=n.split(".").map(Number);return e>=t}var K={"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"},ve=class extends P{loginWithMagicLink(t){let e=h.sdkName==="@magic-sdk/react-native"||h.sdkName==="@magic-sdk/react-native-bare"||h.sdkName==="@magic-sdk/react-native-expo";if(e&&Nt(h.version,19))throw new Error("loginWithMagicLink() is deprecated for this package, please utlize a passcode method like loginWithSMS or loginWithEmailOTP instead.");e&&U({method:"auth.loginWithMagicLink()",removalVersions:K,useInstead:"auth.loginWithEmailOTP()"}).log();let{email:r,showUI:o=!0,redirectURI:s,overrides:a}=t,i=d(this.sdk.testMode?C.LoginWithMagicLinkTestMode:C.LoginWithMagicLink,[{email:r,showUI:o,redirectURI:s,overrides:a}]);return this.request(i)}loginWithSMS(t){let{phoneNumber:e}=t,r=d(this.sdk.testMode?C.LoginWithSmsTestMode:C.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?C.LoginWithEmailOTPTestMode:C.LoginWithEmailOTP,[{email:e,showUI:r,deviceCheckUI:o,overrides:s}]),i=this.request(a);return!o&&i&&i.on($t.Retry,()=>{this.createIntermediaryEvent($t.Retry,a.id)()}),!r&&i&&(i.on(Re.VerifyEmailOtp,c=>{this.createIntermediaryEvent(Re.VerifyEmailOtp,a.id)(c)}),i.on(Re.Cancel,()=>{this.createIntermediaryEvent(Re.Cancel,a.id)()})),i}loginWithCredential(t){let e=t!=null?t:"";if(!t&&h.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?C.LoginWithCredentialTestMode:C.LoginWithCredential,[e]);return this.request(r)}setAuthorizationToken(t){let e=d(C.SetAuthorizationToken,[{jwt:t}]);return this.request(e)}updateEmailWithUI(t){let{email:e,showUI:r=!0}=t,o=d(this.sdk.testMode?C.UpdateEmailTestMode:C.UpdateEmail,[{email:e,showUI:r}]),s=this.request(o);return r||(s.on(Y.Retry,()=>{this.createIntermediaryEvent(Y.Retry,o.id)()}),s.on(Y.Cancel,()=>{this.createIntermediaryEvent(Y.Cancel,o.id)()}),s.on(Y.VerifyEmailOtp,a=>{this.createIntermediaryEvent(Y.VerifyEmailOtp,o.id)(a)}),s.on(z.RetryWithNewEmail,a=>{this.createIntermediaryEvent(z.RetryWithNewEmail,o.id)(a)}),s.on(z.Cancel,()=>{this.createIntermediaryEvent(z.Cancel,o.id)()}),s.on(z.VerifyEmailOtp,a=>{this.createIntermediaryEvent(z.VerifyEmailOtp,o.id)(a)})),s}};import{MagicPayloadMethod as R}from"@magic-sdk/types";var ie={};Yt(ie,{clear:()=>er,getItem:()=>y,iterate:()=>ke,key:()=>nr,keys:()=>rr,length:()=>tr,removeItem:()=>N,setItem:()=>M});var Te;function J(n){return(...t)=>m(this,null,function*(){return Te||(Te=yield h.configureStorage()),yield Te.ready(),Te[n](...t)})}var y=J("getItem"),M=J("setItem"),N=J("removeItem"),er=J("clear"),tr=J("length"),nr=J("key"),rr=J("keys"),ke=J("iterate");function Ct(){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 qe="STORE_KEY_PRIVATE_KEY",Ie="STORE_KEY_PUBLIC_JWK",St="ECDSA",sr="P-256",or={name:St,namedCurve:sr};function ae(){let n=typeof window!="undefined"&&!!window.crypto,t=n&&!!window.crypto.subtle;return n&&t}function Ts(){N(Ie),N(qe)}function Lt(){return m(this,null,function*(){let n=yield ir();if(!n){console.info("unable to create public key or webcrypto is unsupported");return}let{subtle:t}=window.crypto,e=yield y(qe);if(!e||!t){console.info("unable to find private key or webcrypto unsupported");return}let r={iat:Math.floor(new Date().getTime()/1e3),jti:Ct()},o={typ:"dpop+jwt",alg:"ES256",jwk:n},s={protected:At(JSON.stringify(o)),claims:At(JSON.stringify(r))},a=cr(`${s.protected}.${s.claims}`),i={name:St,hash:{name:"SHA-256"}},c=ur(new Uint8Array(yield t.sign(i,e,a)));return`${s.protected}.${s.claims}.${c}`})}function ir(){return m(this,null,function*(){if(!ae()){console.info("webcrypto is not supported");return}return(yield y(Ie))||(yield ar()),y(Ie)})}function ar(){return m(this,null,function*(){let{subtle:n}=window.crypto,t=yield n.generateKey(or,!1,["sign"]),e=yield n.exportKey("jwk",t.publicKey);yield M(qe,t.privateKey),yield M(Ie,e)})}function At(n){return Ot(lr(n))}function cr(n){return new TextEncoder().encode(n)}function Ot(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function lr(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,(e,r)=>String.fromCharCode(parseInt(r,16)))}function ur(n){let t="";return n.forEach(e=>{t+=String.fromCharCode(e)}),Ot(t)}var De="ds",We="ek",Ue="iv",Fe="AES-GCM",dr=256;function Z(){return m(this,null,function*(){let n=[];yield ke((t,e,r)=>{e.startsWith(`${De}_`)&&n.push(e)});for(let t of n)yield N(t)})}function _t(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 kt(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 pr(){return m(this,null,function*(){if(!ae()){console.info("webcrypto is not supported");return}let{crypto:n}=window,t=yield y(Ue);return t||n.getRandomValues(new Uint8Array(12))})}function hr(){return m(this,null,function*(){if(!ae()){console.info("webcrypto is not supported");return}let{subtle:n}=window.crypto,t=yield y(We);return t||(yield n.generateKey({name:Fe,length:dr},!1,["encrypt","decrypt"]))})}function qt(n,t){return m(this,null,function*(){let e=yield pr(),r=yield hr();if(!e||!r||!n)return;let o=kt(n),{subtle:s}=window.crypto,a=yield s.encrypt({name:Fe,iv:e},r,o),i=_t(a);yield M(`${De}_${t}`,i),yield M(We,r),yield M(Ue,e)})}function Dt(n){return m(this,null,function*(){let t=yield y(`${De}_${n}`),e=yield y(Ue),r=yield y(We);if(!e||!t||!r||!ae())return;let{subtle:o}=window.crypto,s=yield o.decrypt({name:Fe,iv:e},r,kt(t));return _t(s)})}function Je(n,t){return t?new URL(n,t):new URL(n)}var be=class extends P{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?R.GetIdTokenTestMode:R.GetIdToken,[e]);return this.request(r)}generateIdToken(e){let r=d(this.sdk.testMode?R.GenerateIdTokenTestMode:R.GenerateIdToken,[e]);return this.request(r)}getInfo(){return m(this,null,function*(){let e=yield y(this.localForageKey),r=d(R.GetInfo,[{walletType:e}]);return this.request(r)})}isLoggedIn(){return k((e,r)=>m(this,null,function*(){try{let o=!1;this.sdk.useStorageCache&&(o=(yield y(this.localForageIsLoggedInKey))==="true",o&&e(!0));let s=d(this.sdk.testMode?R.IsLoggedInTestMode:R.IsLoggedIn),a=yield this.request(s);this.sdk.useStorageCache&&(a?M(this.localForageIsLoggedInKey,!0):N(this.localForageIsLoggedInKey),o&&!a&&this.emitUserLoggedOut(!0)),e(a)}catch(o){r(o)}}))}logout(){return N(this.localForageKey),N(this.localForageIsLoggedInKey),Z(),k((e,r)=>m(this,null,function*(){try{let o=d(this.sdk.testMode?R.LogoutTestMode:R.Logout),s=yield this.request(o);this.sdk.useStorageCache&&this.emitUserLoggedOut(s),e(s)}catch(o){r(o)}}))}requestInfoWithUI(e){let r=d(R.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}showSettings(e){let r=d(this.sdk.testMode?R.UserSettingsTestMode:R.UserSettings,[e]);return this.request(r)}recoverAccount(e){let r=d(this.sdk.testMode?R.RecoverAccountTestMode:R.RecoverAccount,[e]);return this.request(r)}revealPrivateKey(){let e=d(R.RevealPK);return this.request(e)}getMetadata(){U({method:"user.getMetadata()",removalVersions:K,useInstead:"user.getInfo()"}).log();let e=d(this.sdk.testMode?R.GetMetadataTestMode:R.GetMetadata);return this.request(e)}onUserLoggedOut(e){this.userLoggedOutCallbacks.push(e)}emitUserLoggedOut(e){this.userLoggedOutCallbacks.forEach(r=>{r(e)})}};import{Events as Ge,MagicPayloadMethod as $,Wallets as S}from"@magic-sdk/types";var we=class extends P{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}connectWithUI(){let e=k((r,o)=>m(this,null,function*(){try{if(this.isMetaMaskBrowser()&&(yield this.isWalletEnabled(S.MetaMask))){let u=yield this.autoConnectIfWalletBrowser(S.MetaMask);r(u);return}if(this.isCoinbaseWalletBrowser()&&(yield this.isWalletEnabled(S.CoinbaseWallet))){let u=yield this.autoConnectIfWalletBrowser(S.CoinbaseWallet);r(u);return}let s=this.getUserEnv(),a=d($.Login,[s]),i=this.request(a);i.on(Ge.WalletSelected,u=>this.handleWalletSelected(B(j({},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($.ShowUI))}showAddress(){return this.request(d($.ShowAddress))}showSendTokensUI(){return this.request(d($.ShowSendTokensUI))}showOnRamp(){return this.request(d($.ShowOnRamp))}showNFTs(){return this.request(d($.ShowNFTs))}showBalances(){return this.request(d($.ShowBalances))}sendGaslessTransaction(e,r){return this.request(d($.SendGaslessTransaction,[e,r]))}getInfo(){return m(this,null,function*(){U({method:"wallet.getInfo()",removalVersions:K,useInstead:"user.getInfo()"}).log();let e=yield y(this.localForageKey),r=d($.GetInfo,[{walletType:e}]);return this.request(r)})}disconnect(){U({method:"wallet.disconnect()",removalVersions:K,useInstead:"user.logout()"}).log(),N(this.localForageKey),Z();let e=d($.Disconnect);return this.request(e)}requestUserInfoWithUI(e){U({method:"wallet.requestUserInfoWithUI()",removalVersions:K,useInstead:"user.requestUserInfoWithUI()"}).log();let r=d($.RequestUserInfoWithUI,e?[e]:[]);return this.request(r)}getProvider(){return m(this,null,function*(){switch(yield y(this.localForageKey)){case S.MetaMask:return this.getMetaMaskProvider();case S.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 S.MetaMask:return this.connectToMetaMask();case S.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 m(this,null,function*(){try{let r=yield this.connectToThirdPartyWallet(e.wallet);yield M(this.localForageKey,e.wallet),this.createIntermediaryEvent(Ge.WalletConnected,e.payloadId)(r)}catch(r){console.error(r),this.createIntermediaryEvent(Ge.WalletRejected,e.payloadId)()}})}autoConnectIfWalletBrowser(e){return m(this,null,function*(){let r;e===S.MetaMask&&(r=yield this.getMetaMaskProvider().request({method:"eth_requestAccounts"})),e===S.CoinbaseWallet&&(r=yield this.getCoinbaseProvider().request({method:"eth_requestAccounts"})),yield M(this.localForageKey,e);let o=d($.AutoConnect,[{wallet:e,address:r}]);return this.request(o)})}};import{MagicOutgoingWindowMessage as Wt,MagicPayloadMethod as mr}from"@magic-sdk/types";var{createBoundEmitterMethod:Pe,createChainingEmitterMethod:Q}=ge(),Me=class extends P{constructor(){super(...arguments);this.isMagic=!0;this.on=Q("on",this);this.once=Q("once",this);this.addListener=Q("addListener",this);this.off=Q("off",this);this.removeListener=Q("removeListener",this);this.removeAllListeners=Q("removeAllListeners",this);this.emit=Pe("emit");this.eventNames=Pe("eventNames");this.listeners=Pe("listeners");this.listenerCount=Pe("listenerCount")}sendAsync(e,r){if(!r)throw gt({procedure:"Magic.rpcProvider.sendAsync",argument:1,expected:"function",received:r===null?"null":typeof r});if(Array.isArray(e))this.overlay.post(Wt.MAGIC_HANDLE_REQUEST,e.map(o=>{let s=G(o);return this.prefixPayloadMethodForTestMode(s),s})).then(o=>{r(null,o.map(s=>B(j({},s.payload),{error:s.hasError?new _(s.payload.error):null})))});else{let o=G(e);this.prefixPayloadMethodForTestMode(o),this.overlay.post(Wt.MAGIC_HANDLE_REQUEST,o).then(s=>{r(s.hasError?new _(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=Rt();return o.log(),new F(e).applyError({code:-32603,message:o.rawMessage}).payload}enable(){let e=d(mr.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 Ut=["request","overlay","sdk"];function fr(n){let t=Object.getPrototypeOf(n),e=[t];for(;t!==P.prototype;)t=Object.getPrototypeOf(t),e.push(t);return e}var xe=class extends P{constructor(){super(void 0);this.__sdk_access_field_descriptors__=new Map;this.__is_initialized__=!1;this.utils={createPromiEvent:k,isPromiEvent:xt,encodeJSON:me,decodeJSON:lt,createJsonRpcRequestPayload:d,standardizeJsonRpcRequestPayload:G,storage:ie};let e=[this,...fr(this)];Ut.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 Et(r)}}))})}init(e){this.__is_initialized__||(Ut.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 se(this,"DEPRECATION_NOTICE",i)}createWarning(e,r){return new se(this,e,r)}createError(e,r,o){return new V(this,e,r,o)}},Ke=class extends xe{},q=class extends xe{};q.Internal=Ke,q.Anonymous="anonymous extension";import{MagicPayloadMethod as je}from"@magic-sdk/types";var Ne=class extends P{purchase(t){let e=d(je.NFTPurchase,[t]);return this.request(e)}checkout(t){let e=d(je.NFTCheckout,[t]);return this.request(e)}transfer(t){let e=d(je.NFTTransfer,[t]);return this.request(e)}};function Ft(n){return n.compat&&n.compat[h.sdkName]!=null?typeof n.compat[h.sdkName]=="string"?at(ct(h.version),n.compat[h.sdkName]):!!n.compat[h.sdkName]:!0}function Er(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 yr(n){var o;let t=(o=n==null?void 0:n.extensions)!=null?o:[],e={},r=[];if(Array.isArray(t)?t.forEach(s=>{Ft(s)?(s.init(this),(s.name||s.name!==q.Anonymous)&&(this[s.name]=s),s instanceof q.Internal&&(re(s.config)||(e[s.name]=s.config))):r.push(s)}):Object.keys(t).forEach(s=>{if(Ft(t[s])){t[s].init(this);let a=t[s];this[s]=a,a instanceof q.Internal&&(re(a.config)||(e[t[s].name]=a.config))}else r.push(t[s])}),r.length)throw yt(r);return e}var ce=class{constructor(t,e){this.apiKey=t;var a;if(!t)throw ht();h.platform==="react-native"&&(e==null?void 0:e.endpoint)&&vt().log();let{defaultEndpoint:r,version:o}=h;this.testMode=!!(e!=null&&e.testMode),this.useStorageCache=!!(e!=null&&e.useStorageCache),this.endpoint=Je((a=e==null?void 0:e.endpoint)!=null?a:r).origin,this.auth=new ve(this),this.user=new be(this),this.wallet=new we(this),this.nft=new Ne(this),this.rpcProvider=new Me(this);let s=yr.call(this,e);this.parameters=me(B(j({API_KEY:this.apiKey,DOMAIN_ORIGIN:window.location?window.location.origin:"",ETH_NETWORK:e==null?void 0:e.network,host:Je(this.endpoint).host,sdk:pt[h.sdkName],version:o,ext:re(s)?void 0:s,locale:(e==null?void 0:e.locale)||"en_US"},h.bundleId?{bundleId:h.bundleId}:{}),{meta:e==null?void 0:e.meta})),this.networkHash=Er(this.apiKey,e==null?void 0:e.network,re(s)?void 0:s),e!=null&&e.deferPreload||this.preload()}get overlay(){if(!ce.__overlays__.has(this.parameters)){let t=new h.ViewController(this.endpoint,this.parameters,this.networkHash);t.init(),ce.__overlays__.set(this.parameters,t)}return ce.__overlays__.get(this.parameters)}preload(){return m(this,null,function*(){yield this.overlay.checkIsReadyForRequest})}},$e=ce;$e.__overlays__=new Map;import{MagicIncomingWindowMessage as le,SDKWarningCode as gr}from"@magic-sdk/types";function Rr(n,t){return t&&Array.isArray(n)?n.find(e=>e.id===t):n}function vr(n,t){var o;let e=(o=t.data.response)==null?void 0:o.id,r=Rr(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 Tr(n,t,e){return m(this,null,function*(){var i;let r=yield y("rt"),o;if(h.platform==="web")try{o=(i=yield y("jwt"))!=null?i:yield Lt()}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 Dt(e);return a&&(s.deviceShare=a),s})}function Ir(n){return m(this,null,function*(){!n.data.rt||(yield M("rt",n.data.rt))})}var Be=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 m(this,null,function*(){return _e((r,o)=>m(this,null,function*(){if(!this.isConnectedToInternet){let l=mt();o(l)}this.isReadyForRequest||(yield this.waitForReady());let s=[],a=Array.isArray(e)?e.map(l=>l.id):[],i=yield Tr(`${t}-${this.parameters}`,e,this.networkHash);yield this._post(i);let c=l=>p=>{var He;let{id:x,response:v}=vr(e,p);if(Ir(p),((He=v==null?void 0:v.payload.error)==null?void 0:He.message)==="User denied account access.")Z();else if(p.data.deviceShare){let{deviceShare:Jt}=p.data;qt(Jt,this.networkHash)}x&&v&&Array.isArray(e)&&a.includes(x)?(s.push(v),s.length===e.length&&(l(),r(s))):x&&v&&!Array.isArray(e)&&x===e.id&&(l(),r(v))},u=this.on(le.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(le.MAGIC_OVERLAY_READY,()=>{this.isReadyForRequest=!0,t(),e()})})}listen(){this.on(le.MAGIC_HIDE_OVERLAY,()=>{this.hideOverlay()}),this.on(le.MAGIC_SHOW_OVERLAY,()=>{this.showOverlay()}),this.on(le.MAGIC_SEND_PRODUCT_ANNOUNCEMENT,t=>{t.data.response.result.product_announcement&&new W(gr.ProductAnnouncement,t.data.response.result.product_announcement).log()})}};export{q as Extension,V as MagicExtensionError,se as MagicExtensionWarning,_ as MagicRPCError,A as MagicSDKError,W as MagicSDKWarning,$e as SDKBase,qe as STORE_KEY_PRIVATE_KEY,Ie as STORE_KEY_PUBLIC_JWK,Oe as TypedEmitter,Be as ViewController,Ts as clearKeys,U as createDeprecationWarning,qr as createDuplicateIframeWarning,Et as createExtensionNotInitializedError,yt as createIncompatibleExtensionsError,gt as createInvalidArgumentError,Lt as createJwt,ft as createMalformedResponseError,ht as createMissingApiKeyError,mt as createModalNotReadyError,k as createPromiEvent,_e as createPromise,vt as createReactNativeEndpointConfigurationWarning,Kn as createSDK,Rt as createSynchronousWeb3MethodWarning,ge as createTypedEmitter,Je as createURL,lt as decodeJSON,me as encodeJSON,Se as getPayloadId,re as isEmpty,dt as isJsonRpcErrorCode,$r as isJsonRpcRequestPayload,ut as isJsonRpcResponsePayload,Cr as isMagicPayloadMethod,Nt as isMajorVersionAtLeast,xt as isPromiEvent,ae as isWebCryptoSupported,ie as storage,Ct as uuid};
6
6
  //# sourceMappingURL=index.js.map