@magic-sdk/provider 20.0.0 → 20.0.1-canary.522b998.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 Nt=Object.create;var re=Object.defineProperty,$t=Object.defineProperties,At=
2
2
  - Extension \`${t.name}\` supports version(s) \`${r}\``:r||(e+=`
3
3
  - Extension \`${t.name}\` does not support ${m.platform} environments.`)}),new A(V.IncompatibleExtensions,e)}function ct(n){let e=t=>{let r=t+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(V.InvalidArgument,`Invalid ${e(n.argument)} argument given to \`${n.procedure}\`.
4
4
  Expected: \`${n.expected}\`
5
- Received: \`${n.received}\``)}function vr(){return new j(de.DuplicateIframe,"Duplicate iframes found.")}function lt(){return new j(de.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 ut(){return new j(de.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:e,removalVersions:t,useInstead:r}=n,o=t[m.sdkName],s=r?` Use \`${r}\` instead.`:"",a=`\`${e}\` will be removed from \`${m.sdkName}\` in version \`${o}\`.${s}`;return new j(de.DeprecationNotice,a)}import{MagicPayloadMethod as $,DeviceVerificationEventEmit as Rt,LoginWithEmailOTPEventEmit as he}from"@magic-sdk/types";import{MagicOutgoingWindowMessage as kn,MagicIncomingWindowMessage as qn,MagicPayloadMethod as Dn}from"@magic-sdk/types";function*Cn(){let n=0;for(;;)n<Number.MAX_SAFE_INTEGER?yield++n:n=0}var Sn=Cn();function Ne(){return Sn.next().value}var dt=Symbol("Payload pre-processed by Magic SDK");function pt(n){return Object.defineProperty(n,dt,{value:!0,enumerable:!1}),n}function Ln(n){return!!n[dt]}function F(n){var e,t,r;return Ln(n)||(n.jsonrpc=(e=n.jsonrpc)!=null?e:"2.0",n.id=Ne(),n.method=(t=n.method)!=null?t:"noop",n.params=(r=n.params)!=null?r:[],pt(n)),n}function d(n,e=[]){return pt({params:e,method:n,jsonrpc:"2.0",id:Ne()})}var W=class{constructor(e){e instanceof W?(this._jsonrpc=e.payload.jsonrpc,this._id=e.payload.id,this._result=e.payload.result,this._error=e.payload.error):tt(e)?(this._jsonrpc=e.jsonrpc,this._id=e.id,this._result=e.result,this._error=e.error):(this._jsonrpc=e.jsonrpc,this._id=e.id,this._result=void 0,this._error=void 0)}applyError(e){return this._error=e,this}applyResult(e){return this._result=e,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 Et=Dt(ht()),Ae=class extends Et.default{};function me(){let n=new Ae;return{emitter:n,createChainingEmitterMethod:(r,o)=>(...s)=>(n[r].apply(n,s),o),createBoundEmitterMethod:r=>(...o)=>n[r].apply(n,o)}}var ft=Symbol("isPromiEvent");function gt(n){return!!n[ft]}function X(n){let e=Ce(n),{createBoundEmitterMethod:t,createChainingEmitterMethod:r}=me(),o=Symbol("Promise.then"),s=Symbol("Promise.catch"),a=Symbol("Promise.finally"),i=(u,p)=>(...P)=>{let q=p[u].apply(p,P);return c(q)},c=u=>Object.assign(u,{[ft]:!0,[o]:u[o]||u.then,[s]:u[s]||u.catch,[a]:u[a]||u.finally,then:i(o,u),catch:i(s,u),finally:i(a,u),on:r("on",u),once:r("once",u),addListener:r("addListener",u),off:r("off",u),removeListener:r("removeListener",u),removeAllListeners:r("removeAllListeners",u),emit:t("emit"),eventNames:t("eventNames"),listeners:t("listeners"),listenerCount:t("listenerCount")}),l=c(e.then(u=>(l.emit("done",u),l.emit("settled"),u),u=>{throw l.emit("error",u),l.emit("settled"),u}));return l}function Ce(n){return new Promise((e,t)=>{let r=n(e,t);Promise.resolve(r).catch(t)})}var b=class{constructor(e){this.sdk=e}get overlay(){return this.sdk.overlay}request(e){let t=this.overlay.post(kn.MAGIC_HANDLE_REQUEST,F(e)),r=X((s,a)=>{t.then(i=>{if(o(),i.hasError)a(new O(i.payload.error));else if(i.hasResult)s(i.payload.result);else throw ot()}).catch(i=>{o(),a(i)})}),o=this.overlay.on(qn.MAGIC_HANDLE_EVENT,s=>{var i;let{response:a}=s.data;if(a.id===e.id&&((i=a.result)==null?void 0:i.event)){let{event:c,params:l=[]}=a.result;r.emit(c,...l)}});return r}createIntermediaryEvent(e,t){return o=>{let s=d(Dn.IntermediaryEvent,[{payloadId:t,eventType:e,args:o}]);this.request(s)}}};function yt(n,e){let[t]=n.split(".").map(Number);return t>=e}var M={"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"},Ee=class extends b{loginWithMagicLink(e){let t=m.sdkName==="@magic-sdk/react-native"||m.sdkName==="@magic-sdk/react-native-bare"||m.sdkName==="@magic-sdk/react-native-expo";if(t&&yt(m.version,19))throw new Error("loginWithMagicLink() is deprecated for this package, please utlize a passcode method like loginWithSMS or loginWithEmailOTP instead.");w({method:"auth.loginWithMagicLink()",removalVersions:M,useInstead:t?"@magic-ext/auth auth.loginWithEmailOTP()":"@magic-ext/auth auth.loginWithMagicLink()"}).log();let{email:r,showUI:o=!0,redirectURI:s}=e,a=d(this.sdk.testMode?$.LoginWithMagicLinkTestMode:$.LoginWithMagicLink,[{email:r,showUI:o,redirectURI:s}]);return this.request(a)}loginWithSMS(e){w({method:"auth.loginWithSMS()",removalVersions:M,useInstead:"@magic-ext/auth auth.loginWithSMS()"}).log();let{phoneNumber:t}=e,r=d(this.sdk.testMode?$.LoginWithSmsTestMode:$.LoginWithSms,[{phoneNumber:t,showUI:!0}]);return this.request(r)}loginWithEmailOTP(e){let{email:t,showUI:r,deviceCheckUI:o}=e,s=d(this.sdk.testMode?$.LoginWithEmailOTPTestMode:$.LoginWithEmailOTP,[{email:t,showUI:r,deviceCheckUI:o}]),a=this.request(s);return!o&&a&&a.on(Rt.Retry,()=>{this.createIntermediaryEvent(Rt.Retry,s.id)()}),!r&&a&&(a.on(he.VerifyEmailOtp,i=>{this.createIntermediaryEvent(he.VerifyEmailOtp,s.id)(i)}),a.on(he.Cancel,()=>{this.createIntermediaryEvent(he.Cancel,s.id)()})),a}loginWithCredential(e){w({method:"auth.loginWithCredential()",removalVersions:M,useInstead:"@magic-ext/auth auth.loginWithCredential()"}).log();let t=e!=null?e:"";if(!e&&m.platform==="web"){t=window.location.search;let o=window.location.origin+window.location.pathname;window.history.replaceState(null,"",o)}let r=d(this.sdk.testMode?$.LoginWithCredentialTestMode:$.LoginWithCredential,[t]);return this.request(r)}setAuthorizationToken(e){w({method:"auth.setAuthorizationToken()",removalVersions:M,useInstead:"@magic-ext/auth auth.setAuthorizationToken()"}).log();let t=d($.SetAuthorizationToken,[{jwt:e}]);return this.request(t)}updateEmailWithUI(e){w({method:"auth.updateEmailWithUI()",removalVersions:M,useInstead:"@magic-ext/auth auth.updateEmailWithUI()"}).log();let{email:t,showUI:r=!0}=e,o=d(this.sdk.testMode?$.UpdateEmailTestMode:$.UpdateEmail,[{email:t,showUI:r}]);return this.request(o)}};import{MagicPayloadMethod as g}from"@magic-sdk/types";var te={};kt(te,{clear:()=>Wn,getItem:()=>x,iterate:()=>Gn,key:()=>Jn,keys:()=>Fn,length:()=>Un,removeItem:()=>J,setItem:()=>_});var fe;function U(n){return(...e)=>E(this,null,function*(){return fe||(fe=yield m.configureStorage()),yield fe.ready(),fe[n](...e)})}var x=U("getItem"),_=U("setItem"),J=U("removeItem"),Wn=U("clear"),Un=U("length"),Jn=U("key"),Fn=U("keys"),Gn=U("iterate");var ge=class extends b{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}getIdToken(t){let r=d(this.sdk.testMode?g.GetIdTokenTestMode:g.GetIdToken,[t]);return this.request(r)}generateIdToken(t){let r=d(this.sdk.testMode?g.GenerateIdTokenTestMode:g.GenerateIdToken,[t]);return this.request(r)}getInfo(){return E(this,null,function*(){let t=yield x(this.localForageKey),r=d(g.GetInfo,[{walletType:t}]);return this.request(r)})}isLoggedIn(){let t=d(this.sdk.testMode?g.IsLoggedInTestMode:g.IsLoggedIn);return this.request(t)}logout(){J(this.localForageKey);let t=d(this.sdk.testMode?g.LogoutTestMode:g.Logout);return this.request(t)}requestInfoWithUI(t){let r=d(g.RequestUserInfoWithUI,t?[t]:[]);return this.request(r)}showSettings(t){let r=d(this.sdk.testMode?g.UserSettingsTestMode:g.UserSettings,[t]);return this.request(r)}recoverAccount(t){let r=d(this.sdk.testMode?g.RecoverAccountTestMode:g.RecoverAccount,[t]);return this.request(r)}getMetadata(){w({method:"user.getMetadata()",removalVersions:M,useInstead:"user.getInfo()"}).log();let t=d(this.sdk.testMode?g.GetMetadataTestMode:g.GetMetadata);return this.request(t)}updateEmail(t){w({method:"user.updateEmail()",removalVersions:M,useInstead:"auth.updateEmailWithUI()"}).log();let{email:r,showUI:o=!0}=t,s=d(this.sdk.testMode?g.UpdateEmailTestMode:g.UpdateEmail,[{email:r,showUI:o}]);return this.request(s)}};import{Events as _e,MagicPayloadMethod as N,Wallets as C}from"@magic-sdk/types";function Se(n,e){return e?new URL(n,e):new URL(n)}function vt(){let n=window.crypto.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&191|128;let e="";return e+=n[0].toString(16),e+=n[1].toString(16),e+=n[2].toString(16),e+=n[3].toString(16),e+="-",e+=n[4].toString(16),e+=n[5].toString(16),e+="-",e+=n[6].toString(16),e+=n[7].toString(16),e+="-",e+=n[8].toString(16),e+=n[9].toString(16),e+="-",e+=n[10].toString(16),e+=n[11].toString(16),e+=n[12].toString(16),e+=n[13].toString(16),e+=n[14].toString(16),e+=n[15].toString(16),e}var Le="STORE_KEY_PRIVATE_KEY",ye="STORE_KEY_PUBLIC_JWK",Oe="ECDSA",It="P-256",Kn={name:Oe,namedCurve:It},jn={name:Oe,namedCurve:It};function Rs(){J(ye),J(Le)}function bt(){return E(this,null,function*(){let n=yield Bn();if(!n){console.info("unable to create public key or webcrypto is unsupported");return}let{subtle:e}=window.crypto,t=yield x(Le);if(!t||!e){console.info("unable to find private key or webcrypto unsupported");return}let r={iat:Math.floor(new Date().getTime()/1e3),jti:vt()},o={typ:"dpop+jwt",alg:"ES256",jwk:n},s={protected:Tt(JSON.stringify(o)),claims:Tt(JSON.stringify(r))},a=Hn(`${s.protected}.${s.claims}`),i={name:Oe,hash:{name:"SHA-256"}},c=Yn(new Uint8Array(yield e.sign(i,t,a)));return`${s.protected}.${s.claims}.${c}`})}function Bn(){return E(this,null,function*(){if(!Xn()){console.info("webcrypto is not supported");return}return(yield x(ye))||(yield Vn()),x(ye)})}function Vn(){return E(this,null,function*(){let n=null,{subtle:e}=window.crypto,t=yield e.generateKey(Kn,!0,["sign"]),r=yield e.exportKey("jwk",t.privateKey);n=yield e.exportKey("jwk",t.publicKey);let o=yield e.importKey("jwk",r,jn,!1,["sign"]);yield _(Le,o),yield _(ye,n)})}function Xn(){let n=typeof window!="undefined"&&!!window.crypto,e=n&&!!window.crypto.subtle;return n&&e}function Tt(n){return Pt(zn(n))}function Hn(n){return new TextEncoder().encode(n)}function Pt(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function zn(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16)))}function Yn(n){let e="";return n.forEach(t=>{e+=String.fromCharCode(t)}),Pt(e)}var Re=class extends b{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}connectWithUI(){let t=X((r,o)=>E(this,null,function*(){try{if(this.isMetaMaskBrowser()&&(yield this.isWalletEnabled(C.MetaMask))){let l=yield this.autoConnectIfWalletBrowser(C.MetaMask);r(l);return}if(this.isCoinbaseWalletBrowser()&&(yield this.isWalletEnabled(C.CoinbaseWallet))){let l=yield this.autoConnectIfWalletBrowser(C.CoinbaseWallet);r(l);return}let s=this.getUserEnv(),a=d(N.Login,[s]),i=this.request(a);i.on(_e.WalletSelected,l=>this.handleWalletSelected(se(G({},l),{payloadId:a.id}))),i.on("id-token-created",l=>{t.emit("id-token-created",l)});let c=yield i;c.error&&o(c),r(c)}catch(s){o(s)}}));return t}showUI(){return this.request(d(N.ShowUI))}showAddress(){return this.request(d(N.ShowAddress))}showSendTokensUI(){return this.request(d(N.ShowSendTokensUI))}showOnRamp(){return this.request(d(N.ShowOnRamp))}showNFTs(){return this.request(d(N.ShowNFTs))}showBalances(){return this.request(d(N.ShowBalances))}sendGaslessTransaction(t,r){return this.request(d(N.SendGaslessTransaction,[[t,r]]))}getInfo(){return E(this,null,function*(){w({method:"wallet.getInfo()",removalVersions:M,useInstead:"user.getInfo()"}).log();let t=yield x(this.localForageKey),r=d(N.GetInfo,[{walletType:t}]);return this.request(r)})}disconnect(){w({method:"wallet.disconnect()",removalVersions:M,useInstead:"user.logout()"}).log(),J(this.localForageKey);let t=d(N.Disconnect);return this.request(t)}requestUserInfoWithUI(t){w({method:"wallet.requestUserInfoWithUI()",removalVersions:M,useInstead:"user.requestUserInfoWithUI()"}).log();let r=d(N.RequestUserInfoWithUI,t?[t]:[]);return this.request(r)}getProvider(){return E(this,null,function*(){switch(yield x(this.localForageKey)){case C.MetaMask:return this.getMetaMaskProvider();case C.CoinbaseWallet:return this.getCoinbaseProvider();default:return this.sdk.rpcProvider}})}isMetaMaskInstalled(){var t,r,o;return((t=window.ethereum)==null?void 0:t.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 t,r;return((r=(t=window.ethereum)==null?void 0:t.providers)==null?void 0:r.find(o=>o==null?void 0:o.isMetaMask))||window.ethereum}connectToMetaMask(){if(this.isMobile()&&!this.isMetaMaskInstalled()){let t=`https://metamask.app.link/dapp/${window.location.href.replace(/(^\w+:|^)\/\//,"")}`;window.location.href=t}return this.getMetaMaskProvider().request({method:"eth_requestAccounts"})}isCoinbaseWalletInstalled(){var t,r,o;return((t=window.ethereum)==null?void 0:t.isCoinbaseWallet)||!!((o=(r=window.ethereum)==null?void 0:r.providers)!=null&&o.find(s=>s==null?void 0:s.isCoinbaseWallet))}isCoinbaseWalletBrowser(){var t;return!!((t=window.ethereum)!=null&&t.isCoinbaseBrowser)}getCoinbaseProvider(){var t,r;return((r=(t=window.ethereum)==null?void 0:t.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(t){switch(t){case C.MetaMask:return this.connectToMetaMask();case C.CoinbaseWallet:return this.connectToCoinbaseWallet();default:throw new Error(`Invalid provider: ${t}. Must be one of "metamask" or "coinbase_wallet".`)}}isWalletEnabled(t){let r=d("mc_is_wallet_enabled",[{wallet:t}]);return this.request(r)}handleWalletSelected(t){return E(this,null,function*(){try{let r=yield this.connectToThirdPartyWallet(t.wallet);yield _(this.localForageKey,t.wallet),this.createIntermediaryEvent(_e.WalletConnected,t.payloadId)(r)}catch(r){console.error(r),this.createIntermediaryEvent(_e.WalletRejected,t.payloadId)()}})}autoConnectIfWalletBrowser(t){return E(this,null,function*(){let r;t===C.MetaMask&&(r=yield this.getMetaMaskProvider().request({method:"eth_requestAccounts"})),t===C.CoinbaseWallet&&(r=yield this.getCoinbaseProvider().request({method:"eth_requestAccounts"})),yield _(this.localForageKey,t);let o=d(N.AutoConnect,[{wallet:t,address:r}]);return this.request(o)})}};import{MagicOutgoingWindowMessage as wt,MagicPayloadMethod as Zn}from"@magic-sdk/types";var{createBoundEmitterMethod:ve,createChainingEmitterMethod:H}=me(),Te=class extends b{constructor(){super(...arguments);this.isMagic=!0;this.on=H("on",this);this.once=H("once",this);this.addListener=H("addListener",this);this.off=H("off",this);this.removeListener=H("removeListener",this);this.removeAllListeners=H("removeAllListeners",this);this.emit=ve("emit");this.eventNames=ve("eventNames");this.listeners=ve("listeners");this.listenerCount=ve("listenerCount")}sendAsync(t,r){if(!r)throw ct({procedure:"Magic.rpcProvider.sendAsync",argument:1,expected:"function",received:r===null?"null":typeof r});if(Array.isArray(t))this.overlay.post(wt.MAGIC_HANDLE_REQUEST,t.map(o=>{let s=F(o);return this.prefixPayloadMethodForTestMode(s),s})).then(o=>{r(null,o.map(s=>se(G({},s.payload),{error:s.hasError?new O(s.payload.error):null})))});else{let o=F(t);this.prefixPayloadMethodForTestMode(o),this.overlay.post(wt.MAGIC_HANDLE_REQUEST,o).then(s=>{r(s.hasError?new O(s.payload.error):null,s.payload)})}}send(t,r){if(typeof t=="string"){let s=d(t,Array.isArray(r)?r:[]);return this.request(s)}if(Array.isArray(t)||!!r){this.sendAsync(t,r);return}let o=lt();return o.log(),new W(t).applyError({code:-32603,message:o.rawMessage}).payload}enable(){let t=d(Zn.Login);return this.request(t)}request(t){return this.prefixPayloadMethodForTestMode(t),super.request(t)}prefixPayloadMethodForTestMode(t){let r="testMode/eth/";this.sdk.testMode&&(t.method=`${r}${t.method}`)}};var Mt=["request","overlay","sdk"];function Qn(n){let e=Object.getPrototypeOf(n),t=[e];for(;e!==b.prototype;)e=Object.getPrototypeOf(e),t.push(e);return t}var Ie=class extends b{constructor(){super(void 0);this.__sdk_access_field_descriptors__=new Map;this.__is_initialized__=!1;this.utils={createPromiEvent:X,isPromiEvent:gt,encodeJSON:ce,decodeJSON:et,createJsonRpcRequestPayload:d,standardizeJsonRpcRequestPayload:F,storage:te};let t=[this,...Qn(this)];Mt.forEach(r=>{let o=t.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 it(r)}}))})}init(t){this.__is_initialized__||(Mt.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=t,this.__is_initialized__=!0)}createDeprecationWarning(t){let{method:r,removalVersion:o,useInstead:s}=t,a=s?` Use \`${s}\` instead.`:"",i=`\`${r}\` will be removed from this Extension in version \`${o}\`.${a}`;return new Q(this,"DEPRECATION_NOTICE",i)}createWarning(t,r){return new Q(this,t,r)}createError(t,r,o){return new B(this,t,r,o)}},ke=class extends Ie{},k=class extends Ie{};k.Internal=ke,k.Anonymous="anonymous extension";import{MagicPayloadMethod as qe}from"@magic-sdk/types";var be=class extends b{purchase(e){let t=d(qe.NFTPurchase,[e]);return this.request(t)}checkout(e){let t=d(qe.NFTCheckout,[e]);return this.request(t)}transfer(e){let t=d(qe.NFTTransfer,[e]);return this.request(t)}};function xt(n){return n.compat&&n.compat[m.sdkName]!=null?typeof n.compat[m.sdkName]=="string"?Ze(Qe(m.version),n.compat[m.sdkName]):!!n.compat[m.sdkName]:!0}function er(n){var o;let e=(o=n==null?void 0:n.extensions)!=null?o:[],t={},r=[];if(Array.isArray(e)?e.forEach(s=>{xt(s)?(s.init(this),(s.name||s.name!==k.Anonymous)&&(this[s.name]=s),s instanceof k.Internal&&(ue(s.config)||(t[s.name]=s.config))):r.push(s)}):Object.keys(e).forEach(s=>{if(xt(e[s])){e[s].init(this);let a=e[s];this[s]=a,a instanceof k.Internal&&(ue(a.config)||(t[e[s].name]=a.config))}else r.push(e[s])}),r.length)throw at(r);return t}var ne=class{constructor(e,t){this.apiKey=e;var a;if(!e)throw st();m.platform==="react-native"&&(t==null?void 0:t.endpoint)&&ut().log();let{defaultEndpoint:r,version:o}=m;this.testMode=!!(t!=null&&t.testMode),this.endpoint=Se((a=t==null?void 0:t.endpoint)!=null?a:r).origin,this.auth=new Ee(this),this.user=new ge(this),this.wallet=new Re(this),this.nft=new be(this),this.rpcProvider=new Te(this);let s=er.call(this,t);this.parameters=ce(G({API_KEY:this.apiKey,DOMAIN_ORIGIN:window.location?window.location.origin:"",ETH_NETWORK:t==null?void 0:t.network,host:Se(this.endpoint).host,sdk:rt[m.sdkName],version:o,ext:ue(s)?void 0:s,locale:(t==null?void 0:t.locale)||"en_US"},m.bundleId?{bundleId:m.bundleId}:{}))}get overlay(){if(!ne.__overlays__.has(this.parameters)){let e=new m.ViewController(this.endpoint,this.parameters);e.init(),ne.__overlays__.set(this.parameters,e)}return ne.__overlays__.get(this.parameters)}preload(){return E(this,null,function*(){yield this.overlay.ready})}},Pe=ne;Pe.__overlays__=new Map;import{MagicIncomingWindowMessage as we}from"@magic-sdk/types";function tr(n,e){return e&&Array.isArray(n)?n.find(t=>t.id===e):n}function nr(n,e){var o;let t=(o=e.data.response)==null?void 0:o.id,r=tr(n,t);if(t&&r){let s=new W(r).applyResult(e.data.response.result).applyError(e.data.response.error);return{id:t,response:s}}return{}}function rr(n,e){return E(this,null,function*(){let t=yield x("rt"),r;if(m.platform==="web")try{r=yield bt()}catch(o){console.error("webcrypto error",o)}return r?t?{msgType:n,payload:e,jwt:r,rt:t}:{msgType:n,payload:e,jwt:r}:{msgType:n,payload:e}})}function sr(n){return E(this,null,function*(){!n.data.rt||(yield _("rt",n.data.rt))})}var De=class{constructor(e,t){this.endpoint=e;this.parameters=t;this.messageHandlers=new Set;this.ready=this.waitForReady(),this.listen()}post(e,t){return E(this,null,function*(){return Ce(r=>E(this,null,function*(){yield this.ready;let o=[],s=Array.isArray(t)?t.map(l=>l.id):[],a=yield rr(`${e}-${this.parameters}`,t);yield this._post(a);let i=l=>u=>{let{id:p,response:P}=nr(t,u);sr(u),p&&P&&Array.isArray(t)&&s.includes(p)?(o.push(P),o.length===t.length&&(l(),r(o))):p&&P&&!Array.isArray(t)&&p===t.id&&(l(),r(P))},c=this.on(we.MAGIC_HANDLE_RESPONSE,i(()=>c()))}))})}on(e,t){let r=t.bind(window),o=s=>{s.data.msgType===`${e}-${this.parameters}`&&r(s)};return this.messageHandlers.add(o),()=>this.messageHandlers.delete(o)}waitForReady(){return new Promise(e=>{this.on(we.MAGIC_OVERLAY_READY,()=>e())})}listen(){this.on(we.MAGIC_HIDE_OVERLAY,()=>{this.hideOverlay()}),this.on(we.MAGIC_SHOW_OVERLAY,()=>{this.showOverlay()})}};export{k as Extension,B as MagicExtensionError,Q as MagicExtensionWarning,O as MagicRPCError,A as MagicSDKError,j as MagicSDKWarning,Pe as SDKBase,Le as STORE_KEY_PRIVATE_KEY,ye as STORE_KEY_PUBLIC_JWK,Ae as TypedEmitter,De as ViewController,Rs as clearKeys,w as createDeprecationWarning,vr as createDuplicateIframeWarning,it as createExtensionNotInitializedError,at as createIncompatibleExtensionsError,ct as createInvalidArgumentError,bt as createJwt,ot as createMalformedResponseError,st as createMissingApiKeyError,Rr as createModalNotReadyError,X as createPromiEvent,Ce as createPromise,ut as createReactNativeEndpointConfigurationWarning,$n as createSDK,lt as createSynchronousWeb3MethodWarning,me as createTypedEmitter,Se as createURL,et as decodeJSON,ce as encodeJSON,Ne as getPayloadId,ue as isEmpty,nt as isJsonRpcErrorCode,dr as isJsonRpcRequestPayload,tt as isJsonRpcResponsePayload,pr as isMagicPayloadMethod,yt as isMajorVersionAtLeast,gt as isPromiEvent,te as storage,vt as uuid};
5
+ Received: \`${n.received}\``)}function vr(){return new j(de.DuplicateIframe,"Duplicate iframes found.")}function lt(){return new j(de.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 ut(){return new j(de.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:e,removalVersions:t,useInstead:r}=n,o=t[m.sdkName],s=r?` Use \`${r}\` instead.`:"",a=`\`${e}\` will be removed from \`${m.sdkName}\` in version \`${o}\`.${s}`;return new j(de.DeprecationNotice,a)}import{MagicPayloadMethod as $,DeviceVerificationEventEmit as Rt,LoginWithEmailOTPEventEmit as he}from"@magic-sdk/types";import{MagicOutgoingWindowMessage as kn,MagicIncomingWindowMessage as qn,MagicPayloadMethod as Dn}from"@magic-sdk/types";function*Cn(){let n=0;for(;;)n<Number.MAX_SAFE_INTEGER?yield++n:n=0}var Sn=Cn();function Ne(){return Sn.next().value}var dt=Symbol("Payload pre-processed by Magic SDK");function pt(n){return Object.defineProperty(n,dt,{value:!0,enumerable:!1}),n}function Ln(n){return!!n[dt]}function F(n){var e,t,r;return Ln(n)||(n.jsonrpc=(e=n.jsonrpc)!=null?e:"2.0",n.id=Ne(),n.method=(t=n.method)!=null?t:"noop",n.params=(r=n.params)!=null?r:[],pt(n)),n}function d(n,e=[]){return pt({params:e,method:n,jsonrpc:"2.0",id:Ne()})}var W=class{constructor(e){e instanceof W?(this._jsonrpc=e.payload.jsonrpc,this._id=e.payload.id,this._result=e.payload.result,this._error=e.payload.error):tt(e)?(this._jsonrpc=e.jsonrpc,this._id=e.id,this._result=e.result,this._error=e.error):(this._jsonrpc=e.jsonrpc,this._id=e.id,this._result=void 0,this._error=void 0)}applyError(e){return this._error=e,this}applyResult(e){return this._result=e,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 Et=Dt(ht()),Ae=class extends Et.default{};function me(){let n=new Ae;return{emitter:n,createChainingEmitterMethod:(r,o)=>(...s)=>(n[r].apply(n,s),o),createBoundEmitterMethod:r=>(...o)=>n[r].apply(n,o)}}var ft=Symbol("isPromiEvent");function gt(n){return!!n[ft]}function X(n){let e=Ce(n),{createBoundEmitterMethod:t,createChainingEmitterMethod:r}=me(),o=Symbol("Promise.then"),s=Symbol("Promise.catch"),a=Symbol("Promise.finally"),i=(u,p)=>(...P)=>{let q=p[u].apply(p,P);return c(q)},c=u=>Object.assign(u,{[ft]:!0,[o]:u[o]||u.then,[s]:u[s]||u.catch,[a]:u[a]||u.finally,then:i(o,u),catch:i(s,u),finally:i(a,u),on:r("on",u),once:r("once",u),addListener:r("addListener",u),off:r("off",u),removeListener:r("removeListener",u),removeAllListeners:r("removeAllListeners",u),emit:t("emit"),eventNames:t("eventNames"),listeners:t("listeners"),listenerCount:t("listenerCount")}),l=c(e.then(u=>(l.emit("done",u),l.emit("settled"),u),u=>{throw l.emit("error",u),l.emit("settled"),u}));return l}function Ce(n){return new Promise((e,t)=>{let r=n(e,t);Promise.resolve(r).catch(t)})}var b=class{constructor(e){this.sdk=e}get overlay(){return this.sdk.overlay}request(e){let t=this.overlay.post(kn.MAGIC_HANDLE_REQUEST,F(e)),r=X((s,a)=>{t.then(i=>{if(o(),i.hasError)a(new O(i.payload.error));else if(i.hasResult)s(i.payload.result);else throw ot()}).catch(i=>{o(),a(i)})}),o=this.overlay.on(qn.MAGIC_HANDLE_EVENT,s=>{var i;let{response:a}=s.data;if(a.id===e.id&&((i=a.result)==null?void 0:i.event)){let{event:c,params:l=[]}=a.result;r.emit(c,...l)}});return r}createIntermediaryEvent(e,t){return o=>{let s=d(Dn.IntermediaryEvent,[{payloadId:t,eventType:e,args:o}]);this.request(s)}}};function yt(n,e){let[t]=n.split(".").map(Number);return t>=e}var M={"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"},Ee=class extends b{loginWithMagicLink(e){let t=m.sdkName==="@magic-sdk/react-native"||m.sdkName==="@magic-sdk/react-native-bare"||m.sdkName==="@magic-sdk/react-native-expo";if(t&&yt(m.version,19))throw new Error("loginWithMagicLink() is deprecated for this package, please utlize a passcode method like loginWithSMS or loginWithEmailOTP instead.");w({method:"auth.loginWithMagicLink()",removalVersions:M,useInstead:t?"@magic-ext/auth auth.loginWithEmailOTP()":"@magic-ext/auth auth.loginWithMagicLink()"}).log();let{email:r,showUI:o=!0,redirectURI:s}=e,a=d(this.sdk.testMode?$.LoginWithMagicLinkTestMode:$.LoginWithMagicLink,[{email:r,showUI:o,redirectURI:s}]);return this.request(a)}loginWithSMS(e){w({method:"auth.loginWithSMS()",removalVersions:M,useInstead:"@magic-ext/auth auth.loginWithSMS()"}).log();let{phoneNumber:t}=e,r=d(this.sdk.testMode?$.LoginWithSmsTestMode:$.LoginWithSms,[{phoneNumber:t,showUI:!0}]);return this.request(r)}loginWithEmailOTP(e){let{email:t,showUI:r,deviceCheckUI:o}=e,s=d(this.sdk.testMode?$.LoginWithEmailOTPTestMode:$.LoginWithEmailOTP,[{email:t,showUI:r,deviceCheckUI:o}]),a=this.request(s);return!o&&a&&a.on(Rt.Retry,()=>{this.createIntermediaryEvent(Rt.Retry,s.id)()}),!r&&a&&(a.on(he.VerifyEmailOtp,i=>{this.createIntermediaryEvent(he.VerifyEmailOtp,s.id)(i)}),a.on(he.Cancel,()=>{this.createIntermediaryEvent(he.Cancel,s.id)()})),a}loginWithCredential(e){w({method:"auth.loginWithCredential()",removalVersions:M,useInstead:"@magic-ext/auth auth.loginWithCredential()"}).log();let t=e!=null?e:"";if(!e&&m.platform==="web"){t=window.location.search;let o=window.location.origin+window.location.pathname;window.history.replaceState(null,"",o)}let r=d(this.sdk.testMode?$.LoginWithCredentialTestMode:$.LoginWithCredential,[t]);return this.request(r)}setAuthorizationToken(e){w({method:"auth.setAuthorizationToken()",removalVersions:M,useInstead:"@magic-ext/auth auth.setAuthorizationToken()"}).log();let t=d($.SetAuthorizationToken,[{jwt:e}]);return this.request(t)}updateEmailWithUI(e){w({method:"auth.updateEmailWithUI()",removalVersions:M,useInstead:"@magic-ext/auth auth.updateEmailWithUI()"}).log();let{email:t,showUI:r=!0}=e,o=d(this.sdk.testMode?$.UpdateEmailTestMode:$.UpdateEmail,[{email:t,showUI:r}]);return this.request(o)}};import{MagicPayloadMethod as g}from"@magic-sdk/types";var te={};kt(te,{clear:()=>Wn,getItem:()=>x,iterate:()=>Gn,key:()=>Jn,keys:()=>Fn,length:()=>Un,removeItem:()=>J,setItem:()=>_});var fe;function U(n){return(...e)=>E(this,null,function*(){return fe||(fe=yield m.configureStorage()),yield fe.ready(),fe[n](...e)})}var x=U("getItem"),_=U("setItem"),J=U("removeItem"),Wn=U("clear"),Un=U("length"),Jn=U("key"),Fn=U("keys"),Gn=U("iterate");var ge=class extends b{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}getIdToken(t){let r=d(this.sdk.testMode?g.GetIdTokenTestMode:g.GetIdToken,[t]);return this.request(r)}generateIdToken(t){let r=d(this.sdk.testMode?g.GenerateIdTokenTestMode:g.GenerateIdToken,[t]);return this.request(r)}getInfo(){return E(this,null,function*(){let t=yield x(this.localForageKey),r=d(g.GetInfo,[{walletType:t}]);return this.request(r)})}isLoggedIn(){let t=d(this.sdk.testMode?g.IsLoggedInTestMode:g.IsLoggedIn);return this.request(t)}logout(){J(this.localForageKey);let t=d(this.sdk.testMode?g.LogoutTestMode:g.Logout);return this.request(t)}requestInfoWithUI(t){let r=d(g.RequestUserInfoWithUI,t?[t]:[]);return this.request(r)}showSettings(t){let r=d(this.sdk.testMode?g.UserSettingsTestMode:g.UserSettings,[t]);return this.request(r)}recoverAccount(t){let r=d(this.sdk.testMode?g.RecoverAccountTestMode:g.RecoverAccount,[t]);return this.request(r)}getMetadata(){w({method:"user.getMetadata()",removalVersions:M,useInstead:"user.getInfo()"}).log();let t=d(this.sdk.testMode?g.GetMetadataTestMode:g.GetMetadata);return this.request(t)}updateEmail(t){w({method:"user.updateEmail()",removalVersions:M,useInstead:"auth.updateEmailWithUI()"}).log();let{email:r,showUI:o=!0}=t,s=d(this.sdk.testMode?g.UpdateEmailTestMode:g.UpdateEmail,[{email:r,showUI:o}]);return this.request(s)}};import{Events as _e,MagicPayloadMethod as N,Wallets as C}from"@magic-sdk/types";function Se(n,e){return e?new URL(n,e):new URL(n)}function vt(){let n=window.crypto.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&191|128;let e="";return e+=n[0].toString(16),e+=n[1].toString(16),e+=n[2].toString(16),e+=n[3].toString(16),e+="-",e+=n[4].toString(16),e+=n[5].toString(16),e+="-",e+=n[6].toString(16),e+=n[7].toString(16),e+="-",e+=n[8].toString(16),e+=n[9].toString(16),e+="-",e+=n[10].toString(16),e+=n[11].toString(16),e+=n[12].toString(16),e+=n[13].toString(16),e+=n[14].toString(16),e+=n[15].toString(16),e}var Le="STORE_KEY_PRIVATE_KEY",ye="STORE_KEY_PUBLIC_JWK",Oe="ECDSA",It="P-256",Kn={name:Oe,namedCurve:It},jn={name:Oe,namedCurve:It};function Rs(){J(ye),J(Le)}function bt(){return E(this,null,function*(){let n=yield Bn();if(!n){console.info("unable to create public key or webcrypto is unsupported");return}let{subtle:e}=window.crypto,t=yield x(Le);if(!t||!e){console.info("unable to find private key or webcrypto unsupported");return}let r={iat:Math.floor(new Date().getTime()/1e3),jti:vt()},o={typ:"dpop+jwt",alg:"ES256",jwk:n},s={protected:Tt(JSON.stringify(o)),claims:Tt(JSON.stringify(r))},a=Hn(`${s.protected}.${s.claims}`),i={name:Oe,hash:{name:"SHA-256"}},c=Yn(new Uint8Array(yield e.sign(i,t,a)));return`${s.protected}.${s.claims}.${c}`})}function Bn(){return E(this,null,function*(){if(!Xn()){console.info("webcrypto is not supported");return}return(yield x(ye))||(yield Vn()),x(ye)})}function Vn(){return E(this,null,function*(){let n=null,{subtle:e}=window.crypto,t=yield e.generateKey(Kn,!0,["sign"]),r=yield e.exportKey("jwk",t.privateKey);n=yield e.exportKey("jwk",t.publicKey);let o=yield e.importKey("jwk",r,jn,!1,["sign"]);yield _(Le,o),yield _(ye,n)})}function Xn(){let n=typeof window!="undefined"&&!!window.crypto,e=n&&!!window.crypto.subtle;return n&&e}function Tt(n){return Pt(zn(n))}function Hn(n){return new TextEncoder().encode(n)}function Pt(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function zn(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16)))}function Yn(n){let e="";return n.forEach(t=>{e+=String.fromCharCode(t)}),Pt(e)}var Re=class extends b{constructor(){super(...arguments);this.localForageKey="mc_active_wallet"}connectWithUI(){let t=X((r,o)=>E(this,null,function*(){try{if(this.isMetaMaskBrowser()&&(yield this.isWalletEnabled(C.MetaMask))){let l=yield this.autoConnectIfWalletBrowser(C.MetaMask);r(l);return}if(this.isCoinbaseWalletBrowser()&&(yield this.isWalletEnabled(C.CoinbaseWallet))){let l=yield this.autoConnectIfWalletBrowser(C.CoinbaseWallet);r(l);return}let s=this.getUserEnv(),a=d(N.Login,[s]),i=this.request(a);i.on(_e.WalletSelected,l=>this.handleWalletSelected(se(G({},l),{payloadId:a.id}))),i.on("id-token-created",l=>{t.emit("id-token-created",l)});let c=yield i;c.error&&o(c),r(c)}catch(s){o(s)}}));return t}showUI(){return this.request(d(N.ShowUI))}showAddress(){return this.request(d(N.ShowAddress))}showSendTokensUI(){return this.request(d(N.ShowSendTokensUI))}showOnRamp(){return this.request(d(N.ShowOnRamp))}showNFTs(){return this.request(d(N.ShowNFTs))}showBalances(){return this.request(d(N.ShowBalances))}sendGaslessTransaction(t,r){return this.request(d(N.SendGaslessTransaction,[t,r]))}getInfo(){return E(this,null,function*(){w({method:"wallet.getInfo()",removalVersions:M,useInstead:"user.getInfo()"}).log();let t=yield x(this.localForageKey),r=d(N.GetInfo,[{walletType:t}]);return this.request(r)})}disconnect(){w({method:"wallet.disconnect()",removalVersions:M,useInstead:"user.logout()"}).log(),J(this.localForageKey);let t=d(N.Disconnect);return this.request(t)}requestUserInfoWithUI(t){w({method:"wallet.requestUserInfoWithUI()",removalVersions:M,useInstead:"user.requestUserInfoWithUI()"}).log();let r=d(N.RequestUserInfoWithUI,t?[t]:[]);return this.request(r)}getProvider(){return E(this,null,function*(){switch(yield x(this.localForageKey)){case C.MetaMask:return this.getMetaMaskProvider();case C.CoinbaseWallet:return this.getCoinbaseProvider();default:return this.sdk.rpcProvider}})}isMetaMaskInstalled(){var t,r,o;return((t=window.ethereum)==null?void 0:t.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 t,r;return((r=(t=window.ethereum)==null?void 0:t.providers)==null?void 0:r.find(o=>o==null?void 0:o.isMetaMask))||window.ethereum}connectToMetaMask(){if(this.isMobile()&&!this.isMetaMaskInstalled()){let t=`https://metamask.app.link/dapp/${window.location.href.replace(/(^\w+:|^)\/\//,"")}`;window.location.href=t}return this.getMetaMaskProvider().request({method:"eth_requestAccounts"})}isCoinbaseWalletInstalled(){var t,r,o;return((t=window.ethereum)==null?void 0:t.isCoinbaseWallet)||!!((o=(r=window.ethereum)==null?void 0:r.providers)!=null&&o.find(s=>s==null?void 0:s.isCoinbaseWallet))}isCoinbaseWalletBrowser(){var t;return!!((t=window.ethereum)!=null&&t.isCoinbaseBrowser)}getCoinbaseProvider(){var t,r;return((r=(t=window.ethereum)==null?void 0:t.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(t){switch(t){case C.MetaMask:return this.connectToMetaMask();case C.CoinbaseWallet:return this.connectToCoinbaseWallet();default:throw new Error(`Invalid provider: ${t}. Must be one of "metamask" or "coinbase_wallet".`)}}isWalletEnabled(t){let r=d("mc_is_wallet_enabled",[{wallet:t}]);return this.request(r)}handleWalletSelected(t){return E(this,null,function*(){try{let r=yield this.connectToThirdPartyWallet(t.wallet);yield _(this.localForageKey,t.wallet),this.createIntermediaryEvent(_e.WalletConnected,t.payloadId)(r)}catch(r){console.error(r),this.createIntermediaryEvent(_e.WalletRejected,t.payloadId)()}})}autoConnectIfWalletBrowser(t){return E(this,null,function*(){let r;t===C.MetaMask&&(r=yield this.getMetaMaskProvider().request({method:"eth_requestAccounts"})),t===C.CoinbaseWallet&&(r=yield this.getCoinbaseProvider().request({method:"eth_requestAccounts"})),yield _(this.localForageKey,t);let o=d(N.AutoConnect,[{wallet:t,address:r}]);return this.request(o)})}};import{MagicOutgoingWindowMessage as wt,MagicPayloadMethod as Zn}from"@magic-sdk/types";var{createBoundEmitterMethod:ve,createChainingEmitterMethod:H}=me(),Te=class extends b{constructor(){super(...arguments);this.isMagic=!0;this.on=H("on",this);this.once=H("once",this);this.addListener=H("addListener",this);this.off=H("off",this);this.removeListener=H("removeListener",this);this.removeAllListeners=H("removeAllListeners",this);this.emit=ve("emit");this.eventNames=ve("eventNames");this.listeners=ve("listeners");this.listenerCount=ve("listenerCount")}sendAsync(t,r){if(!r)throw ct({procedure:"Magic.rpcProvider.sendAsync",argument:1,expected:"function",received:r===null?"null":typeof r});if(Array.isArray(t))this.overlay.post(wt.MAGIC_HANDLE_REQUEST,t.map(o=>{let s=F(o);return this.prefixPayloadMethodForTestMode(s),s})).then(o=>{r(null,o.map(s=>se(G({},s.payload),{error:s.hasError?new O(s.payload.error):null})))});else{let o=F(t);this.prefixPayloadMethodForTestMode(o),this.overlay.post(wt.MAGIC_HANDLE_REQUEST,o).then(s=>{r(s.hasError?new O(s.payload.error):null,s.payload)})}}send(t,r){if(typeof t=="string"){let s=d(t,Array.isArray(r)?r:[]);return this.request(s)}if(Array.isArray(t)||!!r){this.sendAsync(t,r);return}let o=lt();return o.log(),new W(t).applyError({code:-32603,message:o.rawMessage}).payload}enable(){let t=d(Zn.Login);return this.request(t)}request(t){return this.prefixPayloadMethodForTestMode(t),super.request(t)}prefixPayloadMethodForTestMode(t){let r="testMode/eth/";this.sdk.testMode&&(t.method=`${r}${t.method}`)}};var Mt=["request","overlay","sdk"];function Qn(n){let e=Object.getPrototypeOf(n),t=[e];for(;e!==b.prototype;)e=Object.getPrototypeOf(e),t.push(e);return t}var Ie=class extends b{constructor(){super(void 0);this.__sdk_access_field_descriptors__=new Map;this.__is_initialized__=!1;this.utils={createPromiEvent:X,isPromiEvent:gt,encodeJSON:ce,decodeJSON:et,createJsonRpcRequestPayload:d,standardizeJsonRpcRequestPayload:F,storage:te};let t=[this,...Qn(this)];Mt.forEach(r=>{let o=t.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 it(r)}}))})}init(t){this.__is_initialized__||(Mt.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=t,this.__is_initialized__=!0)}createDeprecationWarning(t){let{method:r,removalVersion:o,useInstead:s}=t,a=s?` Use \`${s}\` instead.`:"",i=`\`${r}\` will be removed from this Extension in version \`${o}\`.${a}`;return new Q(this,"DEPRECATION_NOTICE",i)}createWarning(t,r){return new Q(this,t,r)}createError(t,r,o){return new B(this,t,r,o)}},ke=class extends Ie{},k=class extends Ie{};k.Internal=ke,k.Anonymous="anonymous extension";import{MagicPayloadMethod as qe}from"@magic-sdk/types";var be=class extends b{purchase(e){let t=d(qe.NFTPurchase,[e]);return this.request(t)}checkout(e){let t=d(qe.NFTCheckout,[e]);return this.request(t)}transfer(e){let t=d(qe.NFTTransfer,[e]);return this.request(t)}};function xt(n){return n.compat&&n.compat[m.sdkName]!=null?typeof n.compat[m.sdkName]=="string"?Ze(Qe(m.version),n.compat[m.sdkName]):!!n.compat[m.sdkName]:!0}function er(n){var o;let e=(o=n==null?void 0:n.extensions)!=null?o:[],t={},r=[];if(Array.isArray(e)?e.forEach(s=>{xt(s)?(s.init(this),(s.name||s.name!==k.Anonymous)&&(this[s.name]=s),s instanceof k.Internal&&(ue(s.config)||(t[s.name]=s.config))):r.push(s)}):Object.keys(e).forEach(s=>{if(xt(e[s])){e[s].init(this);let a=e[s];this[s]=a,a instanceof k.Internal&&(ue(a.config)||(t[e[s].name]=a.config))}else r.push(e[s])}),r.length)throw at(r);return t}var ne=class{constructor(e,t){this.apiKey=e;var a;if(!e)throw st();m.platform==="react-native"&&(t==null?void 0:t.endpoint)&&ut().log();let{defaultEndpoint:r,version:o}=m;this.testMode=!!(t!=null&&t.testMode),this.endpoint=Se((a=t==null?void 0:t.endpoint)!=null?a:r).origin,this.auth=new Ee(this),this.user=new ge(this),this.wallet=new Re(this),this.nft=new be(this),this.rpcProvider=new Te(this);let s=er.call(this,t);this.parameters=ce(G({API_KEY:this.apiKey,DOMAIN_ORIGIN:window.location?window.location.origin:"",ETH_NETWORK:t==null?void 0:t.network,host:Se(this.endpoint).host,sdk:rt[m.sdkName],version:o,ext:ue(s)?void 0:s,locale:(t==null?void 0:t.locale)||"en_US"},m.bundleId?{bundleId:m.bundleId}:{}))}get overlay(){if(!ne.__overlays__.has(this.parameters)){let e=new m.ViewController(this.endpoint,this.parameters);e.init(),ne.__overlays__.set(this.parameters,e)}return ne.__overlays__.get(this.parameters)}preload(){return E(this,null,function*(){yield this.overlay.ready})}},Pe=ne;Pe.__overlays__=new Map;import{MagicIncomingWindowMessage as we}from"@magic-sdk/types";function tr(n,e){return e&&Array.isArray(n)?n.find(t=>t.id===e):n}function nr(n,e){var o;let t=(o=e.data.response)==null?void 0:o.id,r=tr(n,t);if(t&&r){let s=new W(r).applyResult(e.data.response.result).applyError(e.data.response.error);return{id:t,response:s}}return{}}function rr(n,e){return E(this,null,function*(){let t=yield x("rt"),r;if(m.platform==="web")try{r=yield bt()}catch(o){console.error("webcrypto error",o)}return r?t?{msgType:n,payload:e,jwt:r,rt:t}:{msgType:n,payload:e,jwt:r}:{msgType:n,payload:e}})}function sr(n){return E(this,null,function*(){!n.data.rt||(yield _("rt",n.data.rt))})}var De=class{constructor(e,t){this.endpoint=e;this.parameters=t;this.messageHandlers=new Set;this.ready=this.waitForReady(),this.listen()}post(e,t){return E(this,null,function*(){return Ce(r=>E(this,null,function*(){yield this.ready;let o=[],s=Array.isArray(t)?t.map(l=>l.id):[],a=yield rr(`${e}-${this.parameters}`,t);yield this._post(a);let i=l=>u=>{let{id:p,response:P}=nr(t,u);sr(u),p&&P&&Array.isArray(t)&&s.includes(p)?(o.push(P),o.length===t.length&&(l(),r(o))):p&&P&&!Array.isArray(t)&&p===t.id&&(l(),r(P))},c=this.on(we.MAGIC_HANDLE_RESPONSE,i(()=>c()))}))})}on(e,t){let r=t.bind(window),o=s=>{s.data.msgType===`${e}-${this.parameters}`&&r(s)};return this.messageHandlers.add(o),()=>this.messageHandlers.delete(o)}waitForReady(){return new Promise(e=>{this.on(we.MAGIC_OVERLAY_READY,()=>e())})}listen(){this.on(we.MAGIC_HIDE_OVERLAY,()=>{this.hideOverlay()}),this.on(we.MAGIC_SHOW_OVERLAY,()=>{this.showOverlay()})}};export{k as Extension,B as MagicExtensionError,Q as MagicExtensionWarning,O as MagicRPCError,A as MagicSDKError,j as MagicSDKWarning,Pe as SDKBase,Le as STORE_KEY_PRIVATE_KEY,ye as STORE_KEY_PUBLIC_JWK,Ae as TypedEmitter,De as ViewController,Rs as clearKeys,w as createDeprecationWarning,vr as createDuplicateIframeWarning,it as createExtensionNotInitializedError,at as createIncompatibleExtensionsError,ct as createInvalidArgumentError,bt as createJwt,ot as createMalformedResponseError,st as createMissingApiKeyError,Rr as createModalNotReadyError,X as createPromiEvent,Ce as createPromise,ut as createReactNativeEndpointConfigurationWarning,$n as createSDK,lt as createSynchronousWeb3MethodWarning,me as createTypedEmitter,Se as createURL,et as decodeJSON,ce as encodeJSON,Ne as getPayloadId,ue as isEmpty,nt as isJsonRpcErrorCode,dr as isJsonRpcRequestPayload,tt as isJsonRpcResponsePayload,pr as isMagicPayloadMethod,yt as isMajorVersionAtLeast,gt as isPromiEvent,te as storage,vt as uuid};
6
6
  //# sourceMappingURL=index.js.map