@privy-io/react-auth 1.99.1 → 1.100.0-beta-20250113171330
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/client.js +1 -1
- package/dist/cjs/components/embedded-wallets/SolanaTransactionDetails.js +1 -1
- package/dist/cjs/connectors/embeddedProvider.js +1 -1
- package/dist/cjs/connectors/index.js +1 -1
- package/dist/cjs/constants.js +1 -1
- package/dist/cjs/embedded-wallets/solana/provider.js +1 -1
- package/dist/cjs/hooks/privy-provider.js +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/lib/solana/transaction.js +1 -1
- package/dist/cjs/privy-provider-B-zqeRz7.js +2 -0
- package/dist/cjs/screens/SendSolanaTransactionScreen/SendSolanaTransactionScreen.js +1 -1
- package/dist/cjs/screens/SendSolanaTransactionScreen/SolanaTransactionReceiptView.js +1 -1
- package/dist/cjs/screens/SendTransactionScreen/SendTransactionScreenView.js +1 -1
- package/dist/esm/client.mjs +1 -1
- package/dist/esm/components/embedded-wallets/SolanaTransactionDetails.mjs +1 -1
- package/dist/esm/connectors/embeddedProvider.mjs +1 -1
- package/dist/esm/connectors/index.mjs +1 -1
- package/dist/esm/constants.mjs +1 -1
- package/dist/esm/embedded-wallets/solana/provider.mjs +1 -1
- package/dist/esm/hooks/privy-provider.mjs +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/lib/solana/transaction.mjs +1 -1
- package/dist/esm/privy-provider-DJiL84f_.mjs +2 -0
- package/dist/esm/screens/SendSolanaTransactionScreen/SendSolanaTransactionScreen.mjs +1 -1
- package/dist/esm/screens/SendSolanaTransactionScreen/SolanaTransactionReceiptView.mjs +1 -1
- package/dist/esm/screens/SendTransactionScreen/SendTransactionScreenView.mjs +1 -1
- package/package.json +3 -3
- package/dist/cjs/privy-provider-hwWfKY1K.js +0 -2
- package/dist/esm/privy-provider-CoCxAge0.mjs +0 -2
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("@ethersproject/address"),r=require("@ethersproject/providers"),a=require("mipd"),n=require("react"),i=require("react-device-detect"),o=require("@privy-io/js-sdk-core"),s=require("./auth-flows/custom-jwt-account.js"),l=require("./auth-flows/email.js"),c=require("./auth-flows/farcaster.js"),d=require("./auth-flows/guest.js"),u=require("./auth-flows/passkey.js"),h=require("./auth-flows/siwe.js"),y=require("./auth-flows/siws.js"),p=require("./auth-flows/sms.js"),w=require("./auth-flows/telegram.js"),E=require("uuid"),v=require("./accessToken.js"),m=require("./client/user.js"),g=require("eventemitter3"),f=require("./constants.js"),C=require("./storage.js"),A=require("./utils/index.js"),P=require("./connectors/coinbase.js"),_=require("./connectors/embedded.js"),T=require("./embedded-wallets/rpc/types.js"),W=require("./components/Captcha.js"),I=require("./components/LoginModal.js"),S=require("./components/TelegramLoginButton.js"),N=require("./configuration/context.js"),k=require("./connectors/areWalletArraysEqual.js"),U=require("./connectors/errors.js"),b=require("./connectors/is-wallet-installed.js"),O=require("./connectors/isBaseConnectedEthereumWallet.js"),R=require("./connectors/privyProxyProvider.js"),D=require("./connectors/solana/index.js"),M=require("./connectors/walletconnect-v2.js"),F=require("./embedded-wallets/EmbeddedWalletIframe.js"),L=require("./embedded-wallets/delegated-actions.js"),x=require("./embedded-wallets/errors.js"),q=require("./embedded-wallets/rpc/index.js"),j=require("./errors.js"),B=require("./embedded-wallets/solana/transaction.js"),H=require("./lib/caip2.js"),K=require("./lib/cross-app/index.js"),V=require("./lib/cross-app/authFlow.js"),G=require("./lib/cross-app/popupCrossAppAuthFlow.js"),z=require("./lib/cross-app/sendCrossAppRequest.js"),Y=require("./lib/embeddedWalletRecovery.js"),$=require("./lib/funding/index.js"),X=require("./lib/funding/isFundingEnabled.js"),J=require("./lib/isEmbeddedWebview.js"),Q=require("./lib/popup/triggerPopup.js"),Z=require("./lib/popupOAuthFlow.js"),ee=require("./lib/siwe.js"),te=require("./lib/solana/transaction.js"),re=require("./lib/toDisplayFromAccountType.js"),ae=require("./passkeys/transformResponseToSnakeCase.js"),ne=require("./plugins/context/PrivyPluginContext.js"),ie=require("./plugins/solana-funding/id.js"),oe=require("./recent-login/context.js"),se=require("./screens/index.js"),le=require("./screens/LandingScreen/styles.js"),ce=require("./styles.js"),de=require("./hooks/index.js"),ue=require("./hooks/captcha-context.js"),he=require("./hooks/events-context.js"),ye=require("./hooks/internal-context.js"),pe=require("./hooks/modal-context.js"),we=require("./hooks/privy-context.js"),Ee=require("./hooks/useWallets.js"),ve=require("./lib/funding/prepareFundingModalData.js"),me=require("./auth-flows/oauth/detectCompletingOAuthFlow.js"),ge=require("./auth-flows/oauth/OAuthFlow.js"),fe=require("./connectors/getRpcTimeout.js"),Ce=require("./connectors/providerTypes.js"),Ae=require("./connectors/ethereum/index.js"),Pe=require("./connectors/injected.js"),_e=require("./connectors/metamask.js"),Te=require("./connectors/phantom.js"),We=require("./connectors/phantom-solana.js"),Ie=require("./http.js"),Se=require("./lib/smart-wallet-helpers.js"),Ne=require("./passkeys/transformOptionsToCamelCase.js"),ke=require("./paths.js"),Ue=require("./session.js");function be(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var Oe=/*#__PURE__*/be(g);class Re extends Oe.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Ce.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Xe()||!this.address)throw new Ce.EmbeddedProviderError("Disconnected",4900);return(await Ze(t,void 0,void 0,this.address)).hash}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new Ce.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new Ce.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.provider=A.getJsonRpcProvider(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",t)}async handlePersonalSign(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for personal_sign");let t=e.params[0],r=e.params[1];return await Je(t,void 0,r)}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],r="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1];return await Qe(A.generateTypedDataWithDomainType(r),void 0,t)}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;let t={...e.params[0],chainId:A.toHex(this.chainId)};try{return await this.provider.send("eth_estimateGas",[t])}catch(e){console.warn(`Gas estimation failed with error: ${e}. Retrying gas estimation by omitting the 'from' address`);try{return delete t.from,await this.provider.send("eth_estimateGas",[t])}catch(t){throw console.warn(`Gas estimation failed with error: ${t} when omitting the 'from' address`),e}}}async request(e){switch(console.debug("Embedded1193Provider.request() called with args",e),e.method){case"eth_accounts":case"eth_requestAccounts":return this.address?[this.address]:[];case"eth_chainId":return A.toHex(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!T.isSupportedEthereumRpcMethod(e.method))return this.provider.send(e.method,e.params);{let t=await Xe();if(await et(),!t||!this.address)throw new Ce.EmbeddedProviderError("Disconnected",4900);try{return(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:{method:e.method,params:e.params}})).response.data}catch(e){throw console.error(e),new Ce.EmbeddedProviderError("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:a,rpcConfig:n,chains:i,appId:o,chainId:s=1,walletIndex:l}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=a,this.chainId=s,this.rpcConfig=n,this.chains=i,this.provider=A.getJsonRpcProvider(s,this.chains,n,{appId:o}),this.rpcTimeoutDuration=fe.getRpcTimeout(n,"privy"),this.appId=o,this.walletIndex=l}}class De extends Oe.default{get wallets(){let e=new Set,t=this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}`;return!e.has(r)&&(e.add(r),!0)})),r=t.findIndex((e=>e.address===(this.activeWallet?this.activeWallet:"unknown")));return r>=0&&t.unshift(t.splice(r,1)[0]),t}async initialize(){if(this.initialized)return;C.default.get(f.CONNECTORS_STATE_KEY)&&(C.default.getKeys().forEach((e=>{e.startsWith("walletconnect")&&C.default.del(e)})),C.default.del(f.CONNECTORS_STATE_KEY));let e=A.detectInjectedConnectors({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector("injected",e,{eip6963InjectedProvider:t,legacyInjectedProvider:r})}))}));this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector("coinbase_wallet","coinbase_wallet"),!b.isPhantomInstalled()&&this.walletList.includes("phantom")&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&this.createEthereumWalletConnector("phantom","phantom"),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&this.addWalletConnector(new We.PhantomSolanaNullWalletConnector)),this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector("wallet_connect_v2","unknown"),this.externalWalletConfig.solana.connectors?.get().forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{e?.forEach(this.addSolanaWalletConnector)})),await e,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(Ae.isEthereumWalletConnector).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(Ae.isEthereumWalletConnector).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e,t){return this.walletConnectors.filter(D.isSolanaWalletConnector).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&t.walletClientType===e.walletClientType));t&&(e.connectedAt=t.connectedAt)})),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnectors({walletProxy:e,rootWallet:t,embeddedWallets:r,defaultChain:a,appId:n}){for(let i of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(r&&Ae.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let{entropyId:r,entropyIdVerifier:o}=m.getEntropyDetailsFromAccount(t),s=new _.EmbeddedWalletConnector({provider:new Re({walletProxy:e,address:i.address,entropyId:r,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:a.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:a,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,r,a){let n=this.findWalletConnector("embedded_imported","privy");if(n&&Ae.isEthereumWalletConnector(n))n.proxyProvider.walletProxy=e;else{let n=new _.EmbeddedWalletConnector({provider:new Re({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(n)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=Me(),this.emit("walletsUpdated")}removeImportedWalletConnector(){let e=this.findWalletConnector("embedded_imported","privy");if(e){let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1),this.saveConnectionHistory(),this.storedConnections=Me(),this.emit("walletsUpdated")}}async createEthereumWalletConnector(e,t,r){let a=this.findWalletConnector(e,t);if(a&&Ae.isEthereumWalletConnector(a))return a instanceof M.WalletConnectV2WalletConnector&&a.resetConnection(t),a;let n=(()=>"injected"!==e?"coinbase_wallet"===e?new P.CoinbaseWalletConnector(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"phantom"===e?new Te.PhantomEthereumNullWalletConnector(this.defaultChain):new M.WalletConnectV2WalletConnector(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):"metamask"===t&&r?.eip6963InjectedProvider?new _e.MetamaskWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Pe.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Pe.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Pe.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Pe.Injected6963WalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return n&&this.addWalletConnector(n),n||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}saveConnectionHistory(){let e=this.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt})));C.default.put(f.CONNECTIONS_HISTORY_KEY,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&O.isBaseConnectedEthereumWallet(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=t.getAddress(e),this.emit("walletsUpdated")}constructor(e,t,r,a,n,i,o,s,l,c,d,u){super(),this.addSolanaWalletConnector=async e=>{this.findSolanaWalletConnector("solana_adapter",e.walletClientType)||this.addWalletConnector(e)},this.getEthereumProvider=()=>{let e=this.wallets[0],t=this.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new R.PrivyProxyProvider},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=a,this.defaultChain=n,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=l,this.privyAppName=c,this.privyAppLogo=d,this.walletChainType=u||"ethereum-only",this.storedConnections=Me()}}const Me=()=>{let e=C.default.get(f.CONNECTIONS_HISTORY_KEY);return e&&Array.isArray(e)&&e.map((e=>(e=>e&&"string"==typeof e.address&&"string"==typeof e.connectorType&&"string"==typeof e.walletClientType&&"number"==typeof e.connectedAt)(e))).every(Boolean)?e:[]};let Fe;var Le=0,xe="__private_"+Le+++"__getOrGenerateClientAnalyticsId";class qe{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:a,store:n,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new De(this.appId,e,t,r,a,n,i,o,s,l,void 0,c))}generateApi(){let e=new Ie.Http({appId:this.appId,appClientId:this.appClientId,client:this,defaults:{baseURL:this.apiUrl,timeout:this.timeout}});return this.session.api=e,e}updateApiUrl(e){this.apiUrl=e||this.fallbackApiUrl,this.api=this.generateApi(),e&&(this.useServerCookies=!0)}authenticate(){if(!this.authFlow)throw new j.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new j.PrivyClientError("No auth flow in progress.");let{oAuthTokens:e}=await this.session.link(this.authFlow);return{user:await this.getAuthenticatedUser(),oAuthTokens:e}}storeProviderAccessToken(e,t){this.session.storeProviderAccessToken(e,t)}getProviderAccessToken(e){return this.session.getProviderAccessToken(e)}async logout(){await this.session.destroy(),this.authFlow=void 0}clearProviderAcccessTokens(e){e.linkedAccounts.filter((e=>"cross_app"===e.type)).forEach((e=>{this.storeProviderAccessToken(e.providerApp.id,null)}))}startAuthFlow(e){return e.api=this.api,this.authFlow=e,this.authFlow}async initMfaSmsVerification(){try{await this.api.post(ke.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw j.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(ke.mfaPasskeyInitPath,{});return Ne.transformOptionsToCamelCase(e.options)}catch(e){throw j.formatApiError(e)}}async getCrossAppProviderDetails(e){try{return this._cachedProviderAppDetails[e]||(this._cachedProviderAppDetails[e]=await this.api.get(`/api/v1/apps/${e}/cross-app/details`)),this._cachedProviderAppDetails[e]}catch(e){console.error("Error fetching cross app provider details",e)}}async acceptTerms(){try{let e=await this.api.post(ke.acceptTermsPath,{});return m.convertUserResponseToUser(e)}catch(e){throw j.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(ke.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(t)}catch(e){throw j.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(ke.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(t)}catch(e){throw j.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(ke.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(t)}catch(e){throw j.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(ke.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(t)}catch(e){throw j.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(ke.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(r)}catch(e){throw j.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(ke.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(t)}catch(e){throw j.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(ke.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(t)}catch(e){throw j.formatPrivyError(e)}}async unlinkPasskey(e){try{let t=await this.api.post(ke.unlinkPasskeyPath,{credential_id:e});return await this.getAuthenticatedUser()??m.convertUserResponseToUser(t)}catch(e){throw j.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(ke.delegatedActionsRevokePath,{})}catch(e){throw j.formatPrivyError(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:a}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(ke.analyticsEventsPath,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:a?.keepAlive??!1})}catch(e){}}async signMoonpayOnRampUrl(e){try{return this.api.post(ke.moonpayPluginOnRampPath,e)}catch(e){throw j.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(ke.coinbaseOnRampInitPath,e)}catch(e){throw j.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${ke.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw j.formatPrivyError(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()||this.session.hasRecoveryCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(Ue.AccessTokenTypes.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Ue.AccessTokenTypes.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?v.AccessToken.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null):!t?.disableAutoRefresh&&this.session.hasRefreshCredentials(e)?(await this.session.refresh(),this.session.getToken(e)):null:null}async getSmartWalletsConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:Se.getPaymasterContext(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw j.formatPrivyError(e)}}async getServerConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:e}),a=r.telegram_auth_config?{botId:r.telegram_auth_config.bot_id,botName:r.telegram_auth_config.bot_name,linkEnabled:r.telegram_auth_config.link_enabled,seamlessAuthEnabled:r.telegram_auth_config.seamless_auth_enabled}:void 0,n=r.funding_config?{methods:r.funding_config.methods,options:r.funding_config.options,defaultRecommendedAmount:r.funding_config.default_recommended_amount,defaultRecommendedCurrency:r.funding_config.default_recommended_currency,promptFundingOnWalletCreation:r.funding_config.prompt_funding_on_wallet_creation,crossChainBridgingEnabled:r.funding_config.cross_chain_bridging_enabled}:void 0;return{id:r.id,name:r.name,verificationKey:r.verification_key,logoUrl:r.logo_url||void 0,accentColor:r.accent_color||void 0,showWalletLoginFirst:r.show_wallet_login_first,allowlistConfig:{errorTitle:r.allowlist_config.error_title,errorDetail:r.allowlist_config.error_detail,errorCtaText:r.allowlist_config.cta_text,errorCtaLink:r.allowlist_config.cta_link},walletAuth:r.wallet_auth,solanaWalletAuth:r.solana_wallet_auth,emailAuth:r.email_auth,smsAuth:r.sms_auth,googleOAuth:r.google_oauth,twitterOAuth:r.twitter_oauth,discordOAuth:r.discord_oauth,githubOAuth:r.github_oauth,spotifyOAuth:r.spotify_oauth,instagramOAuth:r.instagram_oauth,tiktokOAuth:r.tiktok_oauth,linkedinOAuth:r.linkedin_oauth,appleOAuth:r.apple_oauth,farcasterAuth:r.farcaster_auth,passkeyAuth:r.passkey_auth,passkeysForSignupEnabled:r.passkeys_for_signup_enabled,telegramAuth:r.telegram_auth,disablePlusEmails:r.disable_plus_emails,termsAndConditionsUrl:r.terms_and_conditions_url,embeddedWalletConfig:{createOnLogin:r.embedded_wallet_config?.create_on_login,userOwnedRecoveryOptions:r.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:r.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:r.privacy_policy_url,requireUsersAcceptTerms:r.require_users_accept_terms,customApiUrl:r.custom_api_url,walletConnectCloudProjectId:r.wallet_connect_cloud_project_id,fiatOnRampEnabled:r.fiat_on_ramp_enabled,captchaEnabled:r.captcha_enabled,captchaSiteKey:r.captcha_site_key,createdAt:new Date(1e3*r.created_at),updatedAt:new Date(1e3*r.updated_at),mfaMethods:r.mfa_methods,enforceWalletUis:r.enforce_wallet_uis,legacyWalletUiConfig:r.legacy_wallet_ui_config,telegramAuthConfiguration:a,fundingConfig:n}}catch(e){throw j.formatPrivyError(e)}}async getUsdTokenPrice(e){try{return(await this.api.get(`/api/v1/token_price?chainId=${e.id}&tokenSymbol=${e.nativeCurrency.symbol}`)).usd}catch(t){return void console.error(`Unable to fetch token price for chain with id ${e.id}`)}}async getUsdPriceForSol(){try{return(await this.api.get("/api/v1/token_price?chainId=0&tokenSymbol=SOL")).usd}catch(e){return void console.error("Unable to fetch token price for SOL")}}async getSplTokenMetadata({mintAddress:e,cluster:t}){try{return await this.api.get(`/api/v1/spl_token_info?mint_address=${e}&cluster=${t}`)}catch(r){return void console.error(`Unable to fetch token metadata for ${t}:${e}`)}}async requestFarcasterSignerStatus(e){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:e})}catch(e){throw console.error("Unable to fetch Farcaster signer status"),e}}async forkSession(){return await this.session.forkSession()}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(ke.siweInitPath,{address:e,token:t})).nonce}catch(e){throw j.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i}){return await this.api.post(ke.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){return await this.api.post(ke.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})}async linkSmartWallet({message:e,signature:t,smartWalletType:r}){try{let a=await this.api.post(ke.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r});return m.convertUserResponseToUser(a)}catch(e){throw j.formatPrivyError(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n});return m.convertUserResponseToUser(i)}catch(e){throw j.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(ke.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw j.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a,mode:n}){return await this.api.post(ke.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:a,mode:n})}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(r){case"email":l=ke.transferEmailPath,c={nonce:e,email:t};break;case"sms":l=ke.transferPhonePath,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=ke.transferWalletPath,!a)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...a};break;case"farcaster":l=ke.transferFarcasterPath,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=ke.telegramAccountTransferPath,c={nonce:e,telegram_auth_result:n,telegram_web_app_data:i};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=ke.transferOAuthPath,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??m.convertUserResponseToUser(d)}catch(e){throw j.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a}){return await this.api.post(ke.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:a})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:a}){try{let n=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a});return m.convertUserResponseToUser(n)}catch(e){throw j.formatPrivyError(e)}}constructor({apiUrl:e=f.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:a=f.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,xe,{value:je}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==f.DEFAULT_PRIVY_API_URL&&e.startsWith("https://privy."),this.timeout=a,this.appId=t,this.appClientId=r,this.clientAnalyticsId=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}(this,xe)[xe](),Fe||(Fe=new Ue.Session),this.session=Fe,this.api=this.generateApi(),this.session.client=this}}function je(){if("undefined"==typeof window)return null;try{let e=C.default.get(f.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=E.v4();try{return C.default.put(f.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}class Be{async handleSignMessage(e){if(!e.params||"string"!=typeof e.params.message)throw Error("Message must be provided as a string for Solana signMessage RPC");return await rt({message:e.params.message,address:this.address})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Xe())throw Error("User must be authenticated to use embedded Solana wallet");if(!await tt())throw new j.PrivyClientError("Unable to connect to Solana embedded wallet");if("signMessage"===e.method)return await this.handleSignMessage(e);throw Error("Embedded Solana provider does not yet support this RPC method.")}constructor(e,t){this.walletProxy=e,this.address=t}}let He,Ke,Ve,Ge,ze,Ye,$e;async function Xe(){return He?He.getAccessToken():Promise.resolve(C.default.get(f.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||C.default.get(f.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const Je=(e,t,r)=>Ke(e,t,r),Qe=(e,t,r)=>Ve(e,t,r),Ze=(e,t,r,a)=>Ge(e,t,r,a),et=()=>ze(),tt=()=>Ye(),rt=({message:e,address:t})=>$e({message:e,address:t});let at=E=>{let v=E.client,g=ne.usePlugins(),[P,_]=n.useState(!1),[T,fe]=n.useState(!1),[Ce,Ae]=n.useState(!1),[Pe,_e]=n.useState(null),[Te,We]=n.useState([]),[Ie,Se]=n.useState([]),[Ne,ke]=n.useState([]),Ue=n.useRef(Te),[be,Oe]=n.useState(!1),[Re,De]=n.useState(null),[Me,Fe]=n.useState(!1),[Le,xe]=n.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:de.notImplemented}),[qe,je]=n.useState({status:"initial"}),[Je,Qe]=n.useState({status:"initial"}),[Ze,et]=n.useState({status:"initial"}),[tt,rt]=n.useState({status:"initial"}),[at,nt]=n.useState({status:"initial"}),[it,ot]=n.useState(null),st=N.useAppConfig(),lt=N.useIsServerConfigLoaded(),[ct,dt]=n.useState(!0),[ut,ht]=n.useState({}),[yt,pt]=n.useState(null),[wt,Et]=n.useState(null),[vt,mt]=n.useState(!1),[gt,ft]=n.useState(!1),[Ct,At]=n.useState(st.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),Pt=n.useRef(null),_t=n.useRef(null),Tt=n.useRef(he.privyEventsDefault),[Wt,It]=n.useState(!1);v.onStoreCustomerAccessToken=e=>{e&&he.emitPrivyEvent(Tt,"accessToken","onAccessTokenGranted",e)},v.onDeleteCustomerAccessToken=()=>{_e(null),Ae(!1),he.emitPrivyEvent(Tt,"accessToken","onAccessTokenRemoved")};let St=n.useRef(null),Nt=n.useRef(null),kt=n.useRef(!1),Ut=({showWalletUIs:e,typedData:t})=>kt.current?kt.current:void 0!==e?!e:void 0!==st.embeddedWallets.showWalletUIs?!st.embeddedWallets.showWalletUIs:t?st.embeddedWallets.noPromptOnSignature||(st.legacyWalletUiConfig??!1):!!st.embeddedWallets.noPromptOnSignature,bt=e=>{De(e),setTimeout((()=>{_(!0)}),15),v.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},Ot=e=>{"off"!==st.embeddedWallets.createOnLogin&&dt(!0),bt(e)};n.useEffect((()=>{let e=[...m.getPrivySolanaHDWallets(Pe),m.getImportedPrivySolanaWallet(Pe)].filter((e=>!!e));it&&ke(e.map((e=>({type:"solana",imported:e.imported,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",walletIndex:e.walletIndex??void 0,meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund(){throw new j.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new j.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new Be(it,e.address),async signMessage(t){let r=await Xe();if(!r||!it)throw new j.PrivyClientError("Must have valid access token and Privy wallet to send transaction",j.PrivyErrorCode.MUST_BE_AUTHENTICATED);let a=e.imported?m.getImportedPrivySolanaWallet(Pe):m.getPrivyPrimaryWallet(Pe);if(!a)throw new j.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=m.getEntropyDetailsFromAccount(a);if(!await or.recoverPrimaryWallet().catch((()=>!1)))throw new j.PrivyClientError("Wallet couldn't be connected",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);if(!Pe)throw new j.PrivyClientError("Attempting to sign a transaction with no user initialized");let{response:o}=await it.rpc({accessToken:r,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:this.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(o.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:a}=await Zt({transaction:e,connection:t,transactionOptions:r,wallet:this});return a},async signTransaction(t){let r=await Xe();if(!r||!it)throw new j.PrivyClientError("Must have valid access token and Privy wallet to send transaction",j.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await or.recoverPrimaryWallet().catch((()=>!1)))throw new j.PrivyClientError("Wallet couldn't be connected",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let a=e.imported?e:m.getPrivyPrimaryWallet(Pe);if(!a)throw new j.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=m.getEntropyDetailsFromAccount(a);return await B.signSolanaTransaction({tx:t,accessToken:r,walletProxy:it,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:this.address,transactingWalletIndex:this.walletIndex??0}),t},loginOrLink:async()=>{throw new j.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[it,Pe]),n.useEffect((()=>{if(!Pe)return void v.connectors?.removeEmbeddedWalletConnectors();let e=m.getPrivyEthereumWallet(Pe),t=m.getPrivyEthereumHDWallets(Pe),r=m.getImportedPrivyEthereumWallet(Pe);e&&t.length||v.connectors?.removeEmbeddedWalletConnectors(),r||v.connectors?.removeImportedWalletConnector(),v.connectors?it?(e&&v.connectors.addEmbeddedWalletConnectors({walletProxy:it,rootWallet:e,embeddedWallets:t,defaultChain:st.defaultChain,appId:E.appId}),r&&v.connectors.addImportedWalletConnector(it,r.address,st.defaultChain,E.appId)):console.debug("Failed to add embedded wallet connector: Wallet proxy not initialized"):console.debug("Failed to add embedded wallet connector: Client connectors not initialized")}),[it,Pe]),n.useEffect((()=>{it&&wt?.(it)}),[it]);let Rt=n.useRef();n.useEffect((()=>{(async()=>{if(!st.customAuth?.enabled)return void At({status:"not-enabled"});dt(!0);let{getCustomAccessToken:e,isLoading:t}=st.customAuth;if(T&&!t&&"loading"!==Ct.status){At({status:"loading"});try{let t=await e();if(t===Rt.current)return void At({status:"done"});if(!t&&Ce)return Rt.current=t,await ir.logout(),At({status:"done"}),void he.emitPrivyEvent(Tt,"customAuth","onUnauthenticated");if(!t)return Rt.current=t,void At({status:"done"});v.startAuthFlow(new s.CustomJwtAccountFlow(t));let{user:r,isNewUser:a}=await v.authenticate();if(!r)return await ir.logout(),At({status:"error",error:new j.PrivyClientError("Failed to sync with custom auth provider")}),void he.emitPrivyEvent(Tt,"customAuth","onUnauthenticated");void 0!==a&&he.emitPrivyEvent(Tt,"login","onComplete",r,a,!1,"custom",null),Rt.current=t,he.emitPrivyEvent(Tt,"customAuth","onAuthenticated",{user:r}),At({status:"done"}),_e(r||null),Oe(a||!1),Ae(!0),ft(!0)}catch(e){if(console.warn(e),await ir.logout(),he.emitPrivyEvent(Tt,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void At({status:"initial"});he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),At({status:"error",error:e})}}})()}),["initial"===Ct.status,st.customAuth?.enabled,st.customAuth?.getCustomAccessToken,st.customAuth?.isLoading,T,Ce]),n.useEffect((()=>{gt&&it&&Pe&&m.shouldProceedtoEmbeddedWalletCreationFlow(Pe,st.embeddedWallets.createOnLogin)&&(ft(!1),zt(Pe,f.WALLET_PROXY_TIMEOUT).catch(console.error))}),[gt&&it&&Pe]),n.useEffect((()=>{if(st.externalWallets.solana.connectors)return st.externalWallets.solana.connectors.onMount(),()=>st.externalWallets.solana.connectors?.onUnmount()}),[st.externalWallets.solana.connectors]),n.useEffect((()=>{!T&<&&async function(){let e,t=Dt(),r=Mt();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;C.default.put(f.FORKED_TOKEN_STORAGE_KEY,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let n=a.createStore();v.initializeConnectorManager({walletConnectCloudProjectId:st.walletConnectCloudProjectId,rpcConfig:st.rpcConfig,chains:st.chains,defaultChain:st.defaultChain,store:n,walletList:st.appearance.walletList,shouldEnforceDefaultChainOnConnect:st.shouldEnforceDefaultChainOnConnect,externalWalletConfig:st.externalWallets,appName:st.name??"Privy",walletChainType:st.appearance.walletChainType}),v.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=v.connectors.walletConnectors.length,r=v.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?It(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),It(!0)}),1500)})),v.connectors?.initialize().then((()=>{jt()}));let i=await v.getAuthenticatedUser(),o=!!i;st.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await v.logout(),or.setReadyToTrue(!0),he.emitPrivyEvent(Tt,"logout","onSuccess")):(st.customAuth?.enabled||(Ae(!!i),i&&he.emitPrivyEvent(Tt,"login","onComplete",i,!1,!0,null,null),_e(i)),t?Nt.current=o?"link":"login":r&&!o?(Nt.current="login",ht({telegramAuthModalData:{seamlessAuth:!0}}),Ot(se.ModalScreen.TELEGRAM_AUTH_SCREEN)):or.setReadyToTrue(!!i))}()}),[v,yt,T,lt]),n.useEffect((()=>{if(T){if(!Pe||!Pe.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void mt(!0);mt(!!Te.find((e=>"privy"===e.walletClientType)))}}),[T,Pe,Te]);let Dt=()=>{let e=me.detectCompletingOAuthFlow();return e.inProgress&&e.popupFlow?window.opener.location.origin!==window.location.origin?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Origins between parent and child windows do not match."}):"error"===e.authorizationCode?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Something went wrong. Try again."}):void window.opener.postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}):(e.inProgress&&K.isPrivyTheOAuthProvider(e.provider)&&!e.popupFlow&&(new BroadcastChannel(K.CROSS_APP_BROADCAST_CHANNEL_NAME).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(v.startAuthFlow(new ge.OAuthFlow(e)),Ot(se.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},Mt=()=>{let e=w.detectCompletingTelegramFlow();if(!e||!st.loginMethods.telegram||!st.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new w.TelegramAuthFlow;return v.startAuthFlow(t),"login-url"===e.flowType&&(t.meta.telegramWebAppData=void 0,t.meta.telegramAuthResult=e.authData),"web-app"===e.flowType&&(t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=e.authData),!0},Ft=async(e,t,r,a)=>{Lt(await(v.connectors?.createEthereumWalletConnector(e,t))||null,t,r,a)};async function Lt(e,t,r,a){if(!e)return xe({status:"disconnected",connectedWallet:null,connectError:new j.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:de.notImplemented}),a?.(null,r);xe({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:de.notImplemented}),e instanceof M.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),xe({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Lt(e,t,r,a)});try{let t=await e.connect({showPrompt:!0});if((!t||O.isBaseConnectedEthereumWallet(t))&&st.shouldEnforceDefaultChainOnConnect&&!st.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){xe((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:de.notImplemented})));try{await(t?.switchChain(st.defaultChain.id)),t&&(t.chainId=A.formatChainIdToCAIP2(A.toHex(st.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${st.defaultChain.id}`)}}return xe((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:de.notImplemented}))),t&&he.emitPrivyEvent(Tt,"connectWallet","onSuccess",(e.chainType,t)),a?.(t,r)}catch(e){return e instanceof j.PrivyError?(console.warn(e.cause?e.cause:e.message),he.emitPrivyEvent(Tt,"connectWallet","onError",e.privyErrorCode||j.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),he.emitPrivyEvent(Tt,"connectWallet","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),xe((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),a?.(null,r)}}let xt=async(e,t,r)=>{if(null===e||!O.isBaseConnectedEthereumWallet(e))return;let a=new h.SiweFlow(e,v,t,r);v.startAuthFlow(a)},qt=async(e,t)=>{if(null===e||!D.isBaseConnectedSolanaWallet(e))return;let r=new y.SiwsFlow(e,v,t);v.startAuthFlow(r)},jt=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client");if(!t||!r)return;if("phantom"!==r||b.isPhantomInstalled()||Ot(se.ModalScreen.LOGIN_FAILED_SCREEN),!v.connectors)throw new j.PrivyClientError("Connector not initialized");bt(se.ModalScreen.AWAITING_CONNECTION);let a=new URL(window.location.href);a.searchParams.delete("privy_connector"),a.searchParams.delete("privy_wallet_client"),window.history.pushState({},"",a),Ft(t,r,void 0,xt)};n.useEffect((()=>{T&&Ce&&null===Pe&&v.getAuthenticatedUser().then(_e)}),[T,Ce,Pe,v]);let Bt=e=>{if(!Ce)throw he.emitPrivyEvent(Tt,"linkAccount","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new j.PrivyClientError("User must be authenticated before linking an account.")},Ht=()=>{Bt("siwe"),St.current="siwe",Nt.current="link",bt(se.ModalScreen.LINK_WALLET_SCREEN)},Kt=e=>{if(!Ce||!Pe)return!1;if("privy"===e.walletClientType)return!0;for(let t of Pe.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Vt=async e=>{let t;if(!v.connectors)throw new j.PrivyClientError("Connector not initialized");t="ethereum"===e.type?v.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:v.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,xe((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:de.notImplemented}))),st.captchaEnabled&&!Ce?(ht({captchaModalData:{callback:t=>O.isBaseConnectedEthereumWallet(e)?xt(e,t):qt(e,t),userIntentRequired:!1,onSuccessNavigateTo:se.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:se.ModalScreen.ERROR_SCREEN}}),Ot(se.ModalScreen.CAPTCHA_SCREEN)):(O.isBaseConnectedEthereumWallet(e)?await xt(e):await qt(e),Ot(se.ModalScreen.AWAITING_CONNECTION))},Gt=()=>{We((e=>{let t=v.connectors?.wallets.filter(O.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Kt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new j.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new j.PrivyClientError("Cannot link or login with embedded wallet");Vt(e)},fund:async t=>{await or.fundWallet(e.address,t)},unlink:async()=>{if(!Ce)throw new j.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new j.PrivyClientError("Cannot unlink an embedded wallet");_e(await v.unlinkEthereumWallet(e.address))}})))||[];return k.areWalletArraysEqual(e,t)?e:t})),Se((e=>{let t=(v.connectors?.wallets??[]).concat(Ne).filter(D.isBaseConnectedSolanaWallet).map((e=>({...e,linked:Kt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new j.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new j.PrivyClientError("Cannot link or login with embedded wallet");Vt(e)},fund:async()=>{throw new j.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!Ce)throw new j.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new j.PrivyClientError("Cannot unlink an embedded wallet");_e(await v.unlinkSolanaWallet(e.address))}})));return k.areWalletArraysEqual(e,t)?e:t}))};n.useEffect((()=>{Gt()}),[Pe?.linkedAccounts,Ce,T,Ne]),n.useEffect((()=>{if(T){if(!v.connectors)throw new j.PrivyClientError("Connector not initialized");Gt(),v.connectors.on("walletsUpdated",Gt)}}),[T]),n.useEffect((()=>{[...st.loginMethodsAndOrder?.primary??[],...st.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>v.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!v]),n.useEffect((()=>{let e;if(!Te[0])return;let t=Te[0],r=Ue.current.find((e=>e.address===t.address));if(e="privy"===t.walletClientType?Pe?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"===e.walletClientType)):Pe?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"!==e.walletClientType)),!r&&e){let t=Object.assign({},Pe);t.wallet=e&&{address:e.address,chainType:e.chainType,chainId:e.chainId,walletClient:e.walletClient,walletClientType:e.walletClientType,connectorType:e.connectorType,imported:e.imported,delegated:e.delegated,walletIndex:e.walletIndex},_e(t)}Ue.current=Te}),[Te]);let zt=async(e,t,r)=>{let a=m.getPrivyEthereumWallet(e),n=m.getPrivySolanaWallet(e);if(r&&"walletIndex"in r)return $t(e,t,r.walletIndex,a,n);let i=r&&"createAdditional"in r&&r.createAdditional;if(a&&!i)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[o,s]=await Promise.all([or.initializeWalletProxy(t),Xe()]);if(!o&&st.customAuth?.enabled)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||st.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return Yt();if(!a)return await o.create({accessToken:s,solanaAddress:n?.address}),Jt(0,"ethereum");{let t=(m.getLatestPrivyEthereumWallet(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:a}=m.getEntropyDetailsFromAccount(m.getPrivyPrimaryWallet(e));return await or.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:r,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:t}),Jt(t,"ethereum")}},Yt=async()=>new Promise(((e,t)=>{dt(!0),ht({createWallet:{onSuccess:t=>{he.emitPrivyEvent(Tt,"createWallet","onSuccess",t),e(t)},onFailure:e=>{he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),bt(se.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),$t=async(e,t,r,a,n)=>{if(r<0)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[i,o]=await Promise.all([or.initializeWalletProxy(t),Xe()]);if(!i&&st.customAuth?.enabled)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!i||!o||st.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return Yt();throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==r){if(a)return a;await i.create({accessToken:o,solanaAddress:n?.address})}else{if(!a)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("A user must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let t=m.getPrivyEthereumHDWallets(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:n,entropyIdVerifier:s}=m.getEntropyDetailsFromAccount(m.getPrivyPrimaryWallet(e));await or.recoverPrimaryWallet(),await i.addWallet({accessToken:o,entropyId:n,entropyIdVerifier:s,chainType:"ethereum",hdWalletIndex:r})}return Jt(r,"ethereum")},Xt=async({user:e,wp:t,accessToken:r,walletIndex:a,ethereumWallet:n})=>{let i=m.getPrivySolanaHDWallets(e).find((e=>e.walletIndex===a));if(i)return i;if(0===a)await t.createSolana({accessToken:r,ethereumAddress:n?.address});else{let n=m.getPrivyPrimaryWallet(e);if(!n)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("User must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let{entropyId:i,entropyIdVerifier:o}=m.getEntropyDetailsFromAccount(n);await or.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:i,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:a})}return Jt(a,"solana")},Jt=async(e,t)=>{let r=await or.refreshUser(),a=("ethereum"===t?m.getPrivyEthereumHDWallets(r):m.getPrivySolanaHDWallets(r)).find((t=>t.walletIndex===e));if(!a)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return he.emitPrivyEvent(Tt,"createWallet","onSuccess",a),a},Qt=(e,r,a,n)=>new Promise((async(i,s)=>{let{requesterAppId:l}=r||{};if(!Ce||!Pe)return he.emitPrivyEvent(Tt,"sendTransaction","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(Error("User must be authenticated before signing with a Privy wallet"));let c=n??m.getPrivyEthereumWallet(Pe)?.address;if(!c)throw new j.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:d,rootWallet:u}=m.getEthereumSigningAndRootWallet(Pe,c);if(!u||!d)return he.emitPrivyEvent(Tt,"sendTransaction","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have a Privy wallet before signing"));dt(!0);let h=sr.wallets.find((e=>"privy"===e.walletClientType&&t.getAddress(e.address)===t.getAddress(d.address))),y=await(h?.getEthereumProvider());if(!h||!y)throw new j.PrivyClientError(`Cannot sendTransaction before embedded wallet ${d.address} is connected`);let p=e.chainId?Number(e.chainId):H.extractChainIdFromCAIP2(h.chainId);(e=>{if(!st.chains.map((e=>e.id)).includes(e))throw new j.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,j.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(p);let w=Object.assign({},e,{chainId:p});if(Ut({showWalletUIs:r?.showWalletUIs}))(async()=>{let e=await Xe();if(!e||!it)return he.emitPrivyEvent(Tt,"sendTransaction","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have valid access token and Privy wallet to send transaction"));try{if(!await or.recoverPrimaryWallet())return he.emitPrivyEvent(Tt,"sendTransaction","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(Error("Unable to connect to wallet"));let t=A.getJsonRpcProvider(w.chainId,st.chains,st.rpcConfig,{appId:E.appId}),a=await o.populateTransactionRequest(d.address,w,t);if(Ut({showWalletUIs:r?.showWalletUIs})){let{totalGasEstimate:e}=await o.calculateTotalGasEstimate(a,t),{hasSufficientFunds:r}=await q.getAndCheckBalance(d.address,a,e,t);if(!r)throw new U.PrivyProviderRpcError(new U.ProviderRpcError("Wallet has insufficient funds for this transaction.",o.ProviderErrors.E32603_DEFAULT_INTERNAL_ERROR.eipCode))}let{entropyId:n,entropyIdVerifier:c}=m.getEntropyDetailsFromAccount(u),h=await q.sendTransaction({accessToken:e,entropyId:n,entropyIdVerifier:c,transactingWallet:d,walletProxy:it,transactionRequest:a,provider:t,requesterAppId:l});he.emitPrivyEvent(Tt,"sendTransaction","onSuccess",h),i(h)}catch(e){he.emitPrivyEvent(Tt,"sendTransaction","onError",j.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:e,entropyIdVerifier:t}=m.getEntropyDetailsFromAccount(u),n={entropyId:e,entropyIdVerifier:t,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{he.emitPrivyEvent(Tt,"sendTransaction","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},o=X.isFundingEnabled(st)?ve.prepareFundingModalData({address:d.address,appConfig:st,fundWalletConfig:a,methodScreen:se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:w.chainId,comingFromSendTransactionScreen:!0}):void 0;ht({connectWallet:n,sendTransaction:{transactionRequest:w,transactingWallet:d,entropyId:e,entropyIdVerifier:t,onSuccess:e=>{he.emitPrivyEvent(Tt,"sendTransaction","onSuccess",e),i(e)},onFailure:e=>{he.emitPrivyEvent(Tt,"sendTransaction","onError",j.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:r||{},fundWalletConfig:a,requesterAppId:l},funding:o}),bt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),Zt=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:a,uiOptions:n,wallet:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=n||{};if(!Ce||!Pe)return he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(new j.PrivyClientError("User must be authenticated before signing with a Privy wallet",j.PrivyErrorCode.MUST_BE_AUTHENTICATED));let c=i?Pe.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):m.getPrivySolanaWallet(Pe);if(!c)return he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new j.PrivyClientError("Must have a Privy wallet before signing",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));dt(!0);let{rootWallet:d}=m.getSolanaSigningAndRootWallet(Pe,c.address);if(!await or.recoverPrimaryWallet().catch((()=>!1))||!d)throw he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new j.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${c.address} is connected`,j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);if(Ut({showWalletUIs:n?.showWalletUIs}))(async()=>{let a=await Xe();if(!a||!it)return he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new j.PrivyClientError("Must have valid access token and Privy wallet to send transaction",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{if(!await or.recoverPrimaryWallet())return he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(new j.PrivyClientError("Unable to connect to wallet",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Ut({showWalletUIs:n?.showWalletUIs})&&!await te.hasSufficientFunds(e,t))return he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.INSUFFICIENT_BALANCE),void s(new j.PrivyClientError("Solana wallet has insufficient funds for this transaction.",j.PrivyErrorCode.INSUFFICIENT_BALANCE));let{entropyId:i,entropyIdVerifier:l}=m.getEntropyDetailsFromUser(Pe),{signature:d,receipt:u}=await B.sendSolanaTransaction({accessToken:a,tx:e,connection:t,walletProxy:it,transactionOptions:r,entropyId:i,entropyIdVerifier:l,transactingWalletAddress:c.address,transactingWalletIndex:c.walletIndex??0}),h=te.createSolanaTransactionReceipt(d,u);he.emitPrivyEvent(Tt,"sendSolanaTransaction","onSuccess",h),o(h)}catch(e){he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:i,entropyIdVerifier:u}=m.getEntropyDetailsFromAccount(d),h={entropyId:i,entropyIdVerifier:u,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},y=X.isFundingEnabled(st)?ve.prepareSolanaFundingModalData({address:c.address,appConfig:st,methodScreen:se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:a,comingFromSendTransactionScreen:!0}):void 0;ht({connectWallet:h,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:c,onSuccess:e=>{he.emitPrivyEvent(Tt,"sendSolanaTransaction","onSuccess",e),o(e)},onFailure:e=>{he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:n||{},requesterAppId:l},funding:y}),bt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function er(){return new Promise((async(e,t)=>{let r=await Xe();if(!r||!it)throw Error("Must have valid access token to enroll in MFA");try{await it.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let tr=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],rr=e=>{let t=Pe?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:a}=re.toDisplayFromAccountType(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw he.emitPrivyEvent(Tt,"linkAccount","onError",j.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:a}),new j.PrivyClientError(`User already has an account of type ${r} linked.`)};async function ar({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){De(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!Ce||!Pe)throw he.emitPrivyEvent(Tt,r,"onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let a=m.getPrivyPrimaryWallet(Pe);if(!a||!it)throw he.emitPrivyEvent(Tt,r,"onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await er()}catch(e){throw he.emitPrivyEvent(Tt,r,"onError",j.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((n,i)=>{dt(!0);let o={onSuccess:e=>{he.emitPrivyEvent(Tt,r,"onSuccess","user-passcode",e),n(e)},onFailure:e=>{he.emitPrivyEvent(Tt,r,"onError",j.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),i(e)},callAuthOnSuccessOnClose:!1},s="user-passcode"===a.recoveryMethod,l=Y.toEmbeddedWalletSetRecoveryScreen({walletAction:"update",availableRecoveryMethods:st.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:d}=m.getEntropyDetailsFromAccount(a);ht({setWalletPassword:o,recoverWallet:{entropyId:c,entropyIdVerifier:d,onFailure:i},createWallet:o,connectWallet:{onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,entropyIdVerifier:d,onFailure:e=>{he.emitPrivyEvent(Tt,r,"onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s}}),bt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function nr({appId:e,action:t}){let r=await Xe();if("link"===t&&!r)throw he.emitPrivyEvent(Tt,"linkAccount","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new j.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw he.emitPrivyEvent(Tt,"login","onError",j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new j.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");St.current=`privy:${e}`,Nt.current=t;let a=Q.triggerPopup();return v.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,n)=>{let{name:i,logoUrl:o}=await V.getProviderAppMetadata({api:v.api,providerAppId:e,requesterAppId:st.id});ht({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:a,onSuccess:r,onError:n}}),Ot(se.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let ir={ready:T,authenticated:Ce,user:Pe,walletConnectors:v.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),ht({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress}}),bt(Ce?se.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:se.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:Ht,startCrossAppAuthFlow:nr,linkEmail:()=>{Bt("email"),rr("email"),St.current="email",Nt.current="link",bt(se.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{Bt("sms"),rr("phone"),St.current="sms",Nt.current="link",bt(se.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{Bt("google"),rr("google_oauth"),Nt.current="link",await or.initLoginWithOAuth("google")},linkTwitter:async()=>{Bt("twitter"),rr("twitter_oauth"),Nt.current="link",await or.initLoginWithOAuth("twitter")},linkDiscord:async()=>{Bt("discord"),rr("discord_oauth"),Nt.current="link",await or.initLoginWithOAuth("discord")},linkGithub:async()=>{Bt("github"),rr("github_oauth"),Nt.current="link",await or.initLoginWithOAuth("github")},linkSpotify:async()=>{Bt("spotify"),rr("spotify_oauth"),Nt.current="link",await or.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Bt("instagram"),rr("instagram_oauth"),Nt.current="link",await or.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Bt("tiktok"),rr("tiktok_oauth"),Nt.current="link",await or.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{Bt("linkedin"),rr("linkedin_oauth"),Nt.current="link",await or.initLoginWithOAuth("linkedin")},linkApple:async()=>{Bt("apple"),rr("apple_oauth"),Nt.current="link",await or.initLoginWithOAuth("apple")},linkPasskey:async()=>{Bt("passkey"),rr("passkey"),await or.initLinkWithPasskey(),bt(se.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if(Bt("telegram"),rr("telegram"),Nt.current="link",St.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new w.TelegramAuthFlow;v.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=w.convertInitDataRawToTelegramWebAppData(e.launchParams.initDataRaw),ht({telegramAuthModalData:{seamlessAuth:!0}}),Ot(se.ModalScreen.TELEGRAM_AUTH_SCREEN)}else he.emitPrivyEvent(Tt,"linkAccount","onError",j.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await or.initLoginWithTelegram();bt(se.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{Bt("farcaster"),rr("farcaster"),await or.initLoginWithFarcaster(),Nt.current="link",St.current="farcaster",bt(se.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(Bt("email"),!Pe?.email)throw new j.PrivyClientError("User does not have an email linked to their account.");Nt.current="update",St.current="email",bt(se.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(Bt("sms"),!Pe?.phone)throw new j.PrivyClientError("User does not have a phone number linked to their account.");Nt.current="update",St.current="sms",bt(se.ModalScreen.UPDATE_PHONE_SCREEN)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!T){let e=await new Promise((e=>{pt((t=>e.bind(t)))}));if(pt(null),e)return void console.warn(t)}!Pe||Pe.isGuest?(Nt.current="login",ht({login:e}),Ot(se.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{T||(await new Promise((e=>{pt((()=>e))})),pt(null)),Ce?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(Nt.current="login",Ot(se.ModalScreen.CONNECT_OR_CREATE))},logout:async()=>{if(Nt.current=null,St.current=null,Pe&&v.clearProviderAcccessTokens(Pe),De(null),await v.logout(),Pe&&it)try{await it.clearMfa({userId:Pe.id})}catch(e){}_e(null),Ae(!1),he.emitPrivyEvent(Tt,"logout","onSuccess"),_(!1),C.default.del(f.CLIENT_ANALYTICS_ID_KEY),C.default.del(f.getGuestCredentialStorageKey(st.id))},getAccessToken:()=>v.getCustomerAccessToken(),getEthereumProvider:()=>{if(!Pe||!Pe.wallet)return new R.PrivyProxyProvider;let e=Te.find((e=>Pe.wallet&&e.address===Pe.wallet.address)),t=v.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new R.PrivyProxyProvider},getEthersProvider:()=>{if(!Pe||!Pe.wallet)return new r.Web3Provider(new R.AsExternalProvider(new R.PrivyProxyProvider));let e=Te.find((e=>Pe.wallet&&e.address===Pe.wallet.address)),t=v.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new r.Web3Provider(new R.AsExternalProvider(e&&t?t.proxyProvider:new R.PrivyProxyProvider))},getWeb3jsProvider:()=>{if(!Pe||!Pe.wallet)return new R.AsAbstractProvider(new R.PrivyProxyProvider);let e=Te.find((e=>Pe.wallet&&e.address===Pe.wallet.address)),t=v.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new R.AsAbstractProvider(e&&t?t.proxyProvider:new R.PrivyProxyProvider)},unlinkWallet:async e=>{let t;return _e(t=e.startsWith("0x")?await v.unlinkEthereumWallet(e):await v.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await v.unlinkEmail(e);return _e(t),t},unlinkPhone:async e=>{let t=await v.unlinkPhone(e);return _e(t),t},unlinkGoogle:async e=>{let t=await v.unlinkOAuth("google",e);return _e(t),t},unlinkTwitter:async e=>{let t=await v.unlinkOAuth("twitter",e);return _e(t),t},unlinkDiscord:async e=>{let t=await v.unlinkOAuth("discord",e);return _e(t),t},unlinkGithub:async e=>{let t=await v.unlinkOAuth("github",e);return _e(t),t},unlinkSpotify:async e=>{let t=await v.unlinkOAuth("spotify",e);return _e(t),t},unlinkInstagram:async e=>{let t=await v.unlinkOAuth("instagram",e);return _e(t),t},unlinkTiktok:async e=>{let t=await v.unlinkOAuth("tiktok",e);return _e(t),t},unlinkLinkedIn:async e=>{let t=await v.unlinkOAuth("linkedin",e);return _e(t),t},unlinkApple:async e=>{let t=await v.unlinkOAuth("apple",e);return _e(t),t},unlinkFarcaster:async e=>{let t=await v.unlinkFarcaster(e);return _e(t),t},unlinkTelegram:async e=>{let t=await v.unlinkTelegram(e);return _e(t),t},unlinkPasskey:async e=>{let t=await v.unlinkPasskey(e);return _e(t),t},unlinkCrossAppAccount:async({subject:e})=>{let t=Pe?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new j.PrivyClientError("Invalid subject");v.storeProviderAccessToken(t.id,null);let r=await v.unlinkOAuth(`privy:${t.id}`,e);return _e(r),r},setActiveWallet:async e=>{let r=Te.find((r=>t.getAddress(r.address)===t.getAddress(e))),a=Pe?.linkedAccounts.find((r=>"wallet"===r.type&&t.getAddress(r.address)===t.getAddress(e)));if(r&&await r.isConnected())if(r.linked){let e=Object.assign({},Pe);e.wallet=a&&{address:a.address,chainType:a.chainType,chainId:a.chainId,walletClient:a.walletClient,walletClientType:a.walletClientType,connectorType:a.connectorType,imported:a.imported,delegated:a.delegated,walletIndex:a.walletIndex},_e(e)}else r.loginOrLink();else ht({externalConnectWallet:{suggestedAddress:e}}),Ht()},forkSession:()=>v.forkSession(),createWallet:async e=>{if(e&&"target"in e&&e&&(e=void 0),!Ce||!Pe)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return zt(Pe,15e3,e)},setWalletRecovery:async e=>ar({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>ar({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t,r)=>new Promise((async(a,n)=>{let{requesterAppId:i}=t||{};if(!Ce||!Pe)return he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let o=r??m.getPrivyEthereumWallet(Pe)?.address;if(!o)throw new j.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=m.getEthereumSigningAndRootWallet(Pe,o);if(!s||!l)return he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));dt(!0);let c=async()=>{if(!Ce)throw Error("User must be authenticated before signing with a Privy wallet");let t=await Xe();if(!it||!t||!await or.recoverPrimaryWallet())throw Error("Unable to connect to wallet");v.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:s.address,requesterAppId:i}});let{entropyId:r,entropyIdVerifier:a}=m.getEntropyDetailsFromAccount(l),{response:n}=await it.rpc({accessToken:t,entropyId:r,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:i,request:{method:"personal_sign",params:[e,s.address]}}),o=n.data;return v.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:s.address,requesterAppId:i}}),o};if(Ut({showWalletUIs:t?.showWalletUIs}))try{let e=await c();he.emitPrivyEvent(Tt,"signMessage","onSuccess",e),a(e)}catch(e){he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new U.PrivyProviderRpcError("Unable to sign message"))}else{let{entropyId:r,entropyIdVerifier:i}=m.getEntropyDetailsFromAccount(l);ht({signMessage:{method:"personal_sign",data:e,confirmAndSign:c,onSuccess:e=>{he.emitPrivyEvent(Tt,"signMessage","onSuccess",e),a(e)},onFailure:e=>{he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t||{}},connectWallet:{entropyId:r,entropyIdVerifier:i,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),bt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t,r)=>new Promise((async(a,n)=>{let{requesterAppId:i}=t||{};if(!Ce||!Pe)return he.emitPrivyEvent(Tt,"signTypedData","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let o=r??m.getPrivyEthereumWallet(Pe)?.address;if(!o)throw new j.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=m.getEthereumSigningAndRootWallet(Pe,o);if(!l||!s)return he.emitPrivyEvent(Tt,"signTypedData","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));dt(!0);let c=A.generateTypedDataWithDomainType(e),d=async()=>{if(!Ce)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Xe();if(!it||!e||!await or.recoverPrimaryWallet())throw Error("Unable to connect to wallet");v.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:s.address,requesterAppId:i}});let{entropyId:t,entropyIdVerifier:r}=m.getEntropyDetailsFromAccount(l),{response:a}=await it.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:i,request:{method:"eth_signTypedData_v4",params:[s.address,c]}}),n=a.data;return v.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:s.address,requesterAppId:i}}),n};if(Ut({showWalletUIs:t?.showWalletUIs,typedData:!0}))try{let e=await d();he.emitPrivyEvent(Tt,"signTypedData","onSuccess",e),a(e)}catch(e){he.emitPrivyEvent(Tt,"signTypedData","onError",j.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new U.PrivyProviderRpcError("Unable to sign message"))}else{let{entropyId:e,entropyIdVerifier:r}=m.getEntropyDetailsFromAccount(l);ht({signMessage:{method:"eth_signTypedData_v4",data:c,confirmAndSign:d,onSuccess:e=>{he.emitPrivyEvent(Tt,"signTypedData","onSuccess",e),a(e)},onFailure:e=>{he.emitPrivyEvent(Tt,"signTypedData","onError",j.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t||{}},connectWallet:{entropyId:e,entropyIdVerifier:r,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),bt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t,r,a)=>{let n=await Qt(e,t,r,a);return q.formatReceipt(await n.wait())},sendSolanaTransaction:async(e,t,r,a,n,i)=>{let o=i?Ie.find((({address:e})=>e===i)):Ie.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw he.emitPrivyEvent(Tt,"sendSolanaTransaction","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new j.PrivyClientError("Embedded wallet not found",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);return await Zt({transaction:e,connection:t,transactionOptions:a,uiOptions:r,fundWalletConfig:n,wallet:o})},exportWallet:e=>new Promise((async(t,r)=>{if(!Ce||!Pe)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let a=e?.address??m.getPrivyEthereumWallet(Pe)?.address;if(!a)return void r(Error("User does not have an HD Ethereum wallet. To export an imported wallet, pass the `address` of the wallet to `exportWallet`."));let{signingWallet:n,rootWallet:i}=m.getEthereumSigningAndRootWallet(Pe,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));dt(!0);let{entropyId:o,entropyIdVerifier:s}=m.getEntropyDetailsFromAccount(i),l={entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0};ht(ut),await Xe()&&it?it?(ht({keyExport:{appId:E.appId,appClientId:E.clientId,origin:v.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r},connectWallet:l}),bt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:er,async init(e){switch(e){case"sms":return void await v.initMfaSmsVerification();case"passkey":return await v.initMfaPasskeyVerification();case"totp":return;default:throw Error(`Unsupported MFA method: ${e}`)}},async submit(e,t){switch(e){case"totp":case"sms":if("string"!=typeof t)throw new j.PrivyClientError("Invalid MFA code");Pt.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{_t.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new j.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),a=ae.transformResponseToSnakeCase(await r.startAuthentication(t));Pt.current?.resolve({mfaMethod:e,mfaCode:a,relyingParty:window.origin}),await new Promise(((e,t)=>{_t.current={resolve:e,reject:t}}));break;default:throw Pt.current?.reject(new j.PrivyClientError("Unsupported MFA method")),new j.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){Pt.current?.reject(new j.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Xe();if(!t||!it)throw Error("Must have valid access token to enroll in MFA");await it.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return or.closePrivyModal(),void t();st.mfa.noPromptOnMfaRequired&&console.warn("[Privy Warning] Triggering the 'showMfaEnrollmentModal' function when 'noPromptOnMfaRequired' is set to true is unexpected. If this is intentional, ensure that you are building custom UIs for MFA verification."),ht({mfaEnrollmentFlow:{mfaMethods:st.mfa.methods,onSuccess:t,onFailure:r}}),bt(se.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await Xe();if(!e||!it)throw Error("Must have valid access token to enroll in MFA");let t=await it.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Xe();if(!t||!it)throw Error("Must have valid access token to enroll in MFA");await it.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),_e(await v.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Xe();if(!t||!it)throw Error("Must have valid access token to enroll in MFA");await it.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),_e(await v.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e}){let t=await Xe();if(!t||!it)throw Error("Must have valid access token to enroll in MFA");await it.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:e}),_e(await v.getAuthenticatedUser())},async unenroll(e){let t=await Xe();if(!t||!it)throw Error("Must have valid access token to remove MFA");"passkey"===e?await it.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:[]}):await it.unenrollMfa({method:e,accessToken:t}),_e(await v.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Xe(),t=Pe?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!it||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Pe?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await or.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await it.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&_e(await v.getAuthenticatedUser()||Pe||null),ht({farcasterSigner:r}),bt(se.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await Xe(),r=Pe?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!it||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Pe?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await or.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!Pe.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=Pe.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Xe(),r=Pe?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!it||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Pe?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await or.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!Pe.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let a=await import("@simplewebauthn/browser"),n=await it.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:a.bufferToBase64URLString(e)},fid:BigInt(Pe.farcaster.fid),relyingParty:window.origin});return new Uint8Array(a.base64URLStringToBuffer(n.signature))},createGuestAccount:async()=>{if(Pe&&!Pe.isGuest)throw Error("User cannot already be authenticated to create a guest account");return Pe?.isGuest?Pe:or.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t}){let r=Pe?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return z.sendCrossAppRequest({user:Pe,client:v,address:t,requesterAppId:st.id,request:{method:r?"privy_signSmartWalletMessage":"personal_sign",params:[e,t]},reconnect:nr})},signTypedDataWithCrossAppWallet(e,{address:t}){let r=Pe?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),a=A.generateTypedDataWithDomainType(e);return z.sendCrossAppRequest({user:Pe,client:v,address:t,requesterAppId:st.id,request:{method:r?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,a]},reconnect:nr})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=Pe?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return z.sendCrossAppRequest({user:Pe,client:v,address:t,requesterAppId:st.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e]},reconnect:nr})},isModalOpen:P,mfaMethods:st.mfa.methods};Ke=ir.signMessage,Ve=ir.signTypedData,Ge=async(...e)=>{let t=await Qt(...e);return st.embeddedWallets.waitForTransactionConfirmation&&await t.wait(),t};let or={setAuthenticated:Ae,setUser:_e,isNewUserThisSession:be,pendingTransaction:null,walletConnectionStatus:Le,connectors:v.connectors?.walletConnectors??[],solanaWallets:Ie,rpcConfig:st.rpcConfig,chains:st.chains,appId:E.appId,showFiatPrices:"native-token"!==st.embeddedWallets.priceDisplay.primary,clientAnalyticsId:v.clientAnalyticsId,customAuthStatus:Ct,noPromptOnSignature:kt,emailOtpState:Je,setEmailOtpState:Qe,smsOtpState:Ze,setSmsOtpState:et,oAuthState:at,setOAuthState:nt,siweState:tt,setSiweState:rt,isHeadlessOAuthLoading:Me,nativeTokenSymbolForChainId:e=>st.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(it)return it;let t=new Promise((e=>{Et((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),a=await Promise.race([t,r]);return Et(null),a},getAuthFlow:()=>v.authFlow,getAuthMeta:()=>v.authFlow?.meta,client:v,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=T&&Ce&&Pe;r&&St.current&&(t=tr(Pe)),"login"===Nt.current?e.shouldCallAuthOnSuccess&&r&&St.current?(he.emitPrivyEvent(Tt,"login","onComplete",Pe,be,!1,St.current,t??null),E.onSuccess?.(Pe,be)):he.emitPrivyEvent(Tt,"login","onError",j.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===Nt.current&&t?e.isSuccess&&r&&St.current?he.emitPrivyEvent(Tt,"linkAccount","onSuccess",Pe,St.current,t):St.current&&he.emitPrivyEvent(Tt,"linkAccount","onError",j.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:St.current}):"update"===Nt.current&&t&&(e.isSuccess&&r&&St.current?he.emitPrivyEvent(Tt,"update","onSuccess",Pe,St.current,t):St.current&&he.emitPrivyEvent(Tt,"update","onError",j.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:St.current}));let a=Re&&$.FUNDING_SCREENS.includes(Re),n=Re===se.ModalScreen.ERROR_SCREEN&&ut.errorModalData&&$.FUNDING_SCREENS.includes(ut.errorModalData.previousScreen);if((a||n)&&ut.funding){let e,t=$.fundingScreenMethodMap[Re]??null;if("solana"===ut.funding.chainType){let r=g(ie.SOLANA_FUNDING_PLUGIN_ID);if(!r)return void console.warn("Unable to load solana plugin, skipping balance");try{e=BigInt(await r.getBalance({address:ut.funding.address,cluster:ut.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}he.emitPrivyEvent(Tt,"fundSolanaWallet","onUserExited",{address:ut.funding.address,cluster:ut.funding.cluster,fundingMethod:t,balance:e})}else{let r=A.getJsonRpcProvider(ut.funding.chain.id,st.chains,st.rpcConfig,{appId:E.appId});try{e=(await r.getBalance(ut.funding.address)).toBigInt()}catch{console.error("Unable to pull wallet balance")}he.emitPrivyEvent(Tt,"fundWallet","onUserExited",{address:ut.funding.address,chain:ut.funding.chain,fundingMethod:t,balance:e})}}ht({...ut,externalConnectWallet:{suggestedAddress:void 0}}),Nt.current=null,St.current=null,Oe(!1),_(!1),setTimeout((()=>{v.authFlow=void 0}),200),v.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:({message:e,address:t})=>new Promise((async(r,a)=>{if(!Ce||!Pe)return he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let n=t??m.getPrivySolanaWallet(Pe)?.address;if(!n)throw new j.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:i,rootWallet:o}=m.getSolanaSigningAndRootWallet(Pe,n);if(!i||!o)return he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));dt(!0);let s=async()=>{if(!Ce)throw Error("User must be authenticated before signing with a Privy wallet");let t=await v.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=or.walletProxy??await or.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await or.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!o)throw Error("No root wallet for signing wallet found");let{entropyId:a,entropyIdVerifier:n}=m.getEntropyDetailsFromAccount(o),{response:s}=await r.rpc({accessToken:t,entropyId:a,entropyIdVerifier:n,chainType:"solana",hdWalletIndex:i.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return s.data.signature};if(Ut({showWalletUIs:void 0}))try{let e=await s();r({signature:e})}catch(e){a(e)}else{let{entropyId:t,entropyIdVerifier:n}=m.getEntropyDetailsFromAccount(o);ht({signMessage:{method:"solana_signMessage",data:e,confirmAndSign:s,onSuccess:e=>{r({signature:e})},onFailure:e=>{a(e)},uiOptions:{}},connectWallet:{entropyId:t,entropyIdVerifier:n,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{he.emitPrivyEvent(Tt,"signMessage","onError",j.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Ot(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),openPrivyModal:bt,connectWallet:Lt,initLoginWithWallet:async(e,t,r)=>{O.isBaseConnectedEthereumWallet(e)?(St.current="siwe",xt(e,t,r)):(St.current="siws",qt(e,t))},loginWithWallet:async()=>{let e,t,r;if(!T)throw new j.PrivyNotReadyError;if(v.authFlow instanceof h.SiweFlow?e="siwe":v.authFlow instanceof y.SiwsFlow&&(e="siws"),!e)throw new j.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await v.getAccessToken())try{({user:t}=await v.link()),St.current=e}catch(t){throw he.emitPrivyEvent(Tt,"linkAccount","onError",t.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await v.authenticate()),St.current=e}catch(e){throw he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}_e(t||Pe||null),Oe(r||!1),Ae(!0)},delegateWallet:async({address:e,chainType:t})=>new Promise((async(r,a)=>{let n=await Xe();if(!Ce||!Pe||!n)throw new j.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new j.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let i=or.walletProxy??await or.initializeWalletProxy(15e3);if(!i)throw new j.PrivyClientError("Wallet proxy not initialized.");if(L.isWalletDelegated({address:e,chainType:t,user:Pe}))return r();let o=L.getDelegatedWalletsData({address:e,user:Pe}),s=L.getRootWalletDataForDelegation({address:e,user:Pe});await or.recoverPrimaryWallet(),ht({delegatedActions:{consent:{address:e,onDelegate:async()=>{await i.createDelegatedAction({accessToken:n,rootWallet:s,delegatedWallets:[o]}),await or.refreshUser()},onSuccess:async()=>{r()},onError:async e=>{a(e)}}}}),bt(se.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),revokeDelegatedWallets:async()=>new Promise((async(e,t)=>{if(!Ce||!Pe)throw new j.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===L.getDelegatedWalletsForUser(Pe).length)throw new j.PrivyClientError("User has no delegated wallets to revoke.");ht({delegatedActions:{revoke:{onRevoke:async()=>{await v.revokeDelegatedWallet(),await or.refreshUser()},onSuccess:async()=>{e()},onError:async e=>{t(e)}}}}),bt(se.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN)})),initLoginWithFarcaster:async(e,t)=>{let r=new c.FarcasterFlow(e,t);v.startAuthFlow(r);try{St.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===Nt.current?he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Nt.current&&he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!T)throw new j.PrivyNotReadyError;if(!(v.authFlow instanceof c.FarcasterFlow))throw new j.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await v.getAccessToken())try{({user:e}=await v.link()),St.current="farcaster"}catch(e){throw he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await v.authenticate()),St.current="farcaster"}catch(e){throw he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}_e(e||null),Oe(t||!1),Ae(!0)},async loginWithGuestAccountFlow(){let e=new d.GuestFlow(this.appId);v.startAuthFlow(e);try{Nt.current="login",St.current="guest";let{user:e,isNewUser:t}=await v.authenticate();if(t=t||!1,!e)throw new j.PrivyClientError("Unable to authenticate guest account");if(m.shouldProceedtoEmbeddedWalletCreationFlow(e,st.embeddedWallets.createOnLogin))try{await zt(e,15e3),e=await or.refreshUser()}catch(t){_e(e),console.warn("Unable to create embedded wallet for guest account")}else _e(e);return Oe(t),Ae(!0),he.emitPrivyEvent(Tt,"login","onComplete",e,t,!1,"guest",null),e}catch(e){throw he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let a=`privy:${e}`;St.current=a;let{url:n,stateCode:i,codeVerifier:o}=await V.getCrossAppAuthorizationUrl({api:v.api,appId:e});if(!n)throw v.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new j.PrivyClientError("No authorization URL returned for cross-app auth.");try{let s=await G.popupCrossAppAuthFlow({url:n,popup:t,provider:a}),l=s.stateCode,c=s.authorizationCode;if(l!==i)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:i??"",returnedStateCode:l??""}}),new j.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,j.PrivyErrorCode.OAUTH_UNEXPECTED);let d=await V.authenticateCrossAppAccount({appId:e,codeVerifier:o,stateCode:l,authorizationCode:c,action:r,client:v});d&&v.storeProviderAccessToken(e,d);let u=await or.refreshUser();if(!u)throw new j.PrivyClientError("Unable to update user");return v.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),u}catch(e){throw v.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(St.current=e,!C.isLocalStorageAccessible())return void Ot(se.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&J.default(window.navigator.userAgent))return void Ot(se.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:K.USE_BROADCAST_CHANNEL_EVENT_TYPE},"*"),C.default.del(f.HEADLESS_OAUTH_KEY),C.default.del(f.OAUTH_DISABLE_SIGNUP_KEY);let a=new ge.OAuthFlow({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&a.addCaptchaToken(t),v.startAuthFlow(a);let n=await v.authFlow.getAuthorizationUrl();n&&n.url&&("twitter"===e&&i.isAndroid&&(n.url=n.url.replace("x.com","twitter.com")),window.location.assign(n.url))},async initLoginWithTelegram(e,t){if(!T)throw new j.PrivyNotReadyError;St.current="telegram";let r=new w.TelegramAuthFlow(e,t);v.startAuthFlow(r),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>st.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:st.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new j.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new j.PrivyClientError("Telegram was not initialized")):t(new j.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(v.authFlow instanceof w.TelegramAuthFlow))throw new j.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");if(v.authFlow.meta.captchaToken||=e,"login"===Nt.current)try{let e=await v.authenticate();t=e.user,r=e.isNewUser,St.current="telegram"}catch(e){throw he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==Nt.current)throw new j.PrivyClientError("Unknown auth intent");try{t=(await v.link()).user,St.current="telegram"}catch(e){throw he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}_e(t),Oe(r||!1),Ae(!0)},async recoveryOAuthFlow(e,t,r){let a,n;function i(t){if(!t)throw v.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new j.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,o,{url:s,codeVerifier:l,stateCode:c}=await Y.getRecoveryAuthorizationUrl({api:He.api,provider:e});i(s);try{let a=await Z.popupOAuthFlow({url:s,popup:r,provider:e});if(t=a.stateCode,o=a.authorizationCode,t!==c)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:c??"",returnedStateCode:t??""}}),new j.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,j.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw v.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new j.PrivyClientError("Recovery OAuth failed")}[a,n]=await Promise.all([Xe(),Y.authenticateRecovery({api:He.api,provider:e,codeVerifier:l,stateCode:t,authorizationCode:o})]);break}case"icloud":{let{url:t}=await Y.getRecoveryAuthorizationUrl({api:He.api,provider:e});i(t);let{ckWebAuthToken:o}=await Z.popupOAuthFlow({url:t,popup:r,provider:e});n=o,a=await Xe()}}if(!it)throw new j.PrivyClientError("Cannot connect to wallet proxy");if(!a)throw new j.PrivyClientError("Unable to authorize user");switch(t){case"recover":{let t=ut.recoverWallet?.entropyId,r=ut.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new j.PrivyClientError("Recovery OAuth failed");v.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await it.recover({accessToken:a,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:n}),v.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{v.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await it.create({accessToken:a,recoveryAccessToken:n,recoveryMethod:e});let t=m.getPrivyEthereumWallet(await or.refreshUser());if(!t)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");v.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),he.emitPrivyEvent(Tt,"createWallet","onSuccess",t);break}case"set-recovery":{let t=m.getPrivyPrimaryWallet(Pe);if(!t)throw he.emitPrivyEvent(Tt,"setWalletRecovery","onError",j.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");v.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:i}=m.getEntropyDetailsFromAccount(t);await it.setRecovery({accessToken:a,entropyId:r,entropyIdVerifier:i,recoveryMethod:e,recoveryAccessToken:n});let o=m.getPrivyPrimaryWallet(await or.refreshUser());if(!o)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");v.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),he.emitPrivyEvent(Tt,"setWalletRecovery","onSuccess",e,o);break}default:throw new j.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,a;if(!(v.authFlow instanceof ge.OAuthFlow))throw new j.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let n=C.default.get(f.STATE_CODE_KEY),i=v.authFlow.meta.stateCode;if(n!==i)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:n??"",returnedStateCode:i??""}}),new j.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,j.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await v.getAccessToken())try{let r=await v.link();t=r.user,a=r.oAuthTokens,St.current=e}catch(t){throw he.emitPrivyEvent(Tt,"linkAccount","onError",t.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let n=await v.authenticate();t=n.user,r=n.isNewUser,a=n.oAuthTokens,St.current=e}catch(t){throw"login"===Nt.current?he.emitPrivyEvent(Tt,"login","onError",t.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Nt.current&&he.emitPrivyEvent(Tt,"linkAccount","onError",t.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return _e(t),Oe(r||!1),Ae(!0),a&&t&&he.emitPrivyEvent(Tt,"oAuthAuthorization","onOAuthTokenGrant",a,{user:t}),a},passkeyAuthState:qe,setPasskeyAuthState:je,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new u.PasskeyFlow({captchaToken:e,setPasskeyAuthState:je});v.startAuthFlow(r),Nt.current="login";try{St.current="passkey",je({status:"generating-challenge"}),await r.initRegisterFlow(t),je({status:"awaiting-passkey"})}catch(e){throw je({status:"error",error:e}),he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!T)throw new j.PrivyNotReadyError;if(!(v.authFlow instanceof u.PasskeyFlow))throw new j.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==St.current){let e=new j.PrivyClientError("Must init login with Passkey flow first.");throw je({status:"error",error:e}),e}let r=await Xe();try{St.current="passkey",je({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await v.authenticate())}catch(e){throw je({status:"error",error:e}),he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}_e(e),Oe(t||!1),Ae(!0),je({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new u.PasskeyFlow({captchaToken:e,setPasskeyAuthState:je});v.startAuthFlow(r),Nt.current="login";try{St.current="passkey",je({status:"generating-challenge"}),await r.initAuthenticationFlow(t),je({status:"awaiting-passkey"})}catch(e){throw je({status:"error",error:e}),he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(){let e,t;if(!T)throw new j.PrivyNotReadyError;if(!(v.authFlow instanceof u.PasskeyFlow))throw new j.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==St.current){let e=new j.PrivyClientError("Must init login with Passkey flow first.");throw je({status:"error",error:e}),e}let r=await Xe();try{St.current="passkey",je({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await v.authenticate())}catch(e){throw je({status:"error",error:e}),he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}_e(e),Oe(t||!1),Ae(!0),je({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLinkWithPasskey(e){let t=new u.PasskeyFlow({captchaToken:e});v.startAuthFlow(t),Nt.current="link",St.current="passkey",je({status:"generating-challenge"});try{await t.initLinkFlow(),je({status:"awaiting-passkey"})}catch(e){throw he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),je({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!T)throw new j.PrivyNotReadyError;if(!(v.authFlow instanceof u.PasskeyFlow))throw new j.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==St.current)throw new j.PrivyClientError("Must init login with Passkey flow first.");try{St.current="passkey",({user:e}=await v.link())}catch(e){throw he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return _e(e||Pe||null),je({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!C.isLocalStorageAccessible())throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");if("google"===e&&J.default(window.navigator.userAgent))throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let a=new ge.OAuthFlow({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&a.addCaptchaToken(t),nt({status:"loading"});let n=await v.startAuthFlow(a).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,r,a;Fe(!0),nt({status:"loading"}),v.startAuthFlow(new ge.OAuthFlow(e));let n=C.default.get(f.STATE_CODE_KEY),i=e.stateCode;if(n!==i)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:n??"",returnedStateCode:i??""}}),Fe(!1),new j.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,j.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await v.getAccessToken())try{({user:t,oAuthTokens:a}=await v.link()),St.current=e.provider;let r=tr(t);t&&r&&he.emitPrivyEvent(Tt,"linkAccount","onSuccess",t,St.current,r)}catch(t){throw Fe(!1),he.emitPrivyEvent(Tt,"linkAccount","onError",t.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:a}=await v.authenticate()),St.current=e.provider;let n=tr(t);t&&n&&void 0!==r&&he.emitPrivyEvent(Tt,"login","onComplete",t,r,!1,St.current,n)}catch(e){throw Fe(!1),nt({status:"error",error:e}),he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return _e(t),Oe(r||!1),Ae(!0),Fe(!1),nt({status:"done"}),a&&t&&he.emitPrivyEvent(Tt,"oAuthAuthorization","onOAuthTokenGrant",a,{user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{let n=new l.EmailFlow({email:e,captchaToken:t,disableSignup:r});v.startAuthFlow(n);try{St.current="email",Qe({status:"sending-code"}),await n.sendCodeEmail({withPrivyUi:a}),Qe({status:"awaiting-code-input"})}catch(e){throw Qe({status:"error",error:e}),"login"===Nt.current?he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Nt.current&&he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let a=new l.UpdateEmailFlow(e,t,r);v.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){he.emitPrivyEvent(Tt,"update","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:St.current})}},initUpdatePhone:async(e,t,r)=>{let a=new p.UpdateSmsFlow(e,t,r);v.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){he.emitPrivyEvent(Tt,"update","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:St.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{et({status:"sending-code"});let n=new p.SmsFlow({phoneNumber:e,captchaToken:t,disableSignup:r});v.startAuthFlow(n);try{St.current="sms",await n.sendSmsCode({withPrivyUi:a}),et({status:"awaiting-code-input"})}catch(e){throw et({status:"error",error:e}),"login"===Nt.current?he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Nt.current&&he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(v.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(v.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function a(e){v.authFlow instanceof l.EmailFlow?Qe(e):v.authFlow instanceof p.SmsFlow&&et(e)}if(a({status:"submitting-code"}),!T){let e=new j.PrivyNotReadyError;throw a({status:"error",error:e}),e}if(v.authFlow instanceof l.EmailFlow)v.authFlow.meta.emailCode=e.trim();else{if(!(v.authFlow instanceof p.SmsFlow)){let e=new j.PrivyClientError("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}v.authFlow.meta.smsCode=e.trim()}let n=await Xe();if("link"===Nt.current)try{({user:t}=await v.link())}catch(e){throw a({status:"error",error:e}),he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:St.current}),e}else if("update"===Nt.current)try{({user:t}=await v.link())}catch(e){throw a({status:"error",error:e}),he.emitPrivyEvent(Tt,"update","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:St.current}),e}else try{({user:t,isNewUser:r}=await v.authenticate())}catch(e){throw a({status:"error",error:e}),he.emitPrivyEvent(Tt,"login","onError",e.privyErrorCode||j.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let i=t||Pe;_e(i||null),Oe(r||!1),Ae(!0),a({status:"done"});let o=null;return v.authFlow instanceof l.EmailFlow?o=i?.linkedAccounts.find((({type:e})=>"email"===e))||null:v.authFlow instanceof p.SmsFlow&&(o=i?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:i,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,linkedAccount:o}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{Nt.current="link",St.current="siwe",rt({status:"generating-message"});let a=await v.generateSiweNonce({address:e,captchaToken:r});return rt({status:"awaiting-signature"}),ee.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await v.generateSiweNonce({address:e});return ee.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let a;a=await v.linkSmartWallet({message:e,signature:t,smartWalletType:r}),_e((a=await or.refreshUser()??a)||Pe||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})=>{let i;Bt("siwe");let o=null;try{rt({status:"submitting-signature"}),i=await v.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}),i=await or.refreshUser()??i,rt({status:"done"}),(o=tr(i)||null)&&he.emitPrivyEvent(Tt,"linkAccount","onSuccess",i,"siwe",o)}catch(e){throw he.emitPrivyEvent(Tt,"linkAccount","onError",e.privyErrorCode||j.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),Nt.current=null,St.current=null,rt({status:"error",error:e}),e}let s=i||Pe;return _e(s||null),Nt.current=null,St.current=null,{user:s,linkedAccount:o}},refreshUser:async()=>{let e=await v.getAuthenticatedUser();return Ae(!!e),_e(e),e},walletProxy:it,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>v.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await v.acceptTerms();return _e(e),e},getUsdTokenPrice:e=>v.getUsdTokenPrice(e),getUsdPriceForSol:()=>v.getUsdPriceForSol(),getSplTokenMetadata:e=>v.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let a=m.getPrivyPrimaryWallet(e?.user??Pe)||m.getImportedPrivyEthereumWallet(e?.user??Pe)||m.getImportedPrivySolanaWallet(e?.user??Pe),n=await Xe();if(!n||!it||!a)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));dt(!0);let{entropyId:i,entropyIdVerifier:o}=m.getEntropyDetailsFromAccount(a);try{await it.connect({accessToken:n,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){x.errorIndicatesRecoveryIsNeeded(e)&&"privy"===a.recoveryMethod?(v.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}}),(await it.recover({entropyId:i,entropyIdVerifier:o,accessToken:n})).entropyId||r(Error("Unable to recover wallet")),v.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)):x.errorIndicatesRecoveryIsNeeded(e)&&"privy"!==a.recoveryMethod?(ht({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover"}}),bt(Y.embeddedWalletRecoveryScreen(a.recoveryMethod))):r(e)}})),createEmbeddedSolanaWallet:async e=>{if(e&&"target"in e&&(e=void 0),!Ce||!Pe)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let a=m.getPrivyEthereumWallet(e),n=m.getPrivySolanaWallet(e),i=r&&"createAdditional"in r&&r.createAdditional,o=r&&"walletIndex"in r?r.walletIndex:void 0,s=(m.getLatestPrivySolanaWallet(e)?.walletIndex??-1)+1;if(n&&!i&&"number"!=typeof o)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof o&&o<0)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${o}) is invalid.`);let[l,c]=await Promise.all([or.initializeWalletProxy(t),Xe()]);if(!l||!c)throw he.emitPrivyEvent(Tt,"createWallet","onError",j.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await Xt({user:e,wp:l,accessToken:c,walletIndex:o??s,ethereumWallet:a})})(Pe,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!Ce||!Pe)return void r(Error("User must be authenticated before exporting their Privy wallet"));let a=e?.address??m.getPrivySolanaWallet(Pe)?.address;if(!a)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:n,rootWallet:i}=m.getSolanaSigningAndRootWallet(Pe,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));if(dt(!0),!await Xe()||!it)return void r(Error("Must have valid access token to enroll in MFA"));if(!it)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=m.getEntropyDetailsFromAccount(i);ht({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0},keyExport:{appId:E.appId,appClientId:E.clientId,origin:v.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r}}),bt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{fe(!0),yt?.(e)},updateWallets:()=>Gt(),fundWallet:async(e,t)=>{let r=se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;ht({funding:ve.prepareFundingModalData({address:e,appConfig:st,fundWalletConfig:t,methodScreen:r})}),bt(r)},openModal:bt,requestFarcasterSignerStatus:async e=>{let t=await Xe(),r=Pe?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!it||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Pe?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let a=await v.requestFarcasterSignerStatus(e);return"approved"===a.status&&_e(await v.getAuthenticatedUser()||Pe||null),a},connectCoinbaseSmartWallet:async()=>{st.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=v.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||v.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Lt(e);await Ft("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await v.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return _e(l),l}};ze=or.recoverPrimaryWallet,Ye=or.recoverPrimaryWallet,$e=or.solanaSignMessage;let sr=n.useMemo((()=>({wallets:Te,ready:vt&&Wt})),[Te,vt,Wt]),lr=v.authFlow instanceof w.TelegramAuthFlow,cr=!st.headless&&st.captchaEnabled&&!Ce&&(T||lr);/*#__PURE__*/return e.jsx(we.PrivyContext.Provider,{value:ir,children:/*#__PURE__*/e.jsx(he.PrivyEventsContext.Provider,{value:Tt,children:/*#__PURE__*/e.jsx(Ee.UseWalletsContext.Provider,{value:sr,children:/*#__PURE__*/e.jsx(ue.CaptchaProvider,{...st,children:/*#__PURE__*/e.jsxs(ye.InternalPrivyContext.Provider,{value:or,children:[/*#__PURE__*/e.jsx(oe.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(pe.ModalProvider,{data:ut,setModalData:ht,setInitialScreen:De,initialScreen:Re,authenticated:Ce,open:P,children:[E.children,cr&&/*#__PURE__*/e.jsx(W.Captcha,{delayedExecution:!1}),/*#__PURE__*/e.jsx(ce.GlobalStyle,{theme:{...st.appearance.palette||{}}}),!st.render.standalone&&/*#__PURE__*/e.jsx(I.LoginModal,{open:P})]})}),ct&<?/*#__PURE__*/e.jsx(F.EmbeddedWalletIframe,{appId:E.appId,appClientId:E.clientId,clientAnalyticsId:v.clientAnalyticsId,origin:v.apiUrl,mfaMethods:Pe?.mfaMethods,mfaPromise:Pt,mfaSubmitPromise:_t,onLoad:ot,onLoadFailed:()=>null}):null,st.loginConfig.telegramAuthConfiguration&&
|
|
2
|
-
/*#__PURE__*/e.jsx(le.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(S.TelegramLoginButton,{scriptHost:E.apiUrl||f.DEFAULT_PRIVY_API_URL,botUsername:st.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};exports.ConnectorManager=De,exports.Embedded1193Provider=Re,exports.EmbeddedSolanaProvider=Be,exports.PrivyClient=qe,exports.PrivyProvider=({config:t,...r})=>{var a;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new j.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(a=r.appId)||25!==a.length)throw new j.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");He||(He=new qe({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let n=Object.assign({},t);return void 0!==r.createPrivyWalletOnLogin&&void 0===n.embeddedWallets?.createOnLogin&&(n.embeddedWallets||(n.embeddedWallets={}),n.embeddedWallets.createOnLogin=r.createPrivyWalletOnLogin?"users-without-wallets":"off"),void 0!==r.createPrivyWalletOnLogin&&t?.embeddedWallets?.createOnLogin&&console.warn("Both `createPrivyWalletOnLogin` and `config.embeddedWallets.createOnLogin` are set. `createPrivyWalletOnLogin` is deprecated and should be removed."),/*#__PURE__*/e.jsx(N.PrivyAppConfigProvider,{client:He,clientConfig:n,legacyCreateEmbeddedWalletFlag:r.createPrivyWalletOnLogin,children:/*#__PURE__*/e.jsx(ne.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(at,{...r,client:He})})})},exports.getAccessToken=Xe,exports.getCustomerAccessToken=function(){return He?He.getCustomerAccessToken():Promise.resolve(C.default.get(f.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.globalRecoverEthereumModal=et,exports.globalRecoverSolanaModal=tt,exports.globalSignMessageModal=Je,exports.globalSignSolanaModal=rt,exports.globalSignTypedDataModal=Qe,exports.globalTransactModal=Ze,exports.loadConnectionHistory=Me;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t}from"react/jsx-runtime";import{getAddress as r}from"@ethersproject/address";import{Web3Provider as a}from"@ethersproject/providers";import{createStore as n}from"mipd";import{useState as i,useRef as o,useEffect as s,useMemo as l}from"react";import{isAndroid as c}from"react-device-detect";import{populateTransactionRequest as d,calculateTotalGasEstimate as u,ProviderErrors as h}from"@privy-io/js-sdk-core";import{CustomJwtAccountFlow as p}from"./auth-flows/custom-jwt-account.mjs";import{UpdateEmailFlow as w,EmailFlow as m}from"./auth-flows/email.mjs";import{FarcasterFlow as y}from"./auth-flows/farcaster.mjs";import{GuestFlow as f}from"./auth-flows/guest.mjs";import{PasskeyFlow as g}from"./auth-flows/passkey.mjs";import{SiweFlow as E}from"./auth-flows/siwe.mjs";import{SiwsFlow as _}from"./auth-flows/siws.mjs";import{UpdateSmsFlow as A,SmsFlow as T}from"./auth-flows/sms.mjs";import{TelegramAuthFlow as v,convertInitDataRawToTelegramWebAppData as C,detectCompletingTelegramFlow as I}from"./auth-flows/telegram.mjs";import{v4 as W}from"uuid";import{AccessToken as k}from"./accessToken.mjs";import{getEntropyDetailsFromAccount as N,convertUserResponseToUser as b,getPrivySolanaHDWallets as U,getImportedPrivySolanaWallet as O,getPrivyPrimaryWallet as S,getPrivyEthereumWallet as R,getPrivyEthereumHDWallets as P,getImportedPrivyEthereumWallet as D,shouldProceedtoEmbeddedWalletCreationFlow as M,getPrivySolanaWallet as L,getLatestPrivyEthereumWallet as F,getSolanaSigningAndRootWallet as x,getEthereumSigningAndRootWallet as j,getLatestPrivySolanaWallet as B,getEntropyDetailsFromUser as V}from"./client/user.mjs";import H from"eventemitter3";import{CONNECTORS_STATE_KEY as K,CONNECTIONS_HISTORY_KEY as G,DEFAULT_PRIVY_API_URL as z,DEFAULT_API_TIMEOUT_MS as q,CLIENT_ANALYTICS_ID_KEY as $,CUSTOMER_ACCESS_TOKEN_STORAGE_KEY as Y,PRIVY_ACCESS_TOKEN_STORAGE_KEY as X,getGuestCredentialStorageKey as Q,HEADLESS_OAUTH_KEY as J,OAUTH_DISABLE_SIGNUP_KEY as Z,STATE_CODE_KEY as ee,WALLET_PROXY_TIMEOUT as te,FORKED_TOKEN_STORAGE_KEY as re}from"./constants.mjs";import ae,{isLocalStorageAccessible as ne}from"./storage.mjs";import{getJsonRpcProvider as ie,generateTypedDataWithDomainType as oe,toHex as se,detectInjectedConnectors as le,formatChainIdToCAIP2 as ce}from"./utils/index.mjs";import{CoinbaseWalletConnector as de}from"./connectors/coinbase.mjs";import{EmbeddedWalletConnector as ue}from"./connectors/embedded.mjs";import{isSupportedEthereumRpcMethod as he}from"./embedded-wallets/rpc/types.mjs";import{Captcha as pe}from"./components/Captcha.mjs";import{LoginModal as we}from"./components/LoginModal.mjs";import{TelegramLoginButton as me}from"./components/TelegramLoginButton.mjs";import{PrivyAppConfigProvider as ye,useAppConfig as fe,useIsServerConfigLoaded as ge}from"./configuration/context.mjs";import{areWalletArraysEqual as Ee}from"./connectors/areWalletArraysEqual.mjs";import{PrivyProviderRpcError as _e,ProviderRpcError as Ae}from"./connectors/errors.mjs";import{isPhantomInstalled as Te}from"./connectors/is-wallet-installed.mjs";import{isBaseConnectedEthereumWallet as ve}from"./connectors/isBaseConnectedEthereumWallet.mjs";import{PrivyProxyProvider as Ce,AsExternalProvider as Ie,AsAbstractProvider as We}from"./connectors/privyProxyProvider.mjs";import{isSolanaWalletConnector as ke,isBaseConnectedSolanaWallet as Ne}from"./connectors/solana/index.mjs";import{WalletConnectV2WalletConnector as be}from"./connectors/walletconnect-v2.mjs";import{EmbeddedWalletIframe as Ue}from"./embedded-wallets/EmbeddedWalletIframe.mjs";import{isWalletDelegated as Oe,getDelegatedWalletsData as Se,getRootWalletDataForDelegation as Re,getDelegatedWalletsForUser as Pe}from"./embedded-wallets/delegated-actions.mjs";import{errorIndicatesRecoveryIsNeeded as De}from"./embedded-wallets/errors.mjs";import{formatReceipt as Me,getAndCheckBalance as Le,sendTransaction as Fe}from"./embedded-wallets/rpc/index.mjs";import{PrivyClientError as xe,formatApiError as je,formatPrivyError as Be,PrivyErrorCode as Ve,PrivyNotReadyError as He,PrivyConnectorError as Ke,PrivyError as Ge}from"./errors.mjs";import{signSolanaTransaction as ze,sendSolanaTransaction as qe}from"./embedded-wallets/solana/transaction.mjs";import{extractChainIdFromCAIP2 as $e}from"./lib/caip2.mjs";import{USE_BROADCAST_CHANNEL_EVENT_TYPE as Ye,isPrivyTheOAuthProvider as Xe,CROSS_APP_BROADCAST_CHANNEL_NAME as Qe}from"./lib/cross-app/index.mjs";import{getCrossAppAuthorizationUrl as Je,authenticateCrossAppAccount as Ze,getProviderAppMetadata as et}from"./lib/cross-app/authFlow.mjs";import{popupCrossAppAuthFlow as tt}from"./lib/cross-app/popupCrossAppAuthFlow.mjs";import{sendCrossAppRequest as rt}from"./lib/cross-app/sendCrossAppRequest.mjs";import{getRecoveryAuthorizationUrl as at,authenticateRecovery as nt,embeddedWalletRecoveryScreen as it,toEmbeddedWalletSetRecoveryScreen as ot}from"./lib/embeddedWalletRecovery.mjs";import{FUNDING_SCREENS as st,fundingScreenMethodMap as lt}from"./lib/funding/index.mjs";import{isFundingEnabled as ct}from"./lib/funding/isFundingEnabled.mjs";import dt from"./lib/isEmbeddedWebview.mjs";import{triggerPopup as ut}from"./lib/popup/triggerPopup.mjs";import{popupOAuthFlow as ht}from"./lib/popupOAuthFlow.mjs";import{prepareSiweMessageWithNonce as pt}from"./lib/siwe.mjs";import{hasSufficientFunds as wt,createSolanaTransactionReceipt as mt}from"./lib/solana/transaction.mjs";import{toDisplayFromAccountType as yt}from"./lib/toDisplayFromAccountType.mjs";import{transformResponseToSnakeCase as ft}from"./passkeys/transformResponseToSnakeCase.mjs";import{PrivyPluginProvider as gt,usePlugins as Et}from"./plugins/context/PrivyPluginContext.mjs";import{SOLANA_FUNDING_PLUGIN_ID as _t}from"./plugins/solana-funding/id.mjs";import{RecentlyUsedAccountProvider as At}from"./recent-login/context.mjs";import{ModalScreen as Tt}from"./screens/index.mjs";import{Hide as vt}from"./screens/LandingScreen/styles.mjs";import{GlobalStyle as Ct}from"./styles.mjs";import{notImplemented as It}from"./hooks/index.mjs";import{CaptchaProvider as Wt}from"./hooks/captcha-context.mjs";import{privyEventsDefault as kt,emitPrivyEvent as Nt,PrivyEventsContext as bt}from"./hooks/events-context.mjs";import{InternalPrivyContext as Ut}from"./hooks/internal-context.mjs";import{ModalProvider as Ot}from"./hooks/modal-context.mjs";import{PrivyContext as St}from"./hooks/privy-context.mjs";import{UseWalletsContext as Rt}from"./hooks/useWallets.mjs";import{prepareSolanaFundingModalData as Pt,prepareFundingModalData as Dt}from"./lib/funding/prepareFundingModalData.mjs";import{detectCompletingOAuthFlow as Mt}from"./auth-flows/oauth/detectCompletingOAuthFlow.mjs";import{OAuthFlow as Lt}from"./auth-flows/oauth/OAuthFlow.mjs";import{getRpcTimeout as Ft}from"./connectors/getRpcTimeout.mjs";import{EmbeddedProviderError as xt}from"./connectors/providerTypes.mjs";import{isEthereumWalletConnector as jt}from"./connectors/ethereum/index.mjs";import{LegacyInjectedWalletConnector as Bt,Injected6963WalletConnector as Vt}from"./connectors/injected.mjs";import{MetamaskWalletConnector as Ht}from"./connectors/metamask.mjs";import{PhantomEthereumNullWalletConnector as Kt}from"./connectors/phantom.mjs";import{PhantomSolanaNullWalletConnector as Gt}from"./connectors/phantom-solana.mjs";import{Http as zt}from"./http.mjs";import{getPaymasterContext as qt}from"./lib/smart-wallet-helpers.mjs";import{transformOptionsToCamelCase as $t}from"./passkeys/transformOptionsToCamelCase.mjs";import{mfaPasswordlessSmsInitPath as Yt,mfaPasskeyInitPath as Xt,acceptTermsPath as Qt,unlinkEmailPath as Jt,unlinkPhonePath as Zt,unlinkWalletPath as er,siwsUnlinkWalletPath as tr,unlinkOAuthPath as rr,unlinkFarcasterPath as ar,telegramAccountUnlinkPath as nr,unlinkPasskeyPath as ir,delegatedActionsRevokePath as or,analyticsEventsPath as sr,moonpayPluginOnRampPath as lr,coinbaseOnRampInitPath as cr,coinbaseOnRampStatusPath as dr,siweInitPath as ur,siweAuthenticatePath as hr,siweLinkPath as pr,smartWalletLinkPath as wr,siwsInitPath as mr,siwsAuthenticatePath as yr,transferOAuthPath as fr,telegramAccountTransferPath as gr,transferFarcasterPath as Er,transferWalletPath as _r,transferPhonePath as Ar,transferEmailPath as Tr,siwsLinkPath as vr}from"./paths.mjs";import{AccessTokenTypes as Cr,Session as Ir}from"./session.mjs";class Wr extends H{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new xt(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Hr()||!this.address)throw new xt("Disconnected",4900);return(await zr(t,void 0,void 0,this.address)).hash}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new xt(`Invalid params for ${e.method}`,4200);if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new xt(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.provider=ie(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",t)}async handlePersonalSign(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for personal_sign");let t=e.params[0],r=e.params[1];return await Kr(t,void 0,r)}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],r="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1];return await Gr(oe(r),void 0,t)}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;let t={...e.params[0],chainId:se(this.chainId)};try{return await this.provider.send("eth_estimateGas",[t])}catch(e){console.warn(`Gas estimation failed with error: ${e}. Retrying gas estimation by omitting the 'from' address`);try{return delete t.from,await this.provider.send("eth_estimateGas",[t])}catch(t){throw console.warn(`Gas estimation failed with error: ${t} when omitting the 'from' address`),e}}}async request(e){switch(console.debug("Embedded1193Provider.request() called with args",e),e.method){case"eth_accounts":case"eth_requestAccounts":return this.address?[this.address]:[];case"eth_chainId":return se(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!he(e.method))return this.provider.send(e.method,e.params);{let t=await Hr();if(await qr(),!t||!this.address)throw new xt("Disconnected",4900);try{return(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:{method:e.method,params:e.params}})).response.data}catch(e){throw console.error(e),new xt("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:a,rpcConfig:n,chains:i,appId:o,chainId:s=1,walletIndex:l}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=a,this.chainId=s,this.rpcConfig=n,this.chains=i,this.provider=ie(s,this.chains,n,{appId:o}),this.rpcTimeoutDuration=Ft(n,"privy"),this.appId=o,this.walletIndex=l}}class kr extends H{get wallets(){let e=new Set,t=this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}`;return!e.has(r)&&(e.add(r),!0)})),r=t.findIndex((e=>e.address===(this.activeWallet?this.activeWallet:"unknown")));return r>=0&&t.unshift(t.splice(r,1)[0]),t}async initialize(){if(this.initialized)return;ae.get(K)&&(ae.getKeys().forEach((e=>{e.startsWith("walletconnect")&&ae.del(e)})),ae.del(K));let e=le({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector("injected",e,{eip6963InjectedProvider:t,legacyInjectedProvider:r})}))}));this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector("coinbase_wallet","coinbase_wallet"),!Te()&&this.walletList.includes("phantom")&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&this.createEthereumWalletConnector("phantom","phantom"),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&this.addWalletConnector(new Gt)),this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector("wallet_connect_v2","unknown"),this.externalWalletConfig.solana.connectors?.get().forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{e?.forEach(this.addSolanaWalletConnector)})),await e,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(jt).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(jt).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e,t){return this.walletConnectors.filter(ke).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&t.walletClientType===e.walletClientType));t&&(e.connectedAt=t.connectedAt)})),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnectors({walletProxy:e,rootWallet:t,embeddedWallets:r,defaultChain:a,appId:n}){for(let i of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(r&&jt(r))r.proxyProvider.walletProxy=e;else{let{entropyId:r,entropyIdVerifier:o}=N(t),s=new ue({provider:new Wr({walletProxy:e,address:i.address,entropyId:r,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:a.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:a,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,r,a){let n=this.findWalletConnector("embedded_imported","privy");if(n&&jt(n))n.proxyProvider.walletProxy=e;else{let n=new ue({provider:new Wr({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(n)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=Nr(),this.emit("walletsUpdated")}removeImportedWalletConnector(){let e=this.findWalletConnector("embedded_imported","privy");if(e){let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1),this.saveConnectionHistory(),this.storedConnections=Nr(),this.emit("walletsUpdated")}}async createEthereumWalletConnector(e,t,r){let a=this.findWalletConnector(e,t);if(a&&jt(a))return a instanceof be&&a.resetConnection(t),a;let n=(()=>"injected"!==e?"coinbase_wallet"===e?new de(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"phantom"===e?new Kt(this.defaultChain):new be(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):"metamask"===t&&r?.eip6963InjectedProvider?new Ht(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Bt(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Bt(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Bt(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Vt(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return n&&this.addWalletConnector(n),n||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}saveConnectionHistory(){let e=this.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt})));ae.put(G,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&ve(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=r(e),this.emit("walletsUpdated")}constructor(e,t,r,a,n,i,o,s,l,c,d,u){super(),this.addSolanaWalletConnector=async e=>{this.findSolanaWalletConnector("solana_adapter",e.walletClientType)||this.addWalletConnector(e)},this.getEthereumProvider=()=>{let e=this.wallets[0],t=this.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new Ce},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=a,this.defaultChain=n,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=l,this.privyAppName=c,this.privyAppLogo=d,this.walletChainType=u||"ethereum-only",this.storedConnections=Nr()}}const Nr=()=>{let e=ae.get(G);return e&&Array.isArray(e)&&e.map((e=>(e=>e&&"string"==typeof e.address&&"string"==typeof e.connectorType&&"string"==typeof e.walletClientType&&"number"==typeof e.connectedAt)(e))).every(Boolean)?e:[]};let br;var Ur=0,Or="__private_"+Ur+++"__getOrGenerateClientAnalyticsId";class Sr{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:a,store:n,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new kr(this.appId,e,t,r,a,n,i,o,s,l,void 0,c))}generateApi(){let e=new zt({appId:this.appId,appClientId:this.appClientId,client:this,defaults:{baseURL:this.apiUrl,timeout:this.timeout}});return this.session.api=e,e}updateApiUrl(e){this.apiUrl=e||this.fallbackApiUrl,this.api=this.generateApi(),e&&(this.useServerCookies=!0)}authenticate(){if(!this.authFlow)throw new xe("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new xe("No auth flow in progress.");let{oAuthTokens:e}=await this.session.link(this.authFlow);return{user:await this.getAuthenticatedUser(),oAuthTokens:e}}storeProviderAccessToken(e,t){this.session.storeProviderAccessToken(e,t)}getProviderAccessToken(e){return this.session.getProviderAccessToken(e)}async logout(){await this.session.destroy(),this.authFlow=void 0}clearProviderAcccessTokens(e){e.linkedAccounts.filter((e=>"cross_app"===e.type)).forEach((e=>{this.storeProviderAccessToken(e.providerApp.id,null)}))}startAuthFlow(e){return e.api=this.api,this.authFlow=e,this.authFlow}async initMfaSmsVerification(){try{await this.api.post(Yt,{action:"verify"})}catch(e){throw je(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(Xt,{});return $t(e.options)}catch(e){throw je(e)}}async getCrossAppProviderDetails(e){try{return this._cachedProviderAppDetails[e]||(this._cachedProviderAppDetails[e]=await this.api.get(`/api/v1/apps/${e}/cross-app/details`)),this._cachedProviderAppDetails[e]}catch(e){console.error("Error fetching cross app provider details",e)}}async acceptTerms(){try{let e=await this.api.post(Qt,{});return b(e)}catch(e){throw Be(e)}}async unlinkEmail(e){try{let t=await this.api.post(Jt,{address:e});return await this.getAuthenticatedUser()??b(t)}catch(e){throw Be(e)}}async unlinkPhone(e){try{let t=await this.api.post(Zt,{phoneNumber:e});return await this.getAuthenticatedUser()??b(t)}catch(e){throw Be(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(er,{address:e});return await this.getAuthenticatedUser()??b(t)}catch(e){throw Be(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(tr,{address:e});return await this.getAuthenticatedUser()??b(t)}catch(e){throw Be(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(rr,{provider:e,subject:t});return await this.getAuthenticatedUser()??b(r)}catch(e){throw Be(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(ar,{fid:e});return await this.getAuthenticatedUser()??b(t)}catch(e){throw Be(e)}}async unlinkTelegram(e){try{let t=await this.api.post(nr,{telegram_user_id:e});return await this.getAuthenticatedUser()??b(t)}catch(e){throw Be(e)}}async unlinkPasskey(e){try{let t=await this.api.post(ir,{credential_id:e});return await this.getAuthenticatedUser()??b(t)}catch(e){throw Be(e)}}async revokeDelegatedWallet(){try{await this.api.post(or,{})}catch(e){throw Be(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:a}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(sr,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:a?.keepAlive??!1})}catch(e){}}async signMoonpayOnRampUrl(e){try{return this.api.post(lr,e)}catch(e){throw Be(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(cr,e)}catch(e){throw Be(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${dr}?partnerUserId=${e}`)}catch(e){throw Be(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()||this.session.hasRecoveryCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(Cr.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Cr.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?k.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null):!t?.disableAutoRefresh&&this.session.hasRefreshCredentials(e)?(await this.session.refresh(),this.session.getToken(e)):null:null}async getSmartWalletsConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:qt(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw Be(e)}}async getServerConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:e}),a=r.telegram_auth_config?{botId:r.telegram_auth_config.bot_id,botName:r.telegram_auth_config.bot_name,linkEnabled:r.telegram_auth_config.link_enabled,seamlessAuthEnabled:r.telegram_auth_config.seamless_auth_enabled}:void 0,n=r.funding_config?{methods:r.funding_config.methods,options:r.funding_config.options,defaultRecommendedAmount:r.funding_config.default_recommended_amount,defaultRecommendedCurrency:r.funding_config.default_recommended_currency,promptFundingOnWalletCreation:r.funding_config.prompt_funding_on_wallet_creation,crossChainBridgingEnabled:r.funding_config.cross_chain_bridging_enabled}:void 0;return{id:r.id,name:r.name,verificationKey:r.verification_key,logoUrl:r.logo_url||void 0,accentColor:r.accent_color||void 0,showWalletLoginFirst:r.show_wallet_login_first,allowlistConfig:{errorTitle:r.allowlist_config.error_title,errorDetail:r.allowlist_config.error_detail,errorCtaText:r.allowlist_config.cta_text,errorCtaLink:r.allowlist_config.cta_link},walletAuth:r.wallet_auth,solanaWalletAuth:r.solana_wallet_auth,emailAuth:r.email_auth,smsAuth:r.sms_auth,googleOAuth:r.google_oauth,twitterOAuth:r.twitter_oauth,discordOAuth:r.discord_oauth,githubOAuth:r.github_oauth,spotifyOAuth:r.spotify_oauth,instagramOAuth:r.instagram_oauth,tiktokOAuth:r.tiktok_oauth,linkedinOAuth:r.linkedin_oauth,appleOAuth:r.apple_oauth,farcasterAuth:r.farcaster_auth,passkeyAuth:r.passkey_auth,passkeysForSignupEnabled:r.passkeys_for_signup_enabled,telegramAuth:r.telegram_auth,disablePlusEmails:r.disable_plus_emails,termsAndConditionsUrl:r.terms_and_conditions_url,embeddedWalletConfig:{createOnLogin:r.embedded_wallet_config?.create_on_login,userOwnedRecoveryOptions:r.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:r.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:r.privacy_policy_url,requireUsersAcceptTerms:r.require_users_accept_terms,customApiUrl:r.custom_api_url,walletConnectCloudProjectId:r.wallet_connect_cloud_project_id,fiatOnRampEnabled:r.fiat_on_ramp_enabled,captchaEnabled:r.captcha_enabled,captchaSiteKey:r.captcha_site_key,createdAt:new Date(1e3*r.created_at),updatedAt:new Date(1e3*r.updated_at),mfaMethods:r.mfa_methods,enforceWalletUis:r.enforce_wallet_uis,legacyWalletUiConfig:r.legacy_wallet_ui_config,telegramAuthConfiguration:a,fundingConfig:n}}catch(e){throw Be(e)}}async getUsdTokenPrice(e){try{return(await this.api.get(`/api/v1/token_price?chainId=${e.id}&tokenSymbol=${e.nativeCurrency.symbol}`)).usd}catch(t){return void console.error(`Unable to fetch token price for chain with id ${e.id}`)}}async getUsdPriceForSol(){try{return(await this.api.get("/api/v1/token_price?chainId=0&tokenSymbol=SOL")).usd}catch(e){return void console.error("Unable to fetch token price for SOL")}}async getSplTokenMetadata({mintAddress:e,cluster:t}){try{return await this.api.get(`/api/v1/spl_token_info?mint_address=${e}&cluster=${t}`)}catch(r){return void console.error(`Unable to fetch token metadata for ${t}:${e}`)}}async requestFarcasterSignerStatus(e){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:e})}catch(e){throw console.error("Unable to fetch Farcaster signer status"),e}}async forkSession(){return await this.session.forkSession()}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(ur,{address:e,token:t})).nonce}catch(e){throw Be(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i}){return await this.api.post(hr,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){return await this.api.post(pr,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})}async linkSmartWallet({message:e,signature:t,smartWalletType:r}){try{let a=await this.api.post(wr,{message:e,signature:t,smart_wallet_type:r});return b(a)}catch(e){throw Be(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n});return b(i)}catch(e){throw Be(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(mr,{address:e,token:t})).nonce}catch(e){throw Be(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a,mode:n}){return await this.api.post(yr,{message:e,signature:t,walletClientType:r,connectorType:a,mode:n})}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(r){case"email":l=Tr,c={nonce:e,email:t};break;case"sms":l=Ar,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=_r,!a)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...a};break;case"farcaster":l=Er,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=gr,c={nonce:e,telegram_auth_result:n,telegram_web_app_data:i};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=fr,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??b(d)}catch(e){throw Be(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a}){return await this.api.post(vr,{message:e,signature:t,walletClientType:r,connectorType:a})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:a}){try{let n=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a});return b(n)}catch(e){throw Be(e)}}constructor({apiUrl:e=z,appId:t,appClientId:r,timeout:a=q}){Object.defineProperty(this,Or,{value:Rr}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==z&&e.startsWith("https://privy."),this.timeout=a,this.appId=t,this.appClientId=r,this.clientAnalyticsId=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}(this,Or)[Or](),br||(br=new Ir),this.session=br,this.api=this.generateApi(),this.session.client=this}}function Rr(){if("undefined"==typeof window)return null;try{let e=ae.get($);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=W();try{return ae.put($,e),e}catch(t){return e}}class Pr{async handleSignMessage(e){if(!e.params||"string"!=typeof e.params.message)throw Error("Message must be provided as a string for Solana signMessage RPC");return await Yr({message:e.params.message,address:this.address})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Hr())throw Error("User must be authenticated to use embedded Solana wallet");if(!await $r())throw new xe("Unable to connect to Solana embedded wallet");if("signMessage"===e.method)return await this.handleSignMessage(e);throw Error("Embedded Solana provider does not yet support this RPC method.")}constructor(e,t){this.walletProxy=e,this.address=t}}let Dr,Mr,Lr,Fr,xr,jr,Br;function Vr(){return Dr?Dr.getCustomerAccessToken():Promise.resolve(ae.get(Y)||null)}async function Hr(){return Dr?Dr.getAccessToken():Promise.resolve(ae.get(X)||ae.get(Y)||null)}const Kr=(e,t,r)=>Mr(e,t,r),Gr=(e,t,r)=>Lr(e,t,r),zr=(e,t,r,a)=>Fr(e,t,r,a),qr=()=>xr(),$r=()=>jr(),Yr=({message:e,address:t})=>Br({message:e,address:t});const Xr=({config:t,...r})=>{var a;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new xe("Embedded wallet is only available over HTTPS");if("string"!=typeof(a=r.appId)||25!==a.length)throw new xe("Cannot initialize the Privy provider with an invalid Privy app ID");Dr||(Dr=new Sr({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let n=Object.assign({},t);return void 0!==r.createPrivyWalletOnLogin&&void 0===n.embeddedWallets?.createOnLogin&&(n.embeddedWallets||(n.embeddedWallets={}),n.embeddedWallets.createOnLogin=r.createPrivyWalletOnLogin?"users-without-wallets":"off"),void 0!==r.createPrivyWalletOnLogin&&t?.embeddedWallets?.createOnLogin&&console.warn("Both `createPrivyWalletOnLogin` and `config.embeddedWallets.createOnLogin` are set. `createPrivyWalletOnLogin` is deprecated and should be removed."),/*#__PURE__*/e(ye,{client:Dr,clientConfig:n,legacyCreateEmbeddedWalletFlag:r.createPrivyWalletOnLogin,children:/*#__PURE__*/e(gt,{children:/*#__PURE__*/e(Qr,{...r,client:Dr})})})};let Qr=W=>{let k=W.client,b=Et(),[H,K]=i(!1),[G,q]=i(!1),[Y,X]=i(!1),[le,de]=i(null),[ue,he]=i([]),[ye,ke]=i([]),[je,Be]=i([]),gt=o(ue),[Ft,xt]=i(!1),[jt,Bt]=i(null),[Vt,Ht]=i(!1),[Kt,Gt]=i({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:It}),[zt,qt]=i({status:"initial"}),[$t,Yt]=i({status:"initial"}),[Xt,Qt]=i({status:"initial"}),[Jt,Zt]=i({status:"initial"}),[er,tr]=i({status:"initial"}),[rr,ar]=i(null),nr=fe(),ir=ge(),[or,sr]=i(!0),[lr,cr]=i({}),[dr,ur]=i(null),[hr,pr]=i(null),[wr,mr]=i(!1),[yr,fr]=i(!1),[gr,Er]=i(nr.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),_r=o(null),Ar=o(null),Tr=o(kt),[vr,Cr]=i(!1);k.onStoreCustomerAccessToken=e=>{e&&Nt(Tr,"accessToken","onAccessTokenGranted",e)},k.onDeleteCustomerAccessToken=()=>{de(null),X(!1),Nt(Tr,"accessToken","onAccessTokenRemoved")};let Ir=o(null),Wr=o(null),kr=o(!1),Nr=({showWalletUIs:e,typedData:t})=>kr.current?kr.current:void 0!==e?!e:void 0!==nr.embeddedWallets.showWalletUIs?!nr.embeddedWallets.showWalletUIs:t?nr.embeddedWallets.noPromptOnSignature||(nr.legacyWalletUiConfig??!1):!!nr.embeddedWallets.noPromptOnSignature,br=e=>{Bt(e),setTimeout((()=>{K(!0)}),15),k.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},Ur=e=>{"off"!==nr.embeddedWallets.createOnLogin&&sr(!0),br(e)};s((()=>{let e=[...U(le),O(le)].filter((e=>!!e));rr&&Be(e.map((e=>({type:"solana",imported:e.imported,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",walletIndex:e.walletIndex??void 0,meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund(){throw new xe("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new xe("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new Pr(rr,e.address),async signMessage(t){let r=await Hr();if(!r||!rr)throw new xe("Must have valid access token and Privy wallet to send transaction",Ve.MUST_BE_AUTHENTICATED);let a=e.imported?O(le):S(le);if(!a)throw new xe("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=N(a);if(!await ha.recoverPrimaryWallet().catch((()=>!1)))throw new xe("Wallet couldn't be connected",Ve.UNKNOWN_CONNECT_WALLET_ERROR);if(!le)throw new xe("Attempting to sign a transaction with no user initialized");let{response:o}=await rr.rpc({accessToken:r,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:this.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(o.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:a}=await ia({transaction:e,connection:t,transactionOptions:r,wallet:this});return a},async signTransaction(t){let r=await Hr();if(!r||!rr)throw new xe("Must have valid access token and Privy wallet to send transaction",Ve.MUST_BE_AUTHENTICATED);if(!await ha.recoverPrimaryWallet().catch((()=>!1)))throw new xe("Wallet couldn't be connected",Ve.UNKNOWN_CONNECT_WALLET_ERROR);let a=e.imported?e:S(le);if(!a)throw new xe("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=N(a);return await ze({tx:t,accessToken:r,walletProxy:rr,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:this.address,transactingWalletIndex:this.walletIndex??0}),t},loginOrLink:async()=>{throw new xe("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[rr,le]),s((()=>{if(!le)return void k.connectors?.removeEmbeddedWalletConnectors();let e=R(le),t=P(le),r=D(le);e&&t.length||k.connectors?.removeEmbeddedWalletConnectors(),r||k.connectors?.removeImportedWalletConnector(),k.connectors?rr?(e&&k.connectors.addEmbeddedWalletConnectors({walletProxy:rr,rootWallet:e,embeddedWallets:t,defaultChain:nr.defaultChain,appId:W.appId}),r&&k.connectors.addImportedWalletConnector(rr,r.address,nr.defaultChain,W.appId)):console.debug("Failed to add embedded wallet connector: Wallet proxy not initialized"):console.debug("Failed to add embedded wallet connector: Client connectors not initialized")}),[rr,le]),s((()=>{rr&&hr?.(rr)}),[rr]);let Or=o();s((()=>{(async()=>{if(!nr.customAuth?.enabled)return void Er({status:"not-enabled"});sr(!0);let{getCustomAccessToken:e,isLoading:t}=nr.customAuth;if(G&&!t&&"loading"!==gr.status){Er({status:"loading"});try{let t=await e();if(t===Or.current)return void Er({status:"done"});if(!t&&Y)return Or.current=t,await ua.logout(),Er({status:"done"}),void Nt(Tr,"customAuth","onUnauthenticated");if(!t)return Or.current=t,void Er({status:"done"});k.startAuthFlow(new p(t));let{user:r,isNewUser:a}=await k.authenticate();if(!r)return await ua.logout(),Er({status:"error",error:new xe("Failed to sync with custom auth provider")}),void Nt(Tr,"customAuth","onUnauthenticated");void 0!==a&&Nt(Tr,"login","onComplete",r,a,!1,"custom",null),Or.current=t,Nt(Tr,"customAuth","onAuthenticated",{user:r}),Er({status:"done"}),de(r||null),xt(a||!1),X(!0),fr(!0)}catch(e){if(console.warn(e),await ua.logout(),Nt(Tr,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void Er({status:"initial"});Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),Er({status:"error",error:e})}}})()}),["initial"===gr.status,nr.customAuth?.enabled,nr.customAuth?.getCustomAccessToken,nr.customAuth?.isLoading,G,Y]),s((()=>{yr&&rr&&le&&M(le,nr.embeddedWallets.createOnLogin)&&(fr(!1),Zr(le,te).catch(console.error))}),[yr&&rr&&le]),s((()=>{if(nr.externalWallets.solana.connectors)return nr.externalWallets.solana.connectors.onMount(),()=>nr.externalWallets.solana.connectors?.onUnmount()}),[nr.externalWallets.solana.connectors]),s((()=>{!G&&ir&&async function(){let e,t=Sr(),r=Rr();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;ae.put(re,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let a=n();k.initializeConnectorManager({walletConnectCloudProjectId:nr.walletConnectCloudProjectId,rpcConfig:nr.rpcConfig,chains:nr.chains,defaultChain:nr.defaultChain,store:a,walletList:nr.appearance.walletList,shouldEnforceDefaultChainOnConnect:nr.shouldEnforceDefaultChainOnConnect,externalWalletConfig:nr.externalWallets,appName:nr.name??"Privy",walletChainType:nr.appearance.walletChainType}),k.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=k.connectors.walletConnectors.length,r=k.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?Cr(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),Cr(!0)}),1500)})),k.connectors?.initialize().then((()=>{qr()}));let i=await k.getAuthenticatedUser(),o=!!i;nr.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await k.logout(),ha.setReadyToTrue(!0),Nt(Tr,"logout","onSuccess")):(nr.customAuth?.enabled||(X(!!i),i&&Nt(Tr,"login","onComplete",i,!1,!0,null,null),de(i)),t?Wr.current=o?"link":"login":r&&!o?(Wr.current="login",cr({telegramAuthModalData:{seamlessAuth:!0}}),Ur(Tt.TELEGRAM_AUTH_SCREEN)):ha.setReadyToTrue(!!i))}()}),[k,dr,G,ir]),s((()=>{if(G){if(!le||!le.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void mr(!0);mr(!!ue.find((e=>"privy"===e.walletClientType)))}}),[G,le,ue]);let Sr=()=>{let e=Mt();return e.inProgress&&e.popupFlow?window.opener.location.origin!==window.location.origin?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Origins between parent and child windows do not match."}):"error"===e.authorizationCode?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Something went wrong. Try again."}):void window.opener.postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}):(e.inProgress&&Xe(e.provider)&&!e.popupFlow&&(new BroadcastChannel(Qe).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(k.startAuthFlow(new Lt(e)),Ur(Tt.AWAITING_OAUTH_SCREEN),!0))},Rr=()=>{let e=I();if(!e||!nr.loginMethods.telegram||!nr.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new v;return k.startAuthFlow(t),"login-url"===e.flowType&&(t.meta.telegramWebAppData=void 0,t.meta.telegramAuthResult=e.authData),"web-app"===e.flowType&&(t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=e.authData),!0},Vr=async(e,t,r,a)=>{Kr(await(k.connectors?.createEthereumWalletConnector(e,t))||null,t,r,a)};async function Kr(e,t,r,a){if(!e)return Gt({status:"disconnected",connectedWallet:null,connectError:new Ke("Unable to connect to wallet."),connector:null,connectRetry:It}),a?.(null,r);Gt({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:It}),e instanceof be&&t&&await e.resetConnection(t),Gt({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Kr(e,t,r,a)});try{let t=await e.connect({showPrompt:!0});if((!t||ve(t))&&nr.shouldEnforceDefaultChainOnConnect&&!nr.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){Gt((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:It})));try{await(t?.switchChain(nr.defaultChain.id)),t&&(t.chainId=ce(se(nr.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${nr.defaultChain.id}`)}}return Gt((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:It}))),t&&Nt(Tr,"connectWallet","onSuccess",(e.chainType,t)),a?.(t,r)}catch(e){return e instanceof Ge?(console.warn(e.cause?e.cause:e.message),Nt(Tr,"connectWallet","onError",e.privyErrorCode||Ve.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),Nt(Tr,"connectWallet","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR)),Gt((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),a?.(null,r)}}let Gr=async(e,t,r)=>{if(null===e||!ve(e))return;let a=new E(e,k,t,r);k.startAuthFlow(a)},zr=async(e,t)=>{if(null===e||!Ne(e))return;let r=new _(e,k,t);k.startAuthFlow(r)},qr=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client");if(!t||!r)return;if("phantom"!==r||Te()||Ur(Tt.LOGIN_FAILED_SCREEN),!k.connectors)throw new xe("Connector not initialized");br(Tt.AWAITING_CONNECTION);let a=new URL(window.location.href);a.searchParams.delete("privy_connector"),a.searchParams.delete("privy_wallet_client"),window.history.pushState({},"",a),Vr(t,r,void 0,Gr)};s((()=>{G&&Y&&null===le&&k.getAuthenticatedUser().then(de)}),[G,Y,le,k]);let $r=e=>{if(!Y)throw Nt(Tr,"linkAccount","onError",Ve.MUST_BE_AUTHENTICATED,{linkMethod:e}),new xe("User must be authenticated before linking an account.")},Yr=()=>{$r("siwe"),Ir.current="siwe",Wr.current="link",br(Tt.LINK_WALLET_SCREEN)},Xr=e=>{if(!Y||!le)return!1;if("privy"===e.walletClientType)return!0;for(let t of le.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Qr=async e=>{let t;if(!k.connectors)throw new xe("Connector not initialized");t="ethereum"===e.type?k.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:k.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,Gt((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:It}))),nr.captchaEnabled&&!Y?(cr({captchaModalData:{callback:t=>ve(e)?Gr(e,t):zr(e,t),userIntentRequired:!1,onSuccessNavigateTo:Tt.AWAITING_CONNECTION,onErrorNavigateTo:Tt.ERROR_SCREEN}}),Ur(Tt.CAPTCHA_SCREEN)):(ve(e)?await Gr(e):await zr(e),Ur(Tt.AWAITING_CONNECTION))},Jr=()=>{he((e=>{let t=k.connectors?.wallets.filter(ve).map((e=>({...e,linked:Xr(e),loginOrLink:async()=>{if(!await e.isConnected())throw new xe("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new xe("Cannot link or login with embedded wallet");Qr(e)},fund:async t=>{await ha.fundWallet(e.address,t)},unlink:async()=>{if(!Y)throw new xe("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new xe("Cannot unlink an embedded wallet");de(await k.unlinkEthereumWallet(e.address))}})))||[];return Ee(e,t)?e:t})),ke((e=>{let t=(k.connectors?.wallets??[]).concat(je).filter(Ne).map((e=>({...e,linked:Xr(e),loginOrLink:async()=>{if(!await e.isConnected())throw new xe("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new xe("Cannot link or login with embedded wallet");Qr(e)},fund:async()=>{throw new xe("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!Y)throw new xe("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new xe("Cannot unlink an embedded wallet");de(await k.unlinkSolanaWallet(e.address))}})));return Ee(e,t)?e:t}))};s((()=>{Jr()}),[le?.linkedAccounts,Y,G,je]),s((()=>{if(G){if(!k.connectors)throw new xe("Connector not initialized");Jr(),k.connectors.on("walletsUpdated",Jr)}}),[G]),s((()=>{[...nr.loginMethodsAndOrder?.primary??[],...nr.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>k.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!k]),s((()=>{let e;if(!ue[0])return;let t=ue[0],r=gt.current.find((e=>e.address===t.address));if(e="privy"===t.walletClientType?le?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"===e.walletClientType)):le?.linkedAccounts.find((e=>"wallet"===e.type&&e.address===t.address&&"privy"!==e.walletClientType)),!r&&e){let t=Object.assign({},le);t.wallet=e&&{address:e.address,chainType:e.chainType,chainId:e.chainId,walletClient:e.walletClient,walletClientType:e.walletClientType,connectorType:e.connectorType,imported:e.imported,delegated:e.delegated,walletIndex:e.walletIndex},de(t)}gt.current=ue}),[ue]);let Zr=async(e,t,r)=>{let a=R(e),n=L(e);if(r&&"walletIndex"in r)return ta(e,t,r.walletIndex,a,n);let i=r&&"createAdditional"in r&&r.createAdditional;if(a&&!i)throw Nt(Tr,"createWallet","onError",Ve.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[o,s]=await Promise.all([ha.initializeWalletProxy(t),Hr()]);if(!o&&nr.customAuth?.enabled)throw Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||nr.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return ea();if(!a)return await o.create({accessToken:s,solanaAddress:n?.address}),aa(0,"ethereum");{let t=(F(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:a}=N(S(e));return await ha.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:r,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:t}),aa(t,"ethereum")}},ea=async()=>new Promise(((e,t)=>{sr(!0),cr({createWallet:{onSuccess:t=>{Nt(Tr,"createWallet","onSuccess",t),e(t)},onFailure:e=>{Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),br(Tt.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),ta=async(e,t,r,a,n)=>{if(r<0)throw Nt(Tr,"createWallet","onError",Ve.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[i,o]=await Promise.all([ha.initializeWalletProxy(t),Hr()]);if(!i&&nr.customAuth?.enabled)throw Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!i||!o||nr.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return ea();throw Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==r){if(a)return a;await i.create({accessToken:o,solanaAddress:n?.address})}else{if(!a)throw Nt(Tr,"createWallet","onError",Ve.EMBEDDED_WALLET_CREATE_ERROR),Error("A user must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let t=P(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:n,entropyIdVerifier:s}=N(S(e));await ha.recoverPrimaryWallet(),await i.addWallet({accessToken:o,entropyId:n,entropyIdVerifier:s,chainType:"ethereum",hdWalletIndex:r})}return aa(r,"ethereum")},ra=async({user:e,wp:t,accessToken:r,walletIndex:a,ethereumWallet:n})=>{let i=U(e).find((e=>e.walletIndex===a));if(i)return i;if(0===a)await t.createSolana({accessToken:r,ethereumAddress:n?.address});else{let n=S(e);if(!n)throw Nt(Tr,"createWallet","onError",Ve.EMBEDDED_WALLET_CREATE_ERROR),Error("User must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let{entropyId:i,entropyIdVerifier:o}=N(n);await ha.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:i,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:a})}return aa(a,"solana")},aa=async(e,t)=>{let r=await ha.refreshUser(),a=("ethereum"===t?P(r):U(r)).find((t=>t.walletIndex===e));if(!a)throw Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return Nt(Tr,"createWallet","onSuccess",a),a},na=(e,t,a,n)=>new Promise((async(i,o)=>{let{requesterAppId:s}=t||{};if(!Y||!le)return Nt(Tr,"sendTransaction","onError",Ve.MUST_BE_AUTHENTICATED),void o(Error("User must be authenticated before signing with a Privy wallet"));let l=n??R(le)?.address;if(!l)throw new xe("User must have an embedded wallet to send a transaction.");let{signingWallet:c,rootWallet:p}=j(le,l);if(!p||!c)return Nt(Tr,"sendTransaction","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),void o(Error("Must have a Privy wallet before signing"));sr(!0);let w=pa.wallets.find((e=>"privy"===e.walletClientType&&r(e.address)===r(c.address))),m=await(w?.getEthereumProvider());if(!w||!m)throw new xe(`Cannot sendTransaction before embedded wallet ${c.address} is connected`);let y=e.chainId?Number(e.chainId):$e(w.chainId);(e=>{if(!nr.chains.map((e=>e.id)).includes(e))throw new Ke(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,Ve.UNSUPPORTED_CHAIN_ID)})(y);let f=Object.assign({},e,{chainId:y});if(Nr({showWalletUIs:t?.showWalletUIs}))(async()=>{let e=await Hr();if(!e||!rr)return Nt(Tr,"sendTransaction","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),void o(Error("Must have valid access token and Privy wallet to send transaction"));try{if(!await ha.recoverPrimaryWallet())return Nt(Tr,"sendTransaction","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),void o(Error("Unable to connect to wallet"));let r=ie(f.chainId,nr.chains,nr.rpcConfig,{appId:W.appId}),a=await d(c.address,f,r);if(Nr({showWalletUIs:t?.showWalletUIs})){let{totalGasEstimate:e}=await u(a,r),{hasSufficientFunds:t}=await Le(c.address,a,e,r);if(!t)throw new _e(new Ae("Wallet has insufficient funds for this transaction.",h.E32603_DEFAULT_INTERNAL_ERROR.eipCode))}let{entropyId:n,entropyIdVerifier:l}=N(p),w=await Fe({accessToken:e,entropyId:n,entropyIdVerifier:l,transactingWallet:c,walletProxy:rr,transactionRequest:a,provider:r,requesterAppId:s});Nt(Tr,"sendTransaction","onSuccess",w),i(w)}catch(e){Nt(Tr,"sendTransaction","onError",Ve.TRANSACTION_FAILURE),o(e)}})();else{let{entropyId:e,entropyIdVerifier:r}=N(p),n={entropyId:e,entropyIdVerifier:r,onCompleteNavigateTo:Tt.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{Nt(Tr,"sendTransaction","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}},l=ct(nr)?Dt({address:c.address,appConfig:nr,fundWalletConfig:a,methodScreen:Tt.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:f.chainId,comingFromSendTransactionScreen:!0}):void 0;cr({connectWallet:n,sendTransaction:{transactionRequest:f,transactingWallet:c,entropyId:e,entropyIdVerifier:r,onSuccess:e=>{Nt(Tr,"sendTransaction","onSuccess",e),i(e)},onFailure:e=>{Nt(Tr,"sendTransaction","onError",Ve.TRANSACTION_FAILURE),o(e)},uiOptions:t||{},fundWalletConfig:a,requesterAppId:s},funding:l}),br(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),ia=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:a,uiOptions:n,wallet:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=n||{};if(!Y||!le)return Nt(Tr,"sendSolanaTransaction","onError",Ve.MUST_BE_AUTHENTICATED),void s(new xe("User must be authenticated before signing with a Privy wallet",Ve.MUST_BE_AUTHENTICATED));let c=i?le.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):L(le);if(!c)return Nt(Tr,"sendSolanaTransaction","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),void s(new xe("Must have a Privy wallet before signing",Ve.EMBEDDED_WALLET_NOT_FOUND));sr(!0);let{rootWallet:d}=x(le,c.address);if(!await ha.recoverPrimaryWallet().catch((()=>!1))||!d)throw Nt(Tr,"sendSolanaTransaction","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),new xe(`Cannot sendSolanaTransaction before embedded wallet ${c.address} is connected`,Ve.EMBEDDED_WALLET_NOT_FOUND);if(Nr({showWalletUIs:n?.showWalletUIs}))(async()=>{let a=await Hr();if(!a||!rr)return Nt(Tr,"sendSolanaTransaction","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),void s(new xe("Must have valid access token and Privy wallet to send transaction",Ve.EMBEDDED_WALLET_NOT_FOUND));try{if(!await ha.recoverPrimaryWallet())return Nt(Tr,"sendSolanaTransaction","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),void s(new xe("Unable to connect to wallet",Ve.UNKNOWN_CONNECT_WALLET_ERROR));if(Nr({showWalletUIs:n?.showWalletUIs})&&!await wt(e,t))return Nt(Tr,"sendSolanaTransaction","onError",Ve.INSUFFICIENT_BALANCE),void s(new xe("Solana wallet has insufficient funds for this transaction.",Ve.INSUFFICIENT_BALANCE));let{entropyId:i,entropyIdVerifier:l}=V(le),{signature:d,receipt:u}=await qe({accessToken:a,tx:e,connection:t,walletProxy:rr,transactionOptions:r,entropyId:i,entropyIdVerifier:l,transactingWalletAddress:c.address,transactingWalletIndex:c.walletIndex??0}),h=mt(d,u);Nt(Tr,"sendSolanaTransaction","onSuccess",h),o(h)}catch(e){Nt(Tr,"sendSolanaTransaction","onError",Ve.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:i,entropyIdVerifier:u}=N(d),h={entropyId:i,entropyIdVerifier:u,onCompleteNavigateTo:Tt.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{Nt(Tr,"sendSolanaTransaction","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},p=ct(nr)?Pt({address:c.address,appConfig:nr,methodScreen:Tt.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:a,comingFromSendTransactionScreen:!0}):void 0;cr({connectWallet:h,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:c,onSuccess:e=>{Nt(Tr,"sendSolanaTransaction","onSuccess",e),o(e)},onFailure:e=>{Nt(Tr,"sendSolanaTransaction","onError",Ve.TRANSACTION_FAILURE),s(e)},uiOptions:n||{},requesterAppId:l},funding:p}),br(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function oa(){return new Promise((async(e,t)=>{let r=await Hr();if(!r||!rr)throw Error("Must have valid access token to enroll in MFA");try{await rr.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let sa=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],la=e=>{let t=le?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:a}=yt(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw Nt(Tr,"linkAccount","onError",Ve.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:a}),new xe(`User already has an account of type ${r} linked.`)};async function ca({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){Bt(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!Y||!le)throw Nt(Tr,r,"onError",Ve.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let a=S(le);if(!a||!rr)throw Nt(Tr,r,"onError",Ve.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await oa()}catch(e){throw Nt(Tr,r,"onError",Ve.MISSING_MFA_CREDENTIALS),e}return new Promise(((n,i)=>{sr(!0);let o={onSuccess:e=>{Nt(Tr,r,"onSuccess","user-passcode",e),n(e)},onFailure:e=>{Nt(Tr,r,"onError",Ve.USER_EXITED_SET_PASSWORD_FLOW),i(e)},callAuthOnSuccessOnClose:!1},s="user-passcode"===a.recoveryMethod,l=ot({walletAction:"update",availableRecoveryMethods:nr.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:d}=N(a);cr({setWalletPassword:o,recoverWallet:{entropyId:c,entropyIdVerifier:d,onFailure:i},createWallet:o,connectWallet:{onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,entropyIdVerifier:d,onFailure:e=>{Nt(Tr,r,"onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s}}),br(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function da({appId:e,action:t}){let r=await Hr();if("link"===t&&!r)throw Nt(Tr,"linkAccount","onError",Ve.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new xe("User must be authenticated before linking an account.");if("login"===t&&r)throw Nt(Tr,"login","onError",Ve.UNKNOWN_AUTH_ERROR),new xe("Attempted to log in, but user is already logged in. Use a `link` helper instead.");Ir.current=`privy:${e}`,Wr.current=t;let a=ut();return k.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,n)=>{let{name:i,logoUrl:o}=await et({api:k.api,providerAppId:e,requesterAppId:nr.id});cr({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:a,onSuccess:r,onError:n}}),Ur(Tt.CROSS_APP_AUTH_SCREEN)}))}let ua={ready:G,authenticated:Y,user:le,walletConnectors:k.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),cr({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress}}),br(Y?Tt.CONNECT_ONLY_AUTHENTICATED_SCREEN:Tt.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:Yr,startCrossAppAuthFlow:da,linkEmail:()=>{$r("email"),la("email"),Ir.current="email",Wr.current="link",br(Tt.LINK_EMAIL_SCREEN)},linkPhone:()=>{$r("sms"),la("phone"),Ir.current="sms",Wr.current="link",br(Tt.LINK_PHONE_SCREEN)},linkGoogle:async()=>{$r("google"),la("google_oauth"),Wr.current="link",await ha.initLoginWithOAuth("google")},linkTwitter:async()=>{$r("twitter"),la("twitter_oauth"),Wr.current="link",await ha.initLoginWithOAuth("twitter")},linkDiscord:async()=>{$r("discord"),la("discord_oauth"),Wr.current="link",await ha.initLoginWithOAuth("discord")},linkGithub:async()=>{$r("github"),la("github_oauth"),Wr.current="link",await ha.initLoginWithOAuth("github")},linkSpotify:async()=>{$r("spotify"),la("spotify_oauth"),Wr.current="link",await ha.initLoginWithOAuth("spotify")},linkInstagram:async()=>{$r("instagram"),la("instagram_oauth"),Wr.current="link",await ha.initLoginWithOAuth("instagram")},linkTiktok:async()=>{$r("tiktok"),la("tiktok_oauth"),Wr.current="link",await ha.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{$r("linkedin"),la("linkedin_oauth"),Wr.current="link",await ha.initLoginWithOAuth("linkedin")},linkApple:async()=>{$r("apple"),la("apple_oauth"),Wr.current="link",await ha.initLoginWithOAuth("apple")},linkPasskey:async()=>{$r("passkey"),la("passkey"),await ha.initLinkWithPasskey(),br(Tt.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if($r("telegram"),la("telegram"),Wr.current="link",Ir.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new v;k.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=C(e.launchParams.initDataRaw),cr({telegramAuthModalData:{seamlessAuth:!0}}),Ur(Tt.TELEGRAM_AUTH_SCREEN)}else Nt(Tr,"linkAccount","onError",Ve.INVALID_DATA,{linkMethod:"telegram"});else await ha.initLoginWithTelegram();br(Tt.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{$r("farcaster"),la("farcaster"),await ha.initLoginWithFarcaster(),Wr.current="link",Ir.current="farcaster",br(Tt.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if($r("email"),!le?.email)throw new xe("User does not have an email linked to their account.");Wr.current="update",Ir.current="email",br(Tt.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if($r("sms"),!le?.phone)throw new xe("User does not have a phone number linked to their account.");Wr.current="update",Ir.current="sms",br(Tt.UPDATE_PHONE_SCREEN)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!G){let e=await new Promise((e=>{ur((t=>e.bind(t)))}));if(ur(null),e)return void console.warn(t)}!le||le.isGuest?(Wr.current="login",cr({login:e}),Ur(Tt.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{G||(await new Promise((e=>{ur((()=>e))})),ur(null)),Y?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(Wr.current="login",Ur(Tt.CONNECT_OR_CREATE))},logout:async()=>{if(Wr.current=null,Ir.current=null,le&&k.clearProviderAcccessTokens(le),Bt(null),await k.logout(),le&&rr)try{await rr.clearMfa({userId:le.id})}catch(e){}de(null),X(!1),Nt(Tr,"logout","onSuccess"),K(!1),ae.del($),ae.del(Q(nr.id))},getAccessToken:()=>k.getCustomerAccessToken(),getEthereumProvider:()=>{if(!le||!le.wallet)return new Ce;let e=ue.find((e=>le.wallet&&e.address===le.wallet.address)),t=k.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new Ce},getEthersProvider:()=>{if(!le||!le.wallet)return new a(new Ie(new Ce));let e=ue.find((e=>le.wallet&&e.address===le.wallet.address)),t=k.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new a(new Ie(e&&t?t.proxyProvider:new Ce))},getWeb3jsProvider:()=>{if(!le||!le.wallet)return new We(new Ce);let e=ue.find((e=>le.wallet&&e.address===le.wallet.address)),t=k.connectors?.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return new We(e&&t?t.proxyProvider:new Ce)},unlinkWallet:async e=>{let t;return de(t=e.startsWith("0x")?await k.unlinkEthereumWallet(e):await k.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await k.unlinkEmail(e);return de(t),t},unlinkPhone:async e=>{let t=await k.unlinkPhone(e);return de(t),t},unlinkGoogle:async e=>{let t=await k.unlinkOAuth("google",e);return de(t),t},unlinkTwitter:async e=>{let t=await k.unlinkOAuth("twitter",e);return de(t),t},unlinkDiscord:async e=>{let t=await k.unlinkOAuth("discord",e);return de(t),t},unlinkGithub:async e=>{let t=await k.unlinkOAuth("github",e);return de(t),t},unlinkSpotify:async e=>{let t=await k.unlinkOAuth("spotify",e);return de(t),t},unlinkInstagram:async e=>{let t=await k.unlinkOAuth("instagram",e);return de(t),t},unlinkTiktok:async e=>{let t=await k.unlinkOAuth("tiktok",e);return de(t),t},unlinkLinkedIn:async e=>{let t=await k.unlinkOAuth("linkedin",e);return de(t),t},unlinkApple:async e=>{let t=await k.unlinkOAuth("apple",e);return de(t),t},unlinkFarcaster:async e=>{let t=await k.unlinkFarcaster(e);return de(t),t},unlinkTelegram:async e=>{let t=await k.unlinkTelegram(e);return de(t),t},unlinkPasskey:async e=>{let t=await k.unlinkPasskey(e);return de(t),t},unlinkCrossAppAccount:async({subject:e})=>{let t=le?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new xe("Invalid subject");k.storeProviderAccessToken(t.id,null);let r=await k.unlinkOAuth(`privy:${t.id}`,e);return de(r),r},setActiveWallet:async e=>{let t=ue.find((t=>r(t.address)===r(e))),a=le?.linkedAccounts.find((t=>"wallet"===t.type&&r(t.address)===r(e)));if(t&&await t.isConnected())if(t.linked){let e=Object.assign({},le);e.wallet=a&&{address:a.address,chainType:a.chainType,chainId:a.chainId,walletClient:a.walletClient,walletClientType:a.walletClientType,connectorType:a.connectorType,imported:a.imported,delegated:a.delegated,walletIndex:a.walletIndex},de(e)}else t.loginOrLink();else cr({externalConnectWallet:{suggestedAddress:e}}),Yr()},forkSession:()=>k.forkSession(),createWallet:async e=>{if(e&&"target"in e&&e&&(e=void 0),!Y||!le)throw Nt(Tr,"createWallet","onError",Ve.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return Zr(le,15e3,e)},setWalletRecovery:async e=>ca({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>ca({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t,r)=>new Promise((async(a,n)=>{let{requesterAppId:i}=t||{};if(!Y||!le)return Nt(Tr,"signMessage","onError",Ve.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let o=r??R(le)?.address;if(!o)throw new xe("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=j(le,o);if(!s||!l)return Nt(Tr,"signMessage","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return Nt(Tr,"signMessage","onError",Ve.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));sr(!0);let c=async()=>{if(!Y)throw Error("User must be authenticated before signing with a Privy wallet");let t=await Hr();if(!rr||!t||!await ha.recoverPrimaryWallet())throw Error("Unable to connect to wallet");k.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:s.address,requesterAppId:i}});let{entropyId:r,entropyIdVerifier:a}=N(l),{response:n}=await rr.rpc({accessToken:t,entropyId:r,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:i,request:{method:"personal_sign",params:[e,s.address]}}),o=n.data;return k.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:s.address,requesterAppId:i}}),o};if(Nr({showWalletUIs:t?.showWalletUIs}))try{let e=await c();Nt(Tr,"signMessage","onSuccess",e),a(e)}catch(e){Nt(Tr,"signMessage","onError",Ve.UNABLE_TO_SIGN),n(e??new _e("Unable to sign message"))}else{let{entropyId:r,entropyIdVerifier:i}=N(l);cr({signMessage:{method:"personal_sign",data:e,confirmAndSign:c,onSuccess:e=>{Nt(Tr,"signMessage","onSuccess",e),a(e)},onFailure:e=>{Nt(Tr,"signMessage","onError",Ve.UNABLE_TO_SIGN),n(e)},uiOptions:t||{}},connectWallet:{entropyId:r,entropyIdVerifier:i,onCompleteNavigateTo:Tt.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{Nt(Tr,"signMessage","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),br(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t,r)=>new Promise((async(a,n)=>{let{requesterAppId:i}=t||{};if(!Y||!le)return Nt(Tr,"signTypedData","onError",Ve.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let o=r??R(le)?.address;if(!o)throw new xe("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=j(le,o);if(!l||!s)return Nt(Tr,"signTypedData","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));sr(!0);let c=oe(e),d=async()=>{if(!Y)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Hr();if(!rr||!e||!await ha.recoverPrimaryWallet())throw Error("Unable to connect to wallet");k.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:s.address,requesterAppId:i}});let{entropyId:t,entropyIdVerifier:r}=N(l),{response:a}=await rr.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:i,request:{method:"eth_signTypedData_v4",params:[s.address,c]}}),n=a.data;return k.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:s.address,requesterAppId:i}}),n};if(Nr({showWalletUIs:t?.showWalletUIs,typedData:!0}))try{let e=await d();Nt(Tr,"signTypedData","onSuccess",e),a(e)}catch(e){Nt(Tr,"signTypedData","onError",Ve.UNABLE_TO_SIGN),n(e??new _e("Unable to sign message"))}else{let{entropyId:e,entropyIdVerifier:r}=N(l);cr({signMessage:{method:"eth_signTypedData_v4",data:c,confirmAndSign:d,onSuccess:e=>{Nt(Tr,"signTypedData","onSuccess",e),a(e)},onFailure:e=>{Nt(Tr,"signTypedData","onError",Ve.UNABLE_TO_SIGN),n(e)},uiOptions:t||{}},connectWallet:{entropyId:e,entropyIdVerifier:r,onCompleteNavigateTo:Tt.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{Nt(Tr,"signMessage","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),br(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t,r,a)=>{let n=await na(e,t,r,a);return Me(await n.wait())},sendSolanaTransaction:async(e,t,r,a,n,i)=>{let o=i?ye.find((({address:e})=>e===i)):ye.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw Nt(Tr,"sendSolanaTransaction","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),new xe("Embedded wallet not found",Ve.EMBEDDED_WALLET_NOT_FOUND);return await ia({transaction:e,connection:t,transactionOptions:a,uiOptions:r,fundWalletConfig:n,wallet:o})},exportWallet:e=>new Promise((async(t,r)=>{if(!Y||!le)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let a=e?.address??R(le)?.address;if(!a)return void r(Error("User does not have an HD Ethereum wallet. To export an imported wallet, pass the `address` of the wallet to `exportWallet`."));let{signingWallet:n,rootWallet:i}=j(le,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));sr(!0);let{entropyId:o,entropyIdVerifier:s}=N(i),l={entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:Tt.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0};cr(lr),await Hr()&&rr?rr?(cr({keyExport:{appId:W.appId,appClientId:W.clientId,origin:k.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r},connectWallet:l}),br(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:oa,async init(e){switch(e){case"sms":return void await k.initMfaSmsVerification();case"passkey":return await k.initMfaPasskeyVerification();case"totp":return;default:throw Error(`Unsupported MFA method: ${e}`)}},async submit(e,t){switch(e){case"totp":case"sms":if("string"!=typeof t)throw new xe("Invalid MFA code");_r.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{Ar.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new xe("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),a=ft(await r.startAuthentication(t));_r.current?.resolve({mfaMethod:e,mfaCode:a,relyingParty:window.origin}),await new Promise(((e,t)=>{Ar.current={resolve:e,reject:t}}));break;default:throw _r.current?.reject(new xe("Unsupported MFA method")),new xe(`Unsupported MFA method: ${e}`)}},cancel(){_r.current?.reject(new xe("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Hr();if(!t||!rr)throw Error("Must have valid access token to enroll in MFA");await rr.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return ha.closePrivyModal(),void t();nr.mfa.noPromptOnMfaRequired&&console.warn("[Privy Warning] Triggering the 'showMfaEnrollmentModal' function when 'noPromptOnMfaRequired' is set to true is unexpected. If this is intentional, ensure that you are building custom UIs for MFA verification."),cr({mfaEnrollmentFlow:{mfaMethods:nr.mfa.methods,onSuccess:t,onFailure:r}}),br(Tt.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await Hr();if(!e||!rr)throw Error("Must have valid access token to enroll in MFA");let t=await rr.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Hr();if(!t||!rr)throw Error("Must have valid access token to enroll in MFA");await rr.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),de(await k.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Hr();if(!t||!rr)throw Error("Must have valid access token to enroll in MFA");await rr.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),de(await k.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e}){let t=await Hr();if(!t||!rr)throw Error("Must have valid access token to enroll in MFA");await rr.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:e}),de(await k.getAuthenticatedUser())},async unenroll(e){let t=await Hr();if(!t||!rr)throw Error("Must have valid access token to remove MFA");"passkey"===e?await rr.submitEnrollMfa({method:"passkey",accessToken:t,credentialIds:[]}):await rr.unenrollMfa({method:e,accessToken:t}),de(await k.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Hr(),t=le?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!rr||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!le?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await ha.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await rr.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&de(await k.getAuthenticatedUser()||le||null),cr({farcasterSigner:r}),br(Tt.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await Hr(),r=le?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!rr||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!le?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await ha.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!le.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=le.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Hr(),r=le?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!rr||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!le?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await ha.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!le.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let a=await import("@simplewebauthn/browser"),n=await rr.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:a.bufferToBase64URLString(e)},fid:BigInt(le.farcaster.fid),relyingParty:window.origin});return new Uint8Array(a.base64URLStringToBuffer(n.signature))},createGuestAccount:async()=>{if(le&&!le.isGuest)throw Error("User cannot already be authenticated to create a guest account");return le?.isGuest?le:ha.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t}){let r=le?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return rt({user:le,client:k,address:t,requesterAppId:nr.id,request:{method:r?"privy_signSmartWalletMessage":"personal_sign",params:[e,t]},reconnect:da})},signTypedDataWithCrossAppWallet(e,{address:t}){let r=le?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),a=oe(e);return rt({user:le,client:k,address:t,requesterAppId:nr.id,request:{method:r?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,a]},reconnect:da})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=le?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return rt({user:le,client:k,address:t,requesterAppId:nr.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e]},reconnect:da})},isModalOpen:H,mfaMethods:nr.mfa.methods};Mr=ua.signMessage,Lr=ua.signTypedData,Fr=async(...e)=>{let t=await na(...e);return nr.embeddedWallets.waitForTransactionConfirmation&&await t.wait(),t};let ha={setAuthenticated:X,setUser:de,isNewUserThisSession:Ft,pendingTransaction:null,walletConnectionStatus:Kt,connectors:k.connectors?.walletConnectors??[],solanaWallets:ye,rpcConfig:nr.rpcConfig,chains:nr.chains,appId:W.appId,showFiatPrices:"native-token"!==nr.embeddedWallets.priceDisplay.primary,clientAnalyticsId:k.clientAnalyticsId,customAuthStatus:gr,noPromptOnSignature:kr,emailOtpState:$t,setEmailOtpState:Yt,smsOtpState:Xt,setSmsOtpState:Qt,oAuthState:er,setOAuthState:tr,siweState:Jt,setSiweState:Zt,isHeadlessOAuthLoading:Vt,nativeTokenSymbolForChainId:e=>nr.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(rr)return rr;let t=new Promise((e=>{pr((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),a=await Promise.race([t,r]);return pr(null),a},getAuthFlow:()=>k.authFlow,getAuthMeta:()=>k.authFlow?.meta,client:k,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=G&&Y&≤r&&Ir.current&&(t=sa(le)),"login"===Wr.current?e.shouldCallAuthOnSuccess&&r&&Ir.current?(Nt(Tr,"login","onComplete",le,Ft,!1,Ir.current,t??null),W.onSuccess?.(le,Ft)):Nt(Tr,"login","onError",Ve.USER_EXITED_AUTH_FLOW):"link"===Wr.current&&t?e.isSuccess&&r&&Ir.current?Nt(Tr,"linkAccount","onSuccess",le,Ir.current,t):Ir.current&&Nt(Tr,"linkAccount","onError",Ve.USER_EXITED_LINK_FLOW,{linkMethod:Ir.current}):"update"===Wr.current&&t&&(e.isSuccess&&r&&Ir.current?Nt(Tr,"update","onSuccess",le,Ir.current,t):Ir.current&&Nt(Tr,"update","onError",Ve.USER_EXITED_UPDATE_FLOW,{linkMethod:Ir.current}));let a=jt&&st.includes(jt),n=jt===Tt.ERROR_SCREEN&&lr.errorModalData&&st.includes(lr.errorModalData.previousScreen);if((a||n)&&lr.funding){let e,t=lt[jt]??null;if("solana"===lr.funding.chainType){let r=b(_t);if(!r)return void console.warn("Unable to load solana plugin, skipping balance");try{e=BigInt(await r.getBalance({address:lr.funding.address,cluster:lr.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}Nt(Tr,"fundSolanaWallet","onUserExited",{address:lr.funding.address,cluster:lr.funding.cluster,fundingMethod:t,balance:e})}else{let r=ie(lr.funding.chain.id,nr.chains,nr.rpcConfig,{appId:W.appId});try{e=(await r.getBalance(lr.funding.address)).toBigInt()}catch{console.error("Unable to pull wallet balance")}Nt(Tr,"fundWallet","onUserExited",{address:lr.funding.address,chain:lr.funding.chain,fundingMethod:t,balance:e})}}cr({...lr,externalConnectWallet:{suggestedAddress:void 0}}),Wr.current=null,Ir.current=null,xt(!1),K(!1),setTimeout((()=>{k.authFlow=void 0}),200),k.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:({message:e,address:t})=>new Promise((async(r,a)=>{if(!Y||!le)return Nt(Tr,"signMessage","onError",Ve.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let n=t??L(le)?.address;if(!n)throw new xe("User must have an embedded wallet to sign a message.");let{signingWallet:i,rootWallet:o}=x(le,n);if(!i||!o)return Nt(Tr,"signMessage","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return Nt(Tr,"signMessage","onError",Ve.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));sr(!0);let s=async()=>{if(!Y)throw Error("User must be authenticated before signing with a Privy wallet");let t=await k.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=ha.walletProxy??await ha.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await ha.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!o)throw Error("No root wallet for signing wallet found");let{entropyId:a,entropyIdVerifier:n}=N(o),{response:s}=await r.rpc({accessToken:t,entropyId:a,entropyIdVerifier:n,chainType:"solana",hdWalletIndex:i.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return s.data.signature};if(Nr({showWalletUIs:void 0}))try{let e=await s();r({signature:e})}catch(e){a(e)}else{let{entropyId:t,entropyIdVerifier:n}=N(o);cr({signMessage:{method:"solana_signMessage",data:e,confirmAndSign:s,onSuccess:e=>{r({signature:e})},onFailure:e=>{a(e)},uiOptions:{}},connectWallet:{entropyId:t,entropyIdVerifier:n,onCompleteNavigateTo:Tt.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{Nt(Tr,"signMessage","onError",Ve.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Ur(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),openPrivyModal:br,connectWallet:Kr,initLoginWithWallet:async(e,t,r)=>{ve(e)?(Ir.current="siwe",Gr(e,t,r)):(Ir.current="siws",zr(e,t))},loginWithWallet:async()=>{let e,t,r;if(!G)throw new He;if(k.authFlow instanceof E?e="siwe":k.authFlow instanceof _&&(e="siws"),!e)throw new xe("Must initialize SIWE/SIWS flow first.");if(null!==await k.getAccessToken())try{({user:t}=await k.link()),Ir.current=e}catch(t){throw Nt(Tr,"linkAccount","onError",t.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await k.authenticate()),Ir.current=e}catch(e){throw Nt(Tr,"login","onError",e.privyErrorCode||Ve.GENERIC_CONNECT_WALLET_ERROR),e}de(t||le||null),xt(r||!1),X(!0)},delegateWallet:async({address:e,chainType:t})=>new Promise((async(r,a)=>{let n=await Hr();if(!Y||!le||!n)throw new xe("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new xe("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let i=ha.walletProxy??await ha.initializeWalletProxy(15e3);if(!i)throw new xe("Wallet proxy not initialized.");if(Oe({address:e,chainType:t,user:le}))return r();let o=Se({address:e,user:le}),s=Re({address:e,user:le});await ha.recoverPrimaryWallet(),cr({delegatedActions:{consent:{address:e,onDelegate:async()=>{await i.createDelegatedAction({accessToken:n,rootWallet:s,delegatedWallets:[o]}),await ha.refreshUser()},onSuccess:async()=>{r()},onError:async e=>{a(e)}}}}),br(Tt.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),revokeDelegatedWallets:async()=>new Promise((async(e,t)=>{if(!Y||!le)throw new xe("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===Pe(le).length)throw new xe("User has no delegated wallets to revoke.");cr({delegatedActions:{revoke:{onRevoke:async()=>{await k.revokeDelegatedWallet(),await ha.refreshUser()},onSuccess:async()=>{e()},onError:async e=>{t(e)}}}}),br(Tt.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN)})),initLoginWithFarcaster:async(e,t)=>{let r=new y(e,t);k.startAuthFlow(r);try{Ir.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===Wr.current?Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR):"link"===Wr.current&&Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!G)throw new He;if(!(k.authFlow instanceof y))throw new xe("Must initialize Farcaster flow first.");if(null!==await k.getAccessToken())try{({user:e}=await k.link()),Ir.current="farcaster"}catch(e){throw Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await k.authenticate()),Ir.current="farcaster"}catch(e){throw Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}de(e||null),xt(t||!1),X(!0)},async loginWithGuestAccountFlow(){let e=new f(this.appId);k.startAuthFlow(e);try{Wr.current="login",Ir.current="guest";let{user:e,isNewUser:t}=await k.authenticate();if(t=t||!1,!e)throw new xe("Unable to authenticate guest account");if(M(e,nr.embeddedWallets.createOnLogin))try{await Zr(e,15e3),e=await ha.refreshUser()}catch(t){de(e),console.warn("Unable to create embedded wallet for guest account")}else de(e);return xt(t),X(!0),Nt(Tr,"login","onComplete",e,t,!1,"guest",null),e}catch(e){throw Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let a=`privy:${e}`;Ir.current=a;let{url:n,stateCode:i,codeVerifier:o}=await Je({api:k.api,appId:e});if(!n)throw k.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new xe("No authorization URL returned for cross-app auth.");try{let s=await tt({url:n,popup:t,provider:a}),l=s.stateCode,c=s.authorizationCode;if(l!==i)throw k.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:i??"",returnedStateCode:l??""}}),new xe("Unexpected auth flow. This may be a phishing attempt.",void 0,Ve.OAUTH_UNEXPECTED);let d=await Ze({appId:e,codeVerifier:o,stateCode:l,authorizationCode:c,action:r,client:k});d&&k.storeProviderAccessToken(e,d);let u=await ha.refreshUser();if(!u)throw new xe("Unable to update user");return k.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),u}catch(e){throw k.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(Ir.current=e,!ne())return void Ur(Tt.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&dt(window.navigator.userAgent))return void Ur(Tt.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:Ye},"*"),ae.del(J),ae.del(Z);let a=new Lt({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&a.addCaptchaToken(t),k.startAuthFlow(a);let n=await k.authFlow.getAuthorizationUrl();n&&n.url&&("twitter"===e&&c&&(n.url=n.url.replace("x.com","twitter.com")),window.location.assign(n.url))},async initLoginWithTelegram(e,t){if(!G)throw new He;Ir.current="telegram";let r=new v(e,t);k.startAuthFlow(r),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>nr.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:nr.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new xe("Telegram auth failed or was canceled by the client")))):t(new xe("Telegram was not initialized")):t(new xe("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(k.authFlow instanceof v))throw new xe("Must initialize Telegram flow before calling loginWithTelegram");if(k.authFlow.meta.captchaToken||=e,"login"===Wr.current)try{let e=await k.authenticate();t=e.user,r=e.isNewUser,Ir.current="telegram"}catch(e){throw Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}else{if("link"!==Wr.current)throw new xe("Unknown auth intent");try{t=(await k.link()).user,Ir.current="telegram"}catch(e){throw Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}de(t),xt(r||!1),X(!0)},async recoveryOAuthFlow(e,t,r){let a,n;function i(t){if(!t)throw k.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new xe("Recovery OAuth failed")}switch(e){case"google-drive":{let t,o,{url:s,codeVerifier:l,stateCode:c}=await at({api:Dr.api,provider:e});i(s);try{let a=await ht({url:s,popup:r,provider:e});if(t=a.stateCode,o=a.authorizationCode,t!==c)throw k.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:c??"",returnedStateCode:t??""}}),new xe("Unexpected auth flow. This may be a phishing attempt.",void 0,Ve.OAUTH_UNEXPECTED)}catch(t){throw k.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new xe("Recovery OAuth failed")}[a,n]=await Promise.all([Hr(),nt({api:Dr.api,provider:e,codeVerifier:l,stateCode:t,authorizationCode:o})]);break}case"icloud":{let{url:t}=await at({api:Dr.api,provider:e});i(t);let{ckWebAuthToken:o}=await ht({url:t,popup:r,provider:e});n=o,a=await Hr()}}if(!rr)throw new xe("Cannot connect to wallet proxy");if(!a)throw new xe("Unable to authorize user");switch(t){case"recover":{let t=lr.recoverWallet?.entropyId,r=lr.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new xe("Recovery OAuth failed");k.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await rr.recover({accessToken:a,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:n}),k.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{k.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await rr.create({accessToken:a,recoveryAccessToken:n,recoveryMethod:e});let t=R(await ha.refreshUser());if(!t)throw Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");k.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),Nt(Tr,"createWallet","onSuccess",t);break}case"set-recovery":{let t=S(le);if(!t)throw Nt(Tr,"setWalletRecovery","onError",Ve.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");k.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:i}=N(t);await rr.setRecovery({accessToken:a,entropyId:r,entropyIdVerifier:i,recoveryMethod:e,recoveryAccessToken:n});let o=S(await ha.refreshUser());if(!o)throw Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");k.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),Nt(Tr,"setWalletRecovery","onSuccess",e,o);break}default:throw new xe("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,a;if(!(k.authFlow instanceof Lt))throw new xe("Must initialize OAuth flow before calling loginWithOAuth");let n=ae.get(ee),i=k.authFlow.meta.stateCode;if(n!==i)throw k.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:n??"",returnedStateCode:i??""}}),new xe("Unexpected auth flow. This may be a phishing attempt.",void 0,Ve.OAUTH_UNEXPECTED);if(null!==await k.getAccessToken())try{let r=await k.link();t=r.user,a=r.oAuthTokens,Ir.current=e}catch(t){throw Nt(Tr,"linkAccount","onError",t.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let n=await k.authenticate();t=n.user,r=n.isNewUser,a=n.oAuthTokens,Ir.current=e}catch(t){throw"login"===Wr.current?Nt(Tr,"login","onError",t.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR):"link"===Wr.current&&Nt(Tr,"linkAccount","onError",t.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return de(t),xt(r||!1),X(!0),a&&t&&Nt(Tr,"oAuthAuthorization","onOAuthTokenGrant",a,{user:t}),a},passkeyAuthState:zt,setPasskeyAuthState:qt,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new g({captchaToken:e,setPasskeyAuthState:qt});k.startAuthFlow(r),Wr.current="login";try{Ir.current="passkey",qt({status:"generating-challenge"}),await r.initRegisterFlow(t),qt({status:"awaiting-passkey"})}catch(e){throw qt({status:"error",error:e}),Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!G)throw new He;if(!(k.authFlow instanceof g))throw new xe("Must initialize Passkey flow first.");if("passkey"!==Ir.current){let e=new xe("Must init login with Passkey flow first.");throw qt({status:"error",error:e}),e}let r=await Hr();try{Ir.current="passkey",qt({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await k.authenticate())}catch(e){throw qt({status:"error",error:e}),Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}de(e),xt(t||!1),X(!0),qt({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new g({captchaToken:e,setPasskeyAuthState:qt});k.startAuthFlow(r),Wr.current="login";try{Ir.current="passkey",qt({status:"generating-challenge"}),await r.initAuthenticationFlow(t),qt({status:"awaiting-passkey"})}catch(e){throw qt({status:"error",error:e}),Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(){let e,t;if(!G)throw new He;if(!(k.authFlow instanceof g))throw new xe("Must initialize Passkey flow first.");if("passkey"!==Ir.current){let e=new xe("Must init login with Passkey flow first.");throw qt({status:"error",error:e}),e}let r=await Hr();try{Ir.current="passkey",qt({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await k.authenticate())}catch(e){throw qt({status:"error",error:e}),Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}de(e),xt(t||!1),X(!0),qt({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLinkWithPasskey(e){let t=new g({captchaToken:e});k.startAuthFlow(t),Wr.current="link",Ir.current="passkey",qt({status:"generating-challenge"});try{await t.initLinkFlow(),qt({status:"awaiting-passkey"})}catch(e){throw Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),qt({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!G)throw new He;if(!(k.authFlow instanceof g))throw new xe("Must initialize Passkey flow first.");if("passkey"!==Ir.current)throw new xe("Must init login with Passkey flow first.");try{Ir.current="passkey",({user:e}=await k.link())}catch(e){throw Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return de(e||le||null),qt({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!ne())throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");if("google"===e&&dt(window.navigator.userAgent))throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let a=new Lt({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&a.addCaptchaToken(t),tr({status:"loading"});let n=await k.startAuthFlow(a).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,r,a;Ht(!0),tr({status:"loading"}),k.startAuthFlow(new Lt(e));let n=ae.get(ee),i=e.stateCode;if(n!==i)throw k.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:n??"",returnedStateCode:i??""}}),Ht(!1),new xe("Unexpected auth flow. This may be a phishing attempt.",void 0,Ve.OAUTH_UNEXPECTED);if(null!==await k.getAccessToken())try{({user:t,oAuthTokens:a}=await k.link()),Ir.current=e.provider;let r=sa(t);t&&r&&Nt(Tr,"linkAccount","onSuccess",t,Ir.current,r)}catch(t){throw Ht(!1),Nt(Tr,"linkAccount","onError",t.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:a}=await k.authenticate()),Ir.current=e.provider;let n=sa(t);t&&n&&void 0!==r&&Nt(Tr,"login","onComplete",t,r,!1,Ir.current,n)}catch(e){throw Ht(!1),tr({status:"error",error:e}),Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}return de(t),xt(r||!1),X(!0),Ht(!1),tr({status:"done"}),a&&t&&Nt(Tr,"oAuthAuthorization","onOAuthTokenGrant",a,{user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{let n=new m({email:e,captchaToken:t,disableSignup:r});k.startAuthFlow(n);try{Ir.current="email",Yt({status:"sending-code"}),await n.sendCodeEmail({withPrivyUi:a}),Yt({status:"awaiting-code-input"})}catch(e){throw Yt({status:"error",error:e}),"login"===Wr.current?Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR):"link"===Wr.current&&Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let a=new w(e,t,r);k.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){Nt(Tr,"update","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR,{linkMethod:Ir.current})}},initUpdatePhone:async(e,t,r)=>{let a=new A(e,t,r);k.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){Nt(Tr,"update","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR,{linkMethod:Ir.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{Qt({status:"sending-code"});let n=new T({phoneNumber:e,captchaToken:t,disableSignup:r});k.startAuthFlow(n);try{Ir.current="sms",await n.sendSmsCode({withPrivyUi:a}),Qt({status:"awaiting-code-input"})}catch(e){throw Qt({status:"error",error:e}),"login"===Wr.current?Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR):"link"===Wr.current&&Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(k.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(k.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function a(e){k.authFlow instanceof m?Yt(e):k.authFlow instanceof T&&Qt(e)}if(a({status:"submitting-code"}),!G){let e=new He;throw a({status:"error",error:e}),e}if(k.authFlow instanceof m)k.authFlow.meta.emailCode=e.trim();else{if(!(k.authFlow instanceof T)){let e=new xe("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}k.authFlow.meta.smsCode=e.trim()}let n=await Hr();if("link"===Wr.current)try{({user:t}=await k.link())}catch(e){throw a({status:"error",error:e}),Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:Ir.current}),e}else if("update"===Wr.current)try{({user:t}=await k.link())}catch(e){throw a({status:"error",error:e}),Nt(Tr,"update","onError",e.privyErrorCode||Ve.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:Ir.current}),e}else try{({user:t,isNewUser:r}=await k.authenticate())}catch(e){throw a({status:"error",error:e}),Nt(Tr,"login","onError",e.privyErrorCode||Ve.UNKNOWN_AUTH_ERROR),e}let i=t||le;de(i||null),xt(r||!1),X(!0),a({status:"done"});let o=null;return k.authFlow instanceof m?o=i?.linkedAccounts.find((({type:e})=>"email"===e))||null:k.authFlow instanceof T&&(o=i?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:i,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,linkedAccount:o}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{Wr.current="link",Ir.current="siwe",Zt({status:"generating-message"});let a=await k.generateSiweNonce({address:e,captchaToken:r});return Zt({status:"awaiting-signature"}),pt({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await k.generateSiweNonce({address:e});return pt({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let a;a=await k.linkSmartWallet({message:e,signature:t,smartWalletType:r}),de((a=await ha.refreshUser()??a)||le||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})=>{let i;$r("siwe");let o=null;try{Zt({status:"submitting-signature"}),i=await k.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}),i=await ha.refreshUser()??i,Zt({status:"done"}),(o=sa(i)||null)&&Nt(Tr,"linkAccount","onSuccess",i,"siwe",o)}catch(e){throw Nt(Tr,"linkAccount","onError",e.privyErrorCode||Ve.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),Wr.current=null,Ir.current=null,Zt({status:"error",error:e}),e}let s=i||le;return de(s||null),Wr.current=null,Ir.current=null,{user:s,linkedAccount:o}},refreshUser:async()=>{let e=await k.getAuthenticatedUser();return X(!!e),de(e),e},walletProxy:rr,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>k.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await k.acceptTerms();return de(e),e},getUsdTokenPrice:e=>k.getUsdTokenPrice(e),getUsdPriceForSol:()=>k.getUsdPriceForSol(),getSplTokenMetadata:e=>k.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let a=S(e?.user??le)||D(e?.user??le)||O(e?.user??le),n=await Hr();if(!n||!rr||!a)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));sr(!0);let{entropyId:i,entropyIdVerifier:o}=N(a);try{await rr.connect({accessToken:n,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){De(e)&&"privy"===a.recoveryMethod?(k.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}}),(await rr.recover({entropyId:i,entropyIdVerifier:o,accessToken:n})).entropyId||r(Error("Unable to recover wallet")),k.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)):De(e)&&"privy"!==a.recoveryMethod?(cr({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover"}}),br(it(a.recoveryMethod))):r(e)}})),createEmbeddedSolanaWallet:async e=>{if(e&&"target"in e&&(e=void 0),!Y||!le)throw Nt(Tr,"createWallet","onError",Ve.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let a=R(e),n=L(e),i=r&&"createAdditional"in r&&r.createAdditional,o=r&&"walletIndex"in r?r.walletIndex:void 0,s=(B(e)?.walletIndex??-1)+1;if(n&&!i&&"number"!=typeof o)throw Nt(Tr,"createWallet","onError",Ve.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof o&&o<0)throw Nt(Tr,"createWallet","onError",Ve.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${o}) is invalid.`);let[l,c]=await Promise.all([ha.initializeWalletProxy(t),Hr()]);if(!l||!c)throw Nt(Tr,"createWallet","onError",Ve.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await ra({user:e,wp:l,accessToken:c,walletIndex:o??s,ethereumWallet:a})})(le,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!Y||!le)return void r(Error("User must be authenticated before exporting their Privy wallet"));let a=e?.address??L(le)?.address;if(!a)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:n,rootWallet:i}=x(le,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));if(sr(!0),!await Hr()||!rr)return void r(Error("Must have valid access token to enroll in MFA"));if(!rr)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=N(i);cr({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:Tt.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0},keyExport:{appId:W.appId,appClientId:W.clientId,origin:k.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r}}),br(Tt.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{q(!0),dr?.(e)},updateWallets:()=>Jr(),fundWallet:async(e,t)=>{let r=Tt.FUNDING_METHOD_SELECTION_SCREEN;cr({funding:Dt({address:e,appConfig:nr,fundWalletConfig:t,methodScreen:r})}),br(r)},openModal:br,requestFarcasterSignerStatus:async e=>{let t=await Hr(),r=le?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!rr||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!le?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let a=await k.requestFarcasterSignerStatus(e);return"approved"===a.status&&de(await k.getAuthenticatedUser()||le||null),a},connectCoinbaseSmartWallet:async()=>{nr.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=k.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||k.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Kr(e);await Vr("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await k.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return de(l),l}};xr=ha.recoverPrimaryWallet,jr=ha.recoverPrimaryWallet,Br=ha.solanaSignMessage;let pa=l((()=>({wallets:ue,ready:wr&&vr})),[ue,wr,vr]),wa=k.authFlow instanceof v,ma=!nr.headless&&nr.captchaEnabled&&!Y&&(G||wa);/*#__PURE__*/return e(St.Provider,{value:ua,children:/*#__PURE__*/e(bt.Provider,{value:Tr,children:/*#__PURE__*/e(Rt.Provider,{value:pa,children:/*#__PURE__*/e(Wt,{...nr,children:/*#__PURE__*/t(Ut.Provider,{value:ha,children:[/*#__PURE__*/e(At,{children:/*#__PURE__*/t(Ot,{data:lr,setModalData:cr,setInitialScreen:Bt,initialScreen:jt,authenticated:Y,open:H,children:[W.children,ma&&/*#__PURE__*/e(pe,{delayedExecution:!1}),/*#__PURE__*/e(Ct,{theme:{...nr.appearance.palette||{}}}),!nr.render.standalone&&/*#__PURE__*/e(we,{open:H})]})}),or&&ir?/*#__PURE__*/e(Ue,{appId:W.appId,appClientId:W.clientId,clientAnalyticsId:k.clientAnalyticsId,origin:k.apiUrl,mfaMethods:le?.mfaMethods,mfaPromise:_r,mfaSubmitPromise:Ar,onLoad:ar,onLoadFailed:()=>null}):null,nr.loginConfig.telegramAuthConfiguration&&
|
|
2
|
-
/*#__PURE__*/e(vt,{$if:!0,children:/*#__PURE__*/e(me,{scriptHost:W.apiUrl||z,botUsername:nr.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};export{kr as C,Wr as E,Xr as P,Sr as a,Pr as b,Hr as c,Kr as d,Gr as e,zr as f,Vr as g,qr as h,$r as i,Yr as j,Nr as l};
|