@privy-io/react-auth 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/cjs/client/user.js +1 -1
  2. package/dist/cjs/client.js +1 -1
  3. package/dist/cjs/components/LoginModal.js +1 -1
  4. package/dist/cjs/components/embedded-wallets/PriceDisplay.js +1 -1
  5. package/dist/cjs/components/embedded-wallets/SolanaTransactionDetails.js +1 -1
  6. package/dist/cjs/components/embedded-wallets/TransactionDetails.js +2 -2
  7. package/dist/cjs/components/embedded-wallets/TransactionDetailsWrapper.js +1 -1
  8. package/dist/cjs/components/embedded-wallets/TransactionTotal.js +1 -1
  9. package/dist/cjs/components/embedded-wallets/index.js +1 -1
  10. package/dist/cjs/config.js +1 -1
  11. package/dist/cjs/connectors/embeddedProvider.js +1 -1
  12. package/dist/cjs/connectors/index.js +1 -1
  13. package/dist/cjs/constants.js +1 -1
  14. package/dist/cjs/embedded-wallets/solana/provider.js +1 -1
  15. package/dist/cjs/embedded-wallets/solana/transaction.js +1 -1
  16. package/dist/cjs/hooks/privy-provider.js +1 -1
  17. package/dist/cjs/index.js +1 -1
  18. package/dist/cjs/lib/attempt.js +1 -0
  19. package/dist/cjs/lib/smart-wallets-shared.js +1 -1
  20. package/dist/cjs/lib/smart-wallets.js +1 -1
  21. package/dist/cjs/lib/solana/transaction.js +1 -1
  22. package/dist/cjs/lib/user/shouldCreateEmbeddedEthWallet.js +1 -0
  23. package/dist/cjs/lib/user/shouldCreateEmbeddedSolWallet.js +1 -0
  24. package/dist/cjs/lib/user/shouldProceedtoEmbeddedWalletCreationFlow.js +1 -0
  25. package/dist/cjs/lib/viem/toViemTransactionSerializable.js +1 -1
  26. package/dist/cjs/privy-components/wallets-pill/ConnectWalletView.js +1 -1
  27. package/dist/cjs/privy-components/wallets-pill/WalletsDialog.js +1 -1
  28. package/dist/cjs/privy-provider-CEfM_gA2.js +3 -0
  29. package/dist/cjs/screens/AffirmativeConsentScreen.js +1 -1
  30. package/dist/cjs/screens/AwaitingPasswordlessCodeScreen.js +2 -2
  31. package/dist/cjs/screens/ConnectOnlyStatusScreen.js +1 -1
  32. package/dist/cjs/screens/ConnectionStatusScreen.js +2 -2
  33. package/dist/cjs/screens/CrossAppAuthScreen.js +1 -1
  34. package/dist/cjs/screens/EmbeddedWalletCreatedScreen.js +1 -1
  35. package/dist/cjs/screens/EmbeddedWalletOnAccountCreateScreen.js +1 -1
  36. package/dist/cjs/screens/FarcasterConnectStatusScreen.js +2 -2
  37. package/dist/cjs/screens/Funding/AwaitingEvmToSolBridgingScreen.js +1 -1
  38. package/dist/cjs/screens/Funding/AwaitingExternalSolanaTransferScreen.js +1 -1
  39. package/dist/cjs/screens/Funding/ManualTransferScreen.js +1 -1
  40. package/dist/cjs/screens/MfaScreens/MfaVerifyFlowScreen.js +1 -1
  41. package/dist/cjs/screens/MfaScreens/VerifyWithPasskey.js +1 -1
  42. package/dist/cjs/screens/OAuthStatusScreen.js +1 -1
  43. package/dist/cjs/screens/PasskeyStatusScreen.js +1 -1
  44. package/dist/cjs/screens/SendSolanaTransactionScreen/SendSolanaTransactionScreen.js +1 -1
  45. package/dist/cjs/screens/SendSolanaTransactionScreen/SolanaTransactionReceiptView.js +1 -1
  46. package/dist/cjs/screens/SendTransactionScreen/SendTransactionScreen.js +1 -1
  47. package/dist/cjs/screens/SendTransactionScreen/TransactionReceiptView.js +1 -1
  48. package/dist/cjs/screens/SendTransactionScreen/index.js +1 -1
  49. package/dist/cjs/screens/TelegramAuthScreen.js +1 -1
  50. package/dist/cjs/ui.js +1 -1
  51. package/dist/dts/farcaster.d.mts +1 -1
  52. package/dist/dts/farcaster.d.ts +1 -1
  53. package/dist/dts/index.d.mts +4 -4
  54. package/dist/dts/index.d.ts +4 -4
  55. package/dist/dts/smart-wallets.d.mts +4 -4
  56. package/dist/dts/smart-wallets.d.ts +4 -4
  57. package/dist/dts/solana.d.mts +4 -4
  58. package/dist/dts/solana.d.ts +4 -4
  59. package/dist/dts/{types-Do6eK2EI.d.mts → types-Cj9jWnPs.d.mts} +41 -1
  60. package/dist/dts/{types-Do6eK2EI.d.ts → types-Cj9jWnPs.d.ts} +41 -1
  61. package/dist/dts/ui.d.mts +1 -1
  62. package/dist/dts/ui.d.ts +1 -1
  63. package/dist/dts/{useSolanaWallets-CtSHyXUi.d.ts → useSolanaWallets-CFdCg_zF.d.mts} +1 -1
  64. package/dist/dts/{useSolanaWallets-CtSHyXUi.d.mts → useSolanaWallets-CFdCg_zF.d.ts} +1 -1
  65. package/dist/esm/client/user.mjs +1 -1
  66. package/dist/esm/client.mjs +1 -1
  67. package/dist/esm/components/LoginModal.mjs +1 -1
  68. package/dist/esm/components/embedded-wallets/PriceDisplay.mjs +1 -1
  69. package/dist/esm/components/embedded-wallets/SolanaTransactionDetails.mjs +1 -1
  70. package/dist/esm/components/embedded-wallets/TransactionDetails.mjs +2 -2
  71. package/dist/esm/components/embedded-wallets/TransactionDetailsWrapper.mjs +1 -1
  72. package/dist/esm/components/embedded-wallets/TransactionTotal.mjs +1 -1
  73. package/dist/esm/components/embedded-wallets/index.mjs +1 -1
  74. package/dist/esm/config.mjs +1 -1
  75. package/dist/esm/connectors/embeddedProvider.mjs +1 -1
  76. package/dist/esm/connectors/index.mjs +1 -1
  77. package/dist/esm/constants.mjs +1 -1
  78. package/dist/esm/embedded-wallets/solana/provider.mjs +1 -1
  79. package/dist/esm/embedded-wallets/solana/transaction.mjs +1 -1
  80. package/dist/esm/hooks/privy-provider.mjs +1 -1
  81. package/dist/esm/index.mjs +1 -1
  82. package/dist/esm/lib/attempt.mjs +1 -0
  83. package/dist/esm/lib/smart-wallets-shared.mjs +1 -1
  84. package/dist/esm/lib/smart-wallets.mjs +1 -1
  85. package/dist/esm/lib/solana/transaction.mjs +1 -1
  86. package/dist/esm/lib/user/shouldCreateEmbeddedEthWallet.mjs +1 -0
  87. package/dist/esm/lib/user/shouldCreateEmbeddedSolWallet.mjs +1 -0
  88. package/dist/esm/lib/user/shouldProceedtoEmbeddedWalletCreationFlow.mjs +1 -0
  89. package/dist/esm/lib/viem/toViemTransactionSerializable.mjs +1 -1
  90. package/dist/esm/privy-components/wallets-pill/ConnectWalletView.mjs +1 -1
  91. package/dist/esm/privy-components/wallets-pill/WalletsDialog.mjs +1 -1
  92. package/dist/esm/privy-provider-Dsr4yi3k.mjs +3 -0
  93. package/dist/esm/screens/AffirmativeConsentScreen.mjs +1 -1
  94. package/dist/esm/screens/AwaitingPasswordlessCodeScreen.mjs +2 -2
  95. package/dist/esm/screens/ConnectOnlyStatusScreen.mjs +1 -1
  96. package/dist/esm/screens/ConnectionStatusScreen.mjs +2 -2
  97. package/dist/esm/screens/CrossAppAuthScreen.mjs +1 -1
  98. package/dist/esm/screens/EmbeddedWalletCreatedScreen.mjs +1 -1
  99. package/dist/esm/screens/EmbeddedWalletOnAccountCreateScreen.mjs +1 -1
  100. package/dist/esm/screens/FarcasterConnectStatusScreen.mjs +2 -2
  101. package/dist/esm/screens/Funding/AwaitingEvmToSolBridgingScreen.mjs +1 -1
  102. package/dist/esm/screens/Funding/AwaitingExternalSolanaTransferScreen.mjs +1 -1
  103. package/dist/esm/screens/Funding/ManualTransferScreen.mjs +1 -1
  104. package/dist/esm/screens/MfaScreens/MfaVerifyFlowScreen.mjs +1 -1
  105. package/dist/esm/screens/MfaScreens/VerifyWithPasskey.mjs +1 -1
  106. package/dist/esm/screens/OAuthStatusScreen.mjs +1 -1
  107. package/dist/esm/screens/PasskeyStatusScreen.mjs +1 -1
  108. package/dist/esm/screens/SendSolanaTransactionScreen/SendSolanaTransactionScreen.mjs +1 -1
  109. package/dist/esm/screens/SendSolanaTransactionScreen/SolanaTransactionReceiptView.mjs +1 -1
  110. package/dist/esm/screens/SendTransactionScreen/SendTransactionScreen.mjs +1 -1
  111. package/dist/esm/screens/SendTransactionScreen/TransactionReceiptView.mjs +1 -1
  112. package/dist/esm/screens/SendTransactionScreen/index.mjs +1 -1
  113. package/dist/esm/screens/TelegramAuthScreen.mjs +1 -1
  114. package/dist/esm/ui.mjs +1 -1
  115. package/package.json +3 -3
  116. package/dist/cjs/privy-provider-Cq1Y-Omj.js +0 -3
  117. package/dist/esm/privy-provider-C-cTZKVr.mjs +0 -3
@@ -1,3 +0,0 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("mipd"),r=require("react"),a=require("react-device-detect"),n=require("viem/utils"),i=require("./auth-flows/custom-jwt-account.js"),o=require("./auth-flows/email.js"),s=require("./auth-flows/farcaster.js"),l=require("./auth-flows/guest.js"),c=require("./auth-flows/passkey.js"),d=require("./auth-flows/siwe.js"),u=require("./auth-flows/siws.js"),h=require("./auth-flows/sms.js"),y=require("./auth-flows/telegram.js"),p=require("uuid"),w=require("./accessToken.js"),E=require("./client/user.js"),v=require("eventemitter3"),m=require("./constants.js"),g=require("./storage.js"),f=require("./utils/index.js"),C=require("./connectors/coinbase.js"),A=require("./connectors/embedded.js"),P=require("./embedded-wallets/rpc/types.js"),_=require("./components/Captcha.js"),T=require("./components/LoginModal.js"),I=require("./components/TelegramLoginButton.js"),W=require("./configuration/context.js"),S=require("./connectors/areWalletArraysEqual.js"),k=require("./connectors/errors.js"),N=require("./connectors/isBaseConnectedEthereumWallet.js"),U=require("./connectors/mobile-wallets.js"),b=require("./connectors/solana/index.js"),O=require("./connectors/walletconnect-v2.js"),R=require("./embedded-wallets/EmbeddedWalletIframe.js"),M=require("./embedded-wallets/delegated-actions.js"),D=require("./embedded-wallets/errors.js"),F=require("./embedded-wallets/rpc/index.js"),L=require("./errors.js"),x=require("./embedded-wallets/solana/transaction.js"),q=require("./lib/caip2.js"),j=require("./lib/cross-app/index.js"),B=require("./lib/cross-app/authFlow.js"),H=require("./lib/cross-app/popupCrossAppAuthFlow.js"),K=require("./lib/cross-app/sendCrossAppRequest.js"),V=require("./lib/embeddedWalletRecovery.js"),G=require("./lib/funding/index.js"),z=require("./lib/funding/isFundingEnabled.js"),Y=require("./lib/isEmbeddedWebview.js"),$=require("./lib/popup/triggerPopup.js"),X=require("./lib/popupOAuthFlow.js"),J=require("./lib/siwe.js"),Q=require("./lib/solana/transaction.js"),Z=require("./lib/toDisplayFromAccountType.js"),ee=require("./lib/viem/prepareTransactionRequest.js"),te=require("./passkeys/transformResponseToSnakeCase.js"),re=require("./plugins/context/PrivyPluginContext.js"),ae=require("./plugins/solana-funding/id.js"),ne=require("./recent-login/context.js"),ie=require("./screens/index.js"),oe=require("./screens/LandingScreen/styles.js"),se=require("./styles.js"),le=require("./utils/eth/getPublicClient.js"),ce=require("./hooks/index.js"),de=require("./hooks/captcha-context.js"),ue=require("./hooks/events-context.js"),he=require("./hooks/internal-context.js"),ye=require("./hooks/modal-context.js"),pe=require("./hooks/privy-context.js"),we=require("./hooks/useWallets.js"),Ee=require("./lib/funding/prepareFundingModalData.js"),ve=require("./auth-flows/oauth/detectCompletingOAuthFlow.js"),me=require("./auth-flows/oauth/OAuthFlow.js"),ge=require("./lib/viem/toViemTransactionSerializable.js"),fe=require("./connectors/getRpcTimeout.js"),Ce=require("./connectors/providerTypes.js"),Ae=require("./connectors/ethereum/index.js"),Pe=require("./connectors/ethereum/EthereumNullConnector.js"),_e=require("./connectors/injected.js"),Te=require("./connectors/metamask.js"),Ie=require("./connectors/privyProxyProvider.js"),We=require("./connectors/solana/SolanaNullConnector.js"),Se=require("./connectors/stored-connection.js"),ke=require("./http.js"),Ne=require("./lib/smart-wallet-helpers.js"),Ue=require("./passkeys/transformOptionsToCamelCase.js"),be=require("./paths.js"),Oe=require("./session.js");function Re(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var Me=/*#__PURE__*/Re(v);class De extends Me.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 Qe()||!this.address)throw new Ce.EmbeddedProviderError("Disconnected",4900);let{hash:r}=await rt(t,{address:this.address});return r}async handleSignTransaction(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 Qe()||!this.address)throw new Ce.EmbeddedProviderError("Disconnected",4900);let{signature:r}=await tt(t,{address:this.address});return r}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.publicClient=le.getPublicClient(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],{signature:a}=await Ze({message:t},{address:r});return a}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],{signature:a}=await et(f.generateTypedDataWithDomainType(r),{address:t});return a}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:f.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...ge.toViemTransactionSerializable(t)})}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 f.toHex(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"eth_signTransaction":return this.handleSignTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!P.isSupportedEthereumRpcMethod(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await Qe();if(await at(),!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.publicClient=le.getPublicClient(s,this.chains,n,{appId:o}),this.rpcTimeoutDuration=fe.getRpcTimeout(n,"privy"),this.appId=o,this.walletIndex=l}}class Fe extends Me.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}${t.meta.id}`;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;g.default.get(m.CONNECTORS_STATE_KEY)&&(g.default.getKeys().forEach((e=>{e.startsWith("walletconnect")&&g.default.del(e)})),g.default.del(m.CONNECTORS_STATE_KEY));let e=f.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({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),Object.values(U.mobileWalletsConfig)))!e.isInstalled&&this.walletList.includes(e.client)&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&e.chainTypes.includes("ethereum")&&this.createEthereumWalletConnector({connectorType:"null",walletClientType:e.client,walletConfig:e}),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&e.chainTypes.includes("solana")&&this.addWalletConnector(new We.SolanaNullConnector({id:e.client,name:e.name,icon:e.logoDataUri})));this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"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(b.isSolanaWalletConnector).find((r=>r.connectorType===e&&("unknown"===r.walletClientType?r.walletBranding.id===t: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&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id: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}=E.getEntropyDetailsFromAccount(t),s=new A.EmbeddedWalletConnector({provider:new De({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 A.EmbeddedWalletConnector({provider:new De({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=Se.loadConnectionHistory(),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=Se.loadConnectionHistory(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:a}){let n=this.findWalletConnector(e,t);if(n&&Ae.isEthereumWalletConnector(n))return n instanceof O.WalletConnectV2WalletConnector&&n.resetConnection(t),n;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new C.CoinbaseWalletConnector(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new O.WalletConnectV2WalletConnector(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):a?new Pe.EthereumNullConnector({id:a.client,name:a.name,icon:a.logoDataUri,defaultChain:this.defaultChain,walletClientType:a.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Te.MetamaskWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new _e.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new _e.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new _e.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new _e.Injected6963WalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return i&&this.addWalletConnector(i),i||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,id:e.meta.id})));g.default.put(m.CONNECTIONS_HISTORY_KEY,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&N.isBaseConnectedEthereumWallet(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=n.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 Ie.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=Se.loadConnectionHistory()}}let Le;var xe=0,qe="__private_"+xe+++"__getOrGenerateClientAnalyticsId";class je{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 Fe(this.appId,e,t,r,a,n,i,o,s,l,void 0,c))}generateApi(){let e=new ke.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 L.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new L.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(be.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw L.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(be.mfaPasskeyInitPath,{});return Ue.transformOptionsToCamelCase(e.options)}catch(e){throw L.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(be.acceptTermsPath,{});return E.convertUserResponseToUser(e)}catch(e){throw L.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(be.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw L.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(be.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw L.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(be.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw L.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(be.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw L.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(be.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(r)}catch(e){throw L.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(be.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw L.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(be.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw L.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(be.delegatedActionsRevokePath,{})}catch(e){throw L.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(be.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(be.moonpayPluginOnRampPath,e)}catch(e){throw L.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(be.coinbaseOnRampInitPath,e)}catch(e){throw L.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${be.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw L.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(Oe.AccessTokenTypes.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Oe.AccessTokenTypes.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?w.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:Ne.getPaymasterContext(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw L.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 L.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(be.siweInitPath,{address:e,token:t})).nonce}catch(e){throw L.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i}){return await this.api.post(be.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(be.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(be.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r});return E.convertUserResponseToUser(a)}catch(e){throw L.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 E.convertUserResponseToUser(i)}catch(e){throw L.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(be.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw L.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a,mode:n}){return await this.api.post(be.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=be.transferEmailPath,c={nonce:e,email:t};break;case"sms":l=be.transferPhonePath,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=be.transferWalletPath,!a)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...a};break;case"farcaster":l=be.transferFarcasterPath,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=be.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=be.transferOAuthPath,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??E.convertUserResponseToUser(d)}catch(e){throw L.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a}){return await this.api.post(be.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 E.convertUserResponseToUser(n)}catch(e){throw L.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(be.usersMePath);return this.session.updateIdentityToken(e.identity_token),E.convertUserResponseToUser(e.user)}catch(e){throw L.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(be.transactionScanningPath,e)}catch(e){throw L.formatPrivyError(e)}}constructor({apiUrl:e=m.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:a=m.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,qe,{value:Be}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==m.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,qe)[qe](),Le||(Le=new Oe.Session),this.session=Le,this.api=this.generateApi(),this.session.client=this}}function Be(){if("undefined"==typeof window)return null;try{let e=g.default.get(m.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=p.v4();try{return g.default.put(m.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}class He{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 it({message:e.params.message,address:this.address})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Qe())throw Error("User must be authenticated to use embedded Solana wallet");if(!await nt())throw new L.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 Ke,Ve,Ge,ze,Ye,$e,Xe,Je;async function Qe(){return Ke?Ke.getAccessToken():Promise.resolve(g.default.get(m.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||g.default.get(m.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const Ze=(e,t)=>Ve(e,t),et=(e,t)=>Ge(e,t),tt=(e,t)=>ze(e,t),rt=(e,t)=>Ye(e,t),at=()=>$e(),nt=()=>Xe(),it=({message:e,address:t})=>Je({message:e,address:t});let ot=p=>{let w=p.client,v=re.usePlugins(),[C,A]=r.useState(!1),[P,ge]=r.useState(!1),[fe,Ce]=r.useState(!1),[Ae,Pe]=r.useState(null),[_e,Te]=r.useState([]),[Ie,We]=r.useState([]),[Se,ke]=r.useState([]),[Ne,Ue]=r.useState(!1),[be,Oe]=r.useState(null),[Re,Me]=r.useState(!1),[De,Fe]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:ce.notImplemented}),[Le,xe]=r.useState({status:"initial"}),[qe,je]=r.useState({status:"initial"}),[Be,Ze]=r.useState({status:"initial"}),[et,tt]=r.useState({status:"initial"}),[rt,at]=r.useState({status:"initial"}),[nt,it]=r.useState(null),ot=W.useAppConfig(),st=W.useIsServerConfigLoaded(),[lt,ct]=r.useState(!0),[dt,ut]=r.useState({}),[ht,yt]=r.useState(null),[pt,wt]=r.useState(null),[Et,vt]=r.useState(!1),[mt,gt]=r.useState(!1),[ft,Ct]=r.useState(ot.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),At=r.useRef(null),Pt=r.useRef(null),_t=r.useRef(ue.privyEventsDefault),[Tt,It]=r.useState(!1);w.onStoreCustomerAccessToken=e=>{e&&ue.emitPrivyEvent(_t,"accessToken","onAccessTokenGranted",{accessToken:e})},w.onDeleteCustomerAccessToken=()=>{Pe(null),Ce(!1),ue.emitPrivyEvent(_t,"accessToken","onAccessTokenRemoved")};let Wt=r.useRef(null),St=r.useRef(null),kt=r.useRef(!1),Nt=({showWalletUIs:e})=>kt.current?kt.current:void 0!==e?!e:!ot.embeddedWallets.showWalletUIs,Ut=e=>{Oe(e),setTimeout((()=>{A(!0)}),15),w.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},bt=e=>{"off"!==ot.embeddedWallets.createOnLogin&&ct(!0),Ut(e)};r.useEffect((()=>{let e=[...E.getPrivySolanaHDWallets(Ae),E.getImportedPrivySolanaWallet(Ae)].filter((e=>!!e));nt&&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 L.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new L.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new He(nt,e.address),async signMessage(t){let r=await Qe();if(!r||!nt)throw new L.PrivyClientError("Must have valid access token and Privy wallet to send transaction",L.PrivyErrorCode.MUST_BE_AUTHENTICATED);let a=e.imported?E.getImportedPrivySolanaWallet(Ae):E.getPrivyPrimaryWallet(Ae);if(!a)throw new L.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(a);if(!await nr.recoverPrimaryWallet().catch((()=>!1)))throw new L.PrivyClientError("Wallet couldn't be connected",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);if(!Ae)throw new L.PrivyClientError("Attempting to sign a transaction with no user initialized");let{response:o}=await nt.rpc({accessToken:r,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:e.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 Jt({transaction:e,connection:t,transactionOptions:r,wallet:this});return a},async signTransaction(t){let r=await Qe();if(!r||!nt)throw new L.PrivyClientError("Must have valid access token and Privy wallet to send transaction",L.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await nr.recoverPrimaryWallet().catch((()=>!1)))throw new L.PrivyClientError("Wallet couldn't be connected",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let a=e.imported?e:E.getPrivyPrimaryWallet(Ae);if(!a)throw new L.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(a);return await x.signSolanaTransaction({tx:t,accessToken:r,walletProxy:nt,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:this.address,transactingWalletIndex:e.walletIndex??0}),t},loginOrLink:async()=>{throw new L.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[nt,Ae]),r.useEffect((()=>{if(!Ae)return void w.connectors?.removeEmbeddedWalletConnectors();let e=E.getPrivyEthereumWallet(Ae),t=E.getPrivyEthereumHDWallets(Ae),r=E.getImportedPrivyEthereumWallet(Ae);e&&t.length||w.connectors?.removeEmbeddedWalletConnectors(),r||w.connectors?.removeImportedWalletConnector(),w.connectors?nt?(e&&w.connectors.addEmbeddedWalletConnectors({walletProxy:nt,rootWallet:e,embeddedWallets:t,defaultChain:ot.defaultChain,appId:p.appId}),r&&w.connectors.addImportedWalletConnector(nt,r.address,ot.defaultChain,p.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")}),[nt,Ae]),r.useEffect((()=>{nt&&pt?.(nt)}),[nt]);let Ot=r.useRef();r.useEffect((()=>{(async()=>{if(!ot.customAuth?.enabled)return void Ct({status:"not-enabled"});ct(!0);let{getCustomAccessToken:e,isLoading:t}=ot.customAuth;if(P&&!t&&"loading"!==ft.status){Ct({status:"loading"});try{let t=await e();if(t===Ot.current)return void Ct({status:"done"});if(!t&&fe)return Ot.current=t,await ar.logout(),Ct({status:"done"}),void ue.emitPrivyEvent(_t,"customAuth","onUnauthenticated");if(!t)return Ot.current=t,void Ct({status:"done"});w.startAuthFlow(new i.CustomJwtAccountFlow(t));let{user:r,isNewUser:a}=await w.authenticate();if(!r)return await ar.logout(),Ct({status:"error",error:new L.PrivyClientError("Failed to sync with custom auth provider")}),void ue.emitPrivyEvent(_t,"customAuth","onUnauthenticated");void 0!==a&&ue.emitPrivyEvent(_t,"login","onComplete",{user:r,isNewUser:a,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),Ot.current=t,ue.emitPrivyEvent(_t,"customAuth","onAuthenticated",{user:r}),Ct({status:"done"}),Pe(r||null),Ue(a||!1),Ce(!0),gt(!0)}catch(e){if(console.warn(e),await ar.logout(),ue.emitPrivyEvent(_t,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void Ct({status:"initial"});ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),Ct({status:"error",error:e})}}})()}),["initial"===ft.status,ot.customAuth?.enabled,ot.customAuth?.getCustomAccessToken,ot.customAuth?.isLoading,P,fe]),r.useEffect((()=>{mt&&nt&&Ae&&E.shouldProceedtoEmbeddedWalletCreationFlow(Ae,ot.embeddedWallets.createOnLogin)&&(gt(!1),Vt(Ae,m.WALLET_PROXY_TIMEOUT).catch(console.error))}),[mt&&nt&&Ae]),r.useEffect((()=>{if(ot.externalWallets.solana.connectors)return ot.externalWallets.solana.connectors.onMount(),()=>ot.externalWallets.solana.connectors?.onUnmount()}),[ot.externalWallets.solana.connectors]),r.useEffect((()=>{!P&&st&&async function(){let e,r=Rt(),a=Mt();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;g.default.put(m.FORKED_TOKEN_STORAGE_KEY,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let n=t.createStore();w.initializeConnectorManager({walletConnectCloudProjectId:ot.walletConnectCloudProjectId,rpcConfig:ot.rpcConfig,chains:ot.chains,defaultChain:ot.defaultChain,store:n,walletList:ot.appearance.walletList,shouldEnforceDefaultChainOnConnect:ot.shouldEnforceDefaultChainOnConnect,externalWalletConfig:ot.externalWallets,appName:ot.name??"Privy",walletChainType:ot.appearance.walletChainType}),w.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=w.connectors.walletConnectors.length,r=w.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)})),w.connectors?.initialize().then((()=>{qt()}));let i=await w.getAuthenticatedUser(),o=!!i;ot.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await w.logout(),nr.setReadyToTrue(!0),ue.emitPrivyEvent(_t,"logout","onSuccess")):(ot.customAuth?.enabled||(Ce(!!i),i&&ue.emitPrivyEvent(_t,"login","onComplete",{user:i,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),Pe(i)),r?St.current=o?"link":"login":a&&!o?(St.current="login",ut({telegramAuthModalData:{seamlessAuth:!0}}),bt(ie.ModalScreen.TELEGRAM_AUTH_SCREEN)):nr.setReadyToTrue(!!i))}()}),[w,ht,P,st]),r.useEffect((()=>{if(P){if(!Ae||!Ae.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void vt(!0);vt([..._e,...Se].some((e=>"privy"===e.walletClientType)))}}),[P,Ae,_e,Se]);let Rt=()=>{let e=ve.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&&j.isPrivyTheOAuthProvider(e.provider)&&!e.popupFlow&&(new BroadcastChannel(j.CROSS_APP_BROADCAST_CHANNEL_NAME).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(w.startAuthFlow(new me.OAuthFlow(e)),bt(ie.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},Mt=()=>{let e=y.detectCompletingTelegramFlow();if(!e||!ot.loginMethods.telegram||!ot.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new y.TelegramAuthFlow;return w.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},Dt=async(e,t,r,a)=>{if("solana_adapter"!==e)Ft(await(w.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,a);else{let n=w.connectors?.findSolanaWalletConnector(e,t);if(!n)return;Ft(n,t,r,a)}};async function Ft(e,t,r,a){if(!e)return Fe({status:"disconnected",connectedWallet:null,connectError:new L.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:ce.notImplemented}),a?.(null,r);Fe({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:ce.notImplemented}),e instanceof O.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),Fe({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Ft(e,t,r,a)});try{let t=await e.connect({showPrompt:!0});if((!t||N.isBaseConnectedEthereumWallet(t))&&ot.shouldEnforceDefaultChainOnConnect&&!ot.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){Fe((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:ce.notImplemented})));try{await(t?.switchChain(ot.defaultChain.id)),t&&(t.chainId=f.formatChainIdToCAIP2(f.toHex(ot.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${ot.defaultChain.id}`)}}return Fe((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:ce.notImplemented}))),t&&ue.emitPrivyEvent(_t,"connectWallet","onSuccess",{wallet:t}),a?.(t,r)}catch(e){return e instanceof L.PrivyError?(console.warn(e.cause?e.cause:e.message),ue.emitPrivyEvent(_t,"connectWallet","onError",e.privyErrorCode||L.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),ue.emitPrivyEvent(_t,"connectWallet","onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),Fe((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),a?.(null,r)}}let Lt=async(e,t,r)=>{if(null===e||!N.isBaseConnectedEthereumWallet(e))return;let a=new d.SiweFlow(e,w,t,r);w.startAuthFlow(a)},xt=async(e,t,r)=>{if(null===e||!b.isBaseConnectedSolanaWallet(e))return;let a=new u.SiwsFlow(e,w,t,r);w.startAuthFlow(a)},qt=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),a="true"===e.get("privy_connect_only");if(!t||!r)return;let n=U.getWalletConfigForConnector({connectorType:t,walletClientType:r});if(!n||!n.isInstalled)return bt(ie.ModalScreen.LOGIN_FAILED_SCREEN);if(!w.connectors)throw new L.PrivyClientError("Connector not initialized");Ut(a?ie.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION:ie.ModalScreen.AWAITING_CONNECTION);let i=new URL(window.location.href);i.searchParams.delete("privy_connector"),i.searchParams.delete("privy_wallet_client"),i.searchParams.delete("privy_connect_only"),window.history.pushState({},"",i),Dt(t,r,void 0,a?void 0:"solana_adapter"===t?xt:Lt)};r.useEffect((()=>{P&&fe&&null===Ae&&w.getAuthenticatedUser().then(Pe)}),[P,fe,Ae,w]);let jt=e=>{if(!fe)throw ue.emitPrivyEvent(_t,"linkAccount","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new L.PrivyClientError("User must be authenticated before linking an account.")},Bt=e=>{if(!fe||!Ae)return!1;if("privy"===e.walletClientType)return!0;for(let t of Ae.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Ht=async e=>{let t;if(!w.connectors)throw new L.PrivyClientError("Connector not initialized");t="ethereum"===e.type?w.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:w.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,Fe((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:ce.notImplemented}))),ot.captchaEnabled&&!fe?(ut({captchaModalData:{callback:t=>N.isBaseConnectedEthereumWallet(e)?Lt(e,t):xt(e,t),userIntentRequired:!1,onSuccessNavigateTo:ie.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:ie.ModalScreen.ERROR_SCREEN}}),bt(ie.ModalScreen.CAPTCHA_SCREEN)):(N.isBaseConnectedEthereumWallet(e)?await Lt(e):await xt(e),bt(ie.ModalScreen.AWAITING_CONNECTION))},Kt=()=>{Te((e=>{let t=w.connectors?.wallets.filter(N.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Bt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new L.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new L.PrivyClientError("Cannot link or login with embedded wallet");Ht(e)},fund:async t=>{await nr.fundWallet(e.address,t)},unlink:async()=>{if(!fe)throw new L.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new L.PrivyClientError("Cannot unlink an embedded wallet");Pe(await w.unlinkEthereumWallet(e.address))}})))||[];return S.areWalletArraysEqual(e,t)?e:t})),We((e=>{let t=(w.connectors?.wallets??[]).filter(b.isBaseConnectedSolanaWallet).map((e=>({...e,linked:Bt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new L.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new L.PrivyClientError("Cannot link or login with embedded wallet");Ht(e)},fund:async()=>{throw new L.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!fe)throw new L.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new L.PrivyClientError("Cannot unlink an embedded wallet");Pe(await w.unlinkSolanaWallet(e.address))}})));return S.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{Kt()}),[Ae?.linkedAccounts,fe,P]),r.useEffect((()=>{if(P){if(!w.connectors)throw new L.PrivyClientError("Connector not initialized");Kt(),w.connectors.on("walletsUpdated",Kt)}}),[P]),r.useEffect((()=>{[...ot.loginMethodsAndOrder?.primary??[],...ot.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>w.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!w]);let Vt=async(e,t,r)=>{let a=E.getPrivyEthereumWallet(e),n=E.getPrivySolanaWallet(e);if(r&&"walletIndex"in r)return zt(e,t,r.walletIndex,a,n);let i=r&&"createAdditional"in r&&r.createAdditional;if(a&&!i)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[o,s]=await Promise.all([nr.initializeWalletProxy(t),Qe()]);if(!o&&ot.customAuth?.enabled)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||ot.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return Gt();if(!a)return n&&await nr.recoverPrimaryWallet(),await o.create({accessToken:s,solanaAddress:n?.address}),$t(0,"ethereum");{let t=(E.getLatestPrivyEthereumWallet(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:a}=E.getEntropyDetailsFromAccount(E.getPrivyPrimaryWallet(e));return await nr.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:r,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:t}),$t(t,"ethereum")}},Gt=async()=>new Promise(((e,t)=>{ct(!0),ut({createWallet:{onSuccess:t=>{ue.emitPrivyEvent(_t,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),Ut(ie.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),zt=async(e,t,r,a,n)=>{if(r<0)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[i,o]=await Promise.all([nr.initializeWalletProxy(t),Qe()]);if(!i&&ot.customAuth?.enabled)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!i||!o||ot.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return Gt();throw ue.emitPrivyEvent(_t,"createWallet","onError",L.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 ue.emitPrivyEvent(_t,"createWallet","onError",L.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=E.getPrivyEthereumHDWallets(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:n,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(E.getPrivyPrimaryWallet(e));await nr.recoverPrimaryWallet(),await i.addWallet({accessToken:o,entropyId:n,entropyIdVerifier:s,chainType:"ethereum",hdWalletIndex:r})}return $t(r,"ethereum")},Yt=async({user:e,wp:t,accessToken:r,walletIndex:a,ethereumWallet:n})=>{let i=E.getPrivySolanaHDWallets(e).find((e=>e.walletIndex===a));if(i)return i;if(0===a)n&&await nr.recoverPrimaryWallet(),await t.createSolana({accessToken:r,ethereumAddress:n?.address});else{let n=E.getPrivyPrimaryWallet(e);if(!n)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.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}=E.getEntropyDetailsFromAccount(n);await nr.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:i,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:a})}return $t(a,"solana")},$t=async(e,t)=>{let r=await nr.refreshSessionAndUser(),a=("ethereum"===t?E.getPrivyEthereumHDWallets(r):E.getPrivySolanaHDWallets(r)).find((t=>t.walletIndex===e));if(!a)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return ue.emitPrivyEvent(_t,"createWallet","onSuccess",{wallet:a}),a},Xt=({transaction:e,uiOptions:t,fundWalletConfig:r,address:a,signOnly:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=t||{},c=i?"signTransaction":"sendTransaction";if(!fe||!Ae)return ue.emitPrivyEvent(_t,c,"onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(Error("User must be authenticated before signing with a Privy wallet"));let d=a??E.getPrivyEthereumWallet(Ae)?.address;if(!d)throw new L.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:u,rootWallet:h}=E.getEthereumSigningAndRootWallet(Ae,d);if(!h||!u)return ue.emitPrivyEvent(_t,c,"onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have a Privy wallet before signing"));ct(!0);let y=ir.wallets.find((e=>"privy"===e.walletClientType&&n.getAddress(e.address)===n.getAddress(u.address))),w=await(y?.getEthereumProvider());if(!y||!w)throw new L.PrivyClientError(`Cannot sendTransaction before embedded wallet ${u.address} is connected`);let v=e.chainId?Number(e.chainId):q.extractChainIdFromCAIP2(y.chainId);(e=>{if(!ot.chains.map((e=>e.id)).includes(e))throw new L.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,L.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(v);let m={...e,from:e.from??u.address,chainId:v},g=await Qe();if(!g||!nt)return ue.emitPrivyEvent(_t,c,"onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have valid access token and Privy wallet to send transaction"));let f=le.getPublicClient(m.chainId,ot.chains,ot.rpcConfig,{appId:p.appId});if(Nt({showWalletUIs:t?.showWalletUIs}))(async()=>{try{if(!await nr.recoverPrimaryWallet())return ue.emitPrivyEvent(_t,c,"onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(Error("Unable to connect to wallet"));let e=await ee.prepareTransactionRequest(m,f,m.from),{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(h),a=i?await F.signTransaction({accessToken:g,entropyId:t,entropyIdVerifier:r,transactingWallet:u,walletProxy:nt,transactionRequest:m,requesterAppId:l}):await F.sendTransaction({accessToken:g,entropyId:t,entropyIdVerifier:r,transactingWallet:u,walletProxy:nt,transactionRequest:e,publicClient:f,requesterAppId:l});i?ue.emitPrivyEvent(_t,"signTransaction","onSuccess",{signature:a}):ue.emitPrivyEvent(_t,"sendTransaction","onSuccess",{hash:a}),o({hash:a})}catch(e){ue.emitPrivyEvent(_t,c,"onError",L.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:e,entropyIdVerifier:a}=E.getEntropyDetailsFromAccount(h),n={entropyId:e,entropyIdVerifier:a,onCompleteNavigateTo:ie.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{ue.emitPrivyEvent(_t,c,"onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},d=z.isFundingEnabled(ot)?Ee.prepareFundingModalData({address:u.address,appConfig:ot,fundWalletConfig:r,methodScreen:ie.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:m.chainId,comingFromSendTransactionScreen:!0}):void 0;ut({connectWallet:n,sendTransaction:{transactionRequest:m,transactingWallet:u,entropyId:e,entropyIdVerifier:a,signOnly:i,onConfirm:i?async()=>await F.signTransaction({accessToken:g,entropyId:e,entropyIdVerifier:a,transactingWallet:u,walletProxy:nt,transactionRequest:m,requesterAppId:l}):void 0,onSuccess:e=>{i?ue.emitPrivyEvent(_t,"signTransaction","onSuccess",{signature:e.hash}):ue.emitPrivyEvent(_t,"sendTransaction","onSuccess",{hash:e.hash}),o(e)},onFailure:e=>{ue.emitPrivyEvent(_t,c,"onError",L.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:t||{},fundWalletConfig:r,requesterAppId:l},funding:d}),Ut(ie.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),Jt=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:a,uiOptions:n,wallet:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=n||{};if(!fe||!Ae)return ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(new L.PrivyClientError("User must be authenticated before signing with a Privy wallet",L.PrivyErrorCode.MUST_BE_AUTHENTICATED));let c=i?Ae.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):E.getPrivySolanaWallet(Ae);if(!c)return ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new L.PrivyClientError("Must have a Privy wallet before signing",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));ct(!0);let{rootWallet:d}=E.getSolanaSigningAndRootWallet(Ae,c.address);if(!await nr.recoverPrimaryWallet().catch((()=>!1))||!d)throw ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new L.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${c.address} is connected`,L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);if(Nt({showWalletUIs:n?.showWalletUIs}))(async()=>{let a=await Qe();if(!a||!nt)return ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(new L.PrivyClientError("Must have valid access token and Privy wallet to send transaction",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{if(!await nr.recoverPrimaryWallet())return ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(new L.PrivyClientError("Unable to connect to wallet",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Nt({showWalletUIs:n?.showWalletUIs})&&!await Q.hasSufficientFunds(e,t))return ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.INSUFFICIENT_BALANCE),void s(new L.PrivyClientError("Solana wallet has insufficient funds for this transaction.",L.PrivyErrorCode.INSUFFICIENT_BALANCE));let{entropyId:i,entropyIdVerifier:l}=E.getEntropyDetailsFromUser(Ae),{signature:d,receipt:u}=await x.sendSolanaTransaction({accessToken:a,tx:e,connection:t,walletProxy:nt,transactionOptions:r,entropyId:i,entropyIdVerifier:l,transactingWalletAddress:c.address,transactingWalletIndex:c.walletIndex??0}),h=Q.createSolanaTransactionReceipt(d,u);ue.emitPrivyEvent(_t,"sendSolanaTransaction","onSuccess",{response:h}),o(h)}catch(e){ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:i,entropyIdVerifier:u}=E.getEntropyDetailsFromAccount(d),h={entropyId:i,entropyIdVerifier:u,onCompleteNavigateTo:ie.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},y=z.isFundingEnabled(ot)?Ee.prepareSolanaFundingModalData({address:c.address,appConfig:ot,methodScreen:ie.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:a,comingFromSendTransactionScreen:!0}):void 0;ut({connectWallet:h,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:c,onSuccess:e=>{ue.emitPrivyEvent(_t,"sendSolanaTransaction","onSuccess",{response:e}),o(e)},onFailure:e=>{ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:n||{},requesterAppId:l},funding:y}),Ut(ie.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function Qt(){return new Promise((async(e,t)=>{let r=await Qe();if(!r||!nt)throw Error("Must have valid access token to enroll in MFA");try{await nt.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let Zt=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],er=e=>{let t=Ae?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:a}=Z.toDisplayFromAccountType(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw ue.emitPrivyEvent(_t,"linkAccount","onError",L.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:a}),new L.PrivyClientError(`User already has an account of type ${r} linked.`)};async function tr({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){Oe(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!fe||!Ae)throw ue.emitPrivyEvent(_t,r,"onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let a=E.getPrivyPrimaryWallet(Ae);if(!a||!nt)throw ue.emitPrivyEvent(_t,r,"onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await Qt()}catch(e){throw ue.emitPrivyEvent(_t,r,"onError",L.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((n,i)=>{ct(!0);let o={onSuccess:e=>{ue.emitPrivyEvent(_t,r,"onSuccess",{method:"user-passcode",wallet:e}),n(e)},onFailure:e=>{ue.emitPrivyEvent(_t,r,"onError",L.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),i(e)},callAuthOnSuccessOnClose:!1},s="user-passcode"===a.recoveryMethod,l=V.toEmbeddedWalletSetRecoveryScreen({walletAction:"update",availableRecoveryMethods:ot.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:d}=E.getEntropyDetailsFromAccount(a);ut({setWalletPassword:o,recoverWallet:{entropyId:c,entropyIdVerifier:d,onFailure:i},createWallet:o,connectWallet:{onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,entropyIdVerifier:d,onFailure:e=>{ue.emitPrivyEvent(_t,r,"onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s}}),Ut(ie.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function rr({appId:e,action:t}){let r=await Qe();if("link"===t&&!r)throw ue.emitPrivyEvent(_t,"linkAccount","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new L.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw ue.emitPrivyEvent(_t,"login","onError",L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new L.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");Wt.current=`privy:${e}`,St.current=t;let a=$.triggerPopup();return w.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,n)=>{let{name:i,logoUrl:o}=await B.getProviderAppMetadata({api:w.api,providerAppId:e,requesterAppId:ot.id});ut({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:a,onSuccess:r,onError:n}}),bt(ie.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let ar={ready:P,authenticated:fe,user:Ae,walletConnectors:w.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),ut({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress}}),Ut(fe?ie.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:ie.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:()=>{jt("siwe"),Wt.current="siwe",St.current="link",Ut(ie.ModalScreen.LINK_WALLET_SCREEN)},startCrossAppAuthFlow:rr,linkEmail:()=>{jt("email"),er("email"),Wt.current="email",St.current="link",Ut(ie.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{jt("sms"),er("phone"),Wt.current="sms",St.current="link",Ut(ie.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{jt("google"),er("google_oauth"),St.current="link",await nr.initLoginWithOAuth("google")},linkTwitter:async()=>{jt("twitter"),er("twitter_oauth"),St.current="link",await nr.initLoginWithOAuth("twitter")},linkDiscord:async()=>{jt("discord"),er("discord_oauth"),St.current="link",await nr.initLoginWithOAuth("discord")},linkGithub:async()=>{jt("github"),er("github_oauth"),St.current="link",await nr.initLoginWithOAuth("github")},linkSpotify:async()=>{jt("spotify"),er("spotify_oauth"),St.current="link",await nr.initLoginWithOAuth("spotify")},linkInstagram:async()=>{jt("instagram"),er("instagram_oauth"),St.current="link",await nr.initLoginWithOAuth("instagram")},linkTiktok:async()=>{jt("tiktok"),er("tiktok_oauth"),St.current="link",await nr.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{jt("linkedin"),er("linkedin_oauth"),St.current="link",await nr.initLoginWithOAuth("linkedin")},linkApple:async()=>{jt("apple"),er("apple_oauth"),St.current="link",await nr.initLoginWithOAuth("apple")},linkPasskey:async()=>{jt("passkey"),er("passkey"),await nr.initLinkWithPasskey(),Ut(ie.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if(jt("telegram"),er("telegram"),St.current="link",Wt.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new y.TelegramAuthFlow;w.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=y.convertInitDataRawToTelegramWebAppData(e.launchParams.initDataRaw),ut({telegramAuthModalData:{seamlessAuth:!0}}),bt(ie.ModalScreen.TELEGRAM_AUTH_SCREEN)}else ue.emitPrivyEvent(_t,"linkAccount","onError",L.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await nr.initLoginWithTelegram();Ut(ie.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{jt("farcaster"),er("farcaster"),await nr.initLoginWithFarcaster(),St.current="link",Wt.current="farcaster",Ut(ie.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(jt("email"),!Ae?.email)throw new L.PrivyClientError("User does not have an email linked to their account.");St.current="update",Wt.current="email",Ut(ie.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(jt("sms"),!Ae?.phone)throw new L.PrivyClientError("User does not have a phone number linked to their account.");St.current="update",Wt.current="sms",Ut(ie.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(!P){let e=await new Promise((e=>{yt((t=>e.bind(t)))}));if(yt(null),e)return void console.warn(t)}!Ae||Ae.isGuest?(St.current="login",ut({login:e}),bt(ie.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{P||(await new Promise((e=>{yt((()=>e))})),yt(null)),fe?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(St.current="login",bt(ie.ModalScreen.CONNECT_OR_CREATE))},logout:async()=>{if(St.current=null,Wt.current=null,Ae&&w.clearProviderAcccessTokens(Ae),Oe(null),await w.logout(),Ae&&nt)try{await nt.clearMfa({userId:Ae.id})}catch(e){}Pe(null),Ce(!1),ue.emitPrivyEvent(_t,"logout","onSuccess"),A(!1),g.default.del(m.CLIENT_ANALYTICS_ID_KEY),g.default.del(m.getGuestCredentialStorageKey(ot.id))},getAccessToken:()=>w.getCustomerAccessToken(),unlinkWallet:async e=>{let t;return Pe(t=e.startsWith("0x")?await w.unlinkEthereumWallet(e):await w.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await w.unlinkEmail(e);return Pe(t),t},unlinkPhone:async e=>{let t=await w.unlinkPhone(e);return Pe(t),t},unlinkGoogle:async e=>{let t=await w.unlinkOAuth("google",e);return Pe(t),t},unlinkTwitter:async e=>{let t=await w.unlinkOAuth("twitter",e);return Pe(t),t},unlinkDiscord:async e=>{let t=await w.unlinkOAuth("discord",e);return Pe(t),t},unlinkGithub:async e=>{let t=await w.unlinkOAuth("github",e);return Pe(t),t},unlinkSpotify:async e=>{let t=await w.unlinkOAuth("spotify",e);return Pe(t),t},unlinkInstagram:async e=>{let t=await w.unlinkOAuth("instagram",e);return Pe(t),t},unlinkTiktok:async e=>{let t=await w.unlinkOAuth("tiktok",e);return Pe(t),t},unlinkLinkedIn:async e=>{let t=await w.unlinkOAuth("linkedin",e);return Pe(t),t},unlinkApple:async e=>{let t=await w.unlinkOAuth("apple",e);return Pe(t),t},unlinkFarcaster:async e=>{let t=await w.unlinkFarcaster(e);return Pe(t),t},unlinkTelegram:async e=>{let t=await w.unlinkTelegram(e);return Pe(t),t},unlinkPasskey:async e=>{let t=await Qe();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!nt)throw Error("Wallet proxy not initialized.");let r=ot.passkeys.shouldUnenrollMfaOnUnlink;await nt.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let a=await w.getAuthenticatedUser();return Pe(a),a},unlinkCrossAppAccount:async({subject:e})=>{let t=Ae?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new L.PrivyClientError("Invalid subject");w.storeProviderAccessToken(t.id,null);let r=await w.unlinkOAuth(`privy:${t.id}`,e);return Pe(r),r},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await nr.refreshSessionAndUser();if(!t)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return Vt(t,15e3,e)},setWalletRecovery:async e=>tr({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>tr({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:n}=t?.uiOptions||{},i=e.message;if(!fe||!Ae)return ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let o=t?.address??E.getPrivyEthereumWallet(Ae)?.address;if(!o)throw new L.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=E.getEthereumSigningAndRootWallet(Ae,o);if(!s||!l)return ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof i||i.length<1)return ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));ct(!0);let c=async()=>{if(!fe)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Qe();if(!nt||!e||!await nr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:s.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(l),{response:a}=await nt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:n,request:{method:"personal_sign",params:[i,s.address]}}),o=a.data;return w.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:s.address,requesterAppId:n}}),o};if(Nt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();ue.emitPrivyEvent(_t,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.UNABLE_TO_SIGN),a(e??new k.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"personal_sign",data:i,confirmAndSign:c,onSuccess:e=>{ue.emitPrivyEvent(_t,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(l);ut({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:o,onCompleteNavigateTo:ie.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Ut(ie.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:n}=t?.uiOptions||{};if(!fe||!Ae)return ue.emitPrivyEvent(_t,"signTypedData","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let i=t?.address??E.getPrivyEthereumWallet(Ae)?.address;if(!i)throw new L.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:o,rootWallet:s}=E.getEthereumSigningAndRootWallet(Ae,i);if(!s||!o)return ue.emitPrivyEvent(_t,"signTypedData","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));ct(!0);let l=f.generateTypedDataWithDomainType(e),c=async()=>{if(!fe)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Qe();if(!nt||!e||!await nr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:o.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(s),{response:a}=await nt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:o.walletIndex??0,requesterAppId:n,request:{method:"eth_signTypedData_v4",params:[o.address,l]}}),i=a.data;return w.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:o.address,requesterAppId:n}}),i};if(Nt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();ue.emitPrivyEvent(_t,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){ue.emitPrivyEvent(_t,"signTypedData","onError",L.PrivyErrorCode.UNABLE_TO_SIGN),a(e??new k.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:l,confirmAndSign:c,onSuccess:e=>{ue.emitPrivyEvent(_t,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{ue.emitPrivyEvent(_t,"signTypedData","onError",L.PrivyErrorCode.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(s);ut({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:i,onCompleteNavigateTo:ie.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Ut(ie.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t)=>await Xt({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await Xt({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!fe||!Ae)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??E.getPrivyEthereumWallet(Ae)?.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}=E.getEthereumSigningAndRootWallet(Ae,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));ct(!0);let{entropyId:o,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(i),l={entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:ie.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0};ut(dt),await Qe()&&nt?nt?(ut({keyExport:{appId:p.appId,appClientId:p.clientId,origin:w.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r},connectWallet:l}),Ut(ie.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:Qt,async init(e){switch(e){case"sms":return void await w.initMfaSmsVerification();case"passkey":return await w.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 L.PrivyClientError("Invalid MFA code");At.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{Pt.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new L.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),a=te.transformResponseToSnakeCase(await r.startAuthentication(t));At.current?.resolve({mfaMethod:e,mfaCode:a,relyingParty:window.origin}),await new Promise(((e,t)=>{Pt.current={resolve:e,reject:t}}));break;default:throw At.current?.reject(new L.PrivyClientError("Unsupported MFA method")),new L.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){At.current?.reject(new L.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Qe();if(!t||!nt)throw Error("Must have valid access token to enroll in MFA");await nt.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return nr.closePrivyModal(),void t();ot.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."),ut({mfaEnrollmentFlow:{mfaMethods:ot.mfa.methods,shouldUnlinkOnUnenrollMfa:ot.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),Ut(ie.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await Qe();if(!e||!nt)throw Error("Must have valid access token to enroll in MFA");let t=await nt.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Qe();if(!t||!nt)throw Error("Must have valid access token to enroll in MFA");await nt.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),Pe(await w.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Qe();if(!t||!nt)throw Error("Must have valid access token to enroll in MFA");await nt.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),Pe(await w.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await Qe();if(!r||!nt)throw Error("Must have valid access token to enroll in MFA");await nt.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),Pe(await w.getAuthenticatedUser())},async unenroll(e,t={}){let r=await Qe();if(!r||!nt)throw Error("Must have valid access token to remove MFA");"passkey"===e?await nt.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await nt.unenrollMfa({method:e,accessToken:r}),Pe(await w.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Qe(),t=Ae?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!nt||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Ae?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await nr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await nt.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&Pe(await w.getAuthenticatedUser()||Ae||null),ut({farcasterSigner:r}),Ut(ie.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await Qe(),r=Ae?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!nt||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Ae?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await nr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!Ae.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=Ae.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Qe(),r=Ae?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!nt||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Ae?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await nr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!Ae.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let a=await import("@simplewebauthn/browser"),n=await nt.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:a.bufferToBase64URLString(e)},fid:BigInt(Ae.farcaster.fid),relyingParty:window.origin});return new Uint8Array(a.base64URLStringToBuffer(n.signature))},createGuestAccount:async()=>{if(Ae&&!Ae.isGuest)throw Error("User cannot already be authenticated to create a guest account");return Ae?.isGuest?Ae:nr.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let a=Ae?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return K.sendCrossAppRequest({user:Ae,client:w,address:t,requesterAppId:ot.id,request:{method:a?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:rr})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let a=Ae?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),n=f.generateTypedDataWithDomainType(e);return K.sendCrossAppRequest({user:Ae,client:w,address:t,requesterAppId:ot.id,request:{method:a?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,n],chainId:r},reconnect:rr})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=Ae?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return K.sendCrossAppRequest({user:Ae,client:w,address:t,requesterAppId:ot.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:rr})},isModalOpen:C,mfaMethods:ot.mfa.methods};Ve=ar.signMessage,Ge=ar.signTypedData,Ye=async(e,t)=>await Xt({transaction:e,...t,signOnly:!1}),ze=async(e,t)=>({signature:(await Xt({transaction:e,...t,signOnly:!0})).hash});let nr={setAuthenticated:Ce,setUser:Pe,isNewUserThisSession:Ne,pendingTransaction:null,walletConnectionStatus:De,connectors:w.connectors?.walletConnectors??[],solanaWallets:Ie,rpcConfig:ot.rpcConfig,chains:ot.chains,appId:p.appId,showFiatPrices:"native-token"!==ot.embeddedWallets.priceDisplay.primary,clientAnalyticsId:w.clientAnalyticsId,customAuthStatus:ft,hideWalletUIs:kt,emailOtpState:qe,setEmailOtpState:je,smsOtpState:Be,setSmsOtpState:Ze,oAuthState:rt,setOAuthState:at,siweState:et,setSiweState:tt,isHeadlessOAuthLoading:Re,nativeTokenSymbolForChainId:e=>ot.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(nt)return nt;let t=new Promise((e=>{wt((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),a=await Promise.race([t,r]);return wt(null),a},getAuthFlow:()=>w.authFlow,getAuthMeta:()=>w.authFlow?.meta,client:w,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=P&&fe&&Ae;r&&Wt.current&&(t=Zt(Ae)),"login"===St.current?e.shouldCallAuthOnSuccess&&r&&Wt.current?ue.emitPrivyEvent(_t,"login","onComplete",{user:Ae,isNewUser:Ne,wasAlreadyAuthenticated:!1,loginMethod:Wt.current,loginAccount:t??null}):ue.emitPrivyEvent(_t,"login","onError",L.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===St.current&&t?e.isSuccess&&r&&Wt.current?ue.emitPrivyEvent(_t,"linkAccount","onSuccess",{user:Ae,linkMethod:Wt.current,linkedAccount:t}):Wt.current&&ue.emitPrivyEvent(_t,"linkAccount","onError",L.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:Wt.current}):"update"===St.current&&t&&(e.isSuccess&&r&&Wt.current?ue.emitPrivyEvent(_t,"update","onSuccess",{user:Ae,updateMethod:Wt.current,updatedAccount:t}):Wt.current&&ue.emitPrivyEvent(_t,"update","onError",L.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:Wt.current}));let a=be&&G.FUNDING_SCREENS.includes(be),n=be===ie.ModalScreen.ERROR_SCREEN&&dt.errorModalData&&G.FUNDING_SCREENS.includes(dt.errorModalData.previousScreen);if((a||n)&&dt.funding){let e,t=G.fundingScreenMethodMap[be]??null;if("solana"===dt.funding.chainType){let r=v(ae.SOLANA_FUNDING_PLUGIN_ID);if(!r)return void console.warn("Unable to load solana plugin, skipping balance");try{e=BigInt(await r.getBalance({address:dt.funding.address,cluster:dt.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}ue.emitPrivyEvent(_t,"fundSolanaWallet","onUserExited",{address:dt.funding.address,cluster:dt.funding.cluster,fundingMethod:t,balance:e})}else{let r=le.getPublicClient(dt.funding.chain.id,ot.chains,ot.rpcConfig,{appId:p.appId});try{e=await r.getBalance({address:dt.funding.address})}catch{console.error("Unable to pull wallet balance")}ue.emitPrivyEvent(_t,"fundWallet","onUserExited",{address:dt.funding.address,chain:dt.funding.chain,fundingMethod:t,balance:e})}}ut({...dt,externalConnectWallet:{suggestedAddress:void 0}}),St.current=null,Wt.current=null,Ue(!1),A(!1),setTimeout((()=>{w.authFlow=void 0}),200),w.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:({message:e,address:t})=>new Promise((async(r,a)=>{if(!fe||!Ae)return ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let n=t??E.getPrivySolanaWallet(Ae)?.address;if(!n)throw new L.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:i,rootWallet:o}=E.getSolanaSigningAndRootWallet(Ae,n);if(!i||!o)return ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));ct(!0);let s=async()=>{if(!fe)throw Error("User must be authenticated before signing with a Privy wallet");let t=await w.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=nr.walletProxy??await nr.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await nr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!o)throw Error("No root wallet for signing wallet found");let{entropyId:a,entropyIdVerifier:n}=E.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(Nt({showWalletUIs:void 0}))try{let e=await s();r({signature:e})}catch(e){a(e)}else{let{entropyId:t,entropyIdVerifier:n}=E.getEntropyDetailsFromAccount(o);ut({signMessage:{method:"solana_signMessage",data:e,confirmAndSign:s,onSuccess:e=>{r({signature:e})},onFailure:e=>{a(e)},uiOptions:{}},connectWallet:{entropyId:t,entropyIdVerifier:n,onCompleteNavigateTo:ie.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ue.emitPrivyEvent(_t,"signMessage","onError",L.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),bt(ie.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:a,fundWalletConfig:n,address:i})=>{let o=i?Se.find((e=>e.address===i)):Se.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw ue.emitPrivyEvent(_t,"sendSolanaTransaction","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new L.PrivyClientError("Embedded wallet not found",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);return await Jt({transaction:e,connection:t,transactionOptions:a,uiOptions:r,fundWalletConfig:n,wallet:o})},openPrivyModal:Ut,connectWallet:Ft,initLoginWithWallet:async(e,t,r)=>{N.isBaseConnectedEthereumWallet(e)?(Wt.current="siwe",Lt(e,t,r)):(Wt.current="siws",xt(e,t,r))},loginWithWallet:async()=>{let e,t,r;if(!P)throw new L.PrivyNotReadyError;if(w.authFlow instanceof d.SiweFlow?e="siwe":w.authFlow instanceof u.SiwsFlow&&(e="siws"),!e)throw new L.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await w.getAccessToken())try{({user:t}=await w.link()),Wt.current=e}catch(t){throw ue.emitPrivyEvent(_t,"linkAccount","onError",t.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await w.authenticate()),Wt.current=e}catch(e){throw ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}Pe(t||Ae||null),Ue(r||!1),Ce(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(a,n)=>{let i=await Qe();if(!fe||!Ae||!i)throw new L.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new L.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=nr.walletProxy??await nr.initializeWalletProxy(15e3);if(!o)throw new L.PrivyClientError("Wallet proxy not initialized.");if(M.isWalletDelegated({address:e,chainType:t,user:Ae}))return a();let s=M.getDelegatedWalletsData({address:e,user:Ae}),l=M.getRootWalletDataForDelegation({address:e,user:Ae}),c=async()=>{await o.createDelegatedAction({accessToken:i,rootWallet:l,delegatedWallets:[s]}),await nr.refreshSessionAndUser()};if(!r){try{await c(),a()}catch(e){n(e)}return}await nr.recoverPrimaryWallet(),ut({delegatedActions:{consent:{address:e,onDelegate:c,onSuccess:async()=>{a()},onError:async e=>{n(e)}}}}),Ut(ie.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!fe||!Ae)throw new L.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===M.getDelegatedWalletsForUser(Ae).length)throw new L.PrivyClientError("User has no delegated wallets to revoke.");let a=async()=>{await w.revokeDelegatedWallet(),await nr.refreshSessionAndUser()};if(e)ut({delegatedActions:{revoke:{onRevoke:a,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),Ut(ie.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN);else try{await a(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new s.FarcasterFlow(e,t);w.startAuthFlow(r);try{Wt.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===St.current?ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===St.current&&ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!P)throw new L.PrivyNotReadyError;if(!(w.authFlow instanceof s.FarcasterFlow))throw new L.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await w.getAccessToken())try{({user:e}=await w.link()),Wt.current="farcaster"}catch(e){throw ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await w.authenticate()),Wt.current="farcaster"}catch(e){throw ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Pe(e||null),Ue(t||!1),Ce(!0)},async loginWithGuestAccountFlow(){let e=new l.GuestFlow(this.appId);w.startAuthFlow(e);try{St.current="login",Wt.current="guest";let{user:e,isNewUser:t}=await w.authenticate();if(t=t||!1,!e)throw new L.PrivyClientError("Unable to authenticate guest account");if(E.shouldProceedtoEmbeddedWalletCreationFlow(e,ot.embeddedWallets.createOnLogin))try{await Vt(e,15e3),e=await nr.refreshSessionAndUser()}catch(t){Pe(e),console.warn("Unable to create embedded wallet for guest account")}else Pe(e);return Ue(t),Ce(!0),ue.emitPrivyEvent(_t,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let a=`privy:${e}`;Wt.current=a;let{url:n,stateCode:i,codeVerifier:o}=await B.getCrossAppAuthorizationUrl({api:w.api,appId:e});if(!n)throw w.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new L.PrivyClientError("No authorization URL returned for cross-app auth.");try{let s=await H.popupCrossAppAuthFlow({url:n,popup:t,provider:a}),l=s.stateCode,c=s.authorizationCode;if(l!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:i??"",returnedStateCode:l??""}}),new L.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,L.PrivyErrorCode.OAUTH_UNEXPECTED);let d=await B.authenticateCrossAppAccount({appId:e,codeVerifier:o,stateCode:l,authorizationCode:c,action:r,client:w});d&&w.storeProviderAccessToken(e,d);let u=await nr.refreshSessionAndUser();if(!u)throw new L.PrivyClientError("Unable to update user");return w.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),u}catch(e){throw w.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(Wt.current=e,!g.isLocalStorageAccessible())return void bt(ie.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&Y.default(window.navigator.userAgent))return void bt(ie.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:j.USE_BROADCAST_CHANNEL_EVENT_TYPE},"*"),g.default.del(m.HEADLESS_OAUTH_KEY),g.default.del(m.OAUTH_DISABLE_SIGNUP_KEY);let n=new me.OAuthFlow({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&n.addCaptchaToken(t),w.startAuthFlow(n);let i=await w.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&a.isAndroid&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!P)throw new L.PrivyNotReadyError;Wt.current="telegram";let r=new y.TelegramAuthFlow(e,t);w.startAuthFlow(r),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>ot.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:ot.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new L.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new L.PrivyClientError("Telegram was not initialized")):t(new L.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(w.authFlow instanceof y.TelegramAuthFlow))throw new L.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");if(w.authFlow.meta.captchaToken||=e,"login"===St.current)try{let e=await w.authenticate();t=e.user,r=e.isNewUser,Wt.current="telegram"}catch(e){throw ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==St.current)throw new L.PrivyClientError("Unknown auth intent");try{t=(await w.link()).user,Wt.current="telegram"}catch(e){throw ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}Pe(t),Ue(r||!1),Ce(!0)},async recoveryOAuthFlow(e,t,r){let a,n;function i(t){if(!t)throw w.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new L.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,o,{url:s,codeVerifier:l,stateCode:c}=await V.getRecoveryAuthorizationUrl({api:Ke.api,provider:e});i(s);try{let a=await X.popupOAuthFlow({url:s,popup:r,provider:e});if(t=a.stateCode,o=a.authorizationCode,t!==c)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:c??"",returnedStateCode:t??""}}),new L.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,L.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw w.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new L.PrivyClientError("Recovery OAuth failed")}[a,n]=await Promise.all([Qe(),V.authenticateRecovery({api:Ke.api,provider:e,codeVerifier:l,stateCode:t,authorizationCode:o})]);break}case"icloud":{let{url:t}=await V.getRecoveryAuthorizationUrl({api:Ke.api,provider:e});i(t);let{ckWebAuthToken:o}=await X.popupOAuthFlow({url:t,popup:r,provider:e});n=o,a=await Qe()}}if(!nt)throw new L.PrivyClientError("Cannot connect to wallet proxy");if(!a)throw new L.PrivyClientError("Unable to authorize user");switch(t){case"recover":{let t=dt.recoverWallet?.entropyId,r=dt.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new L.PrivyClientError("Recovery OAuth failed");w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await nt.recover({accessToken:a,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:n}),w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{w.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await nt.create({accessToken:a,recoveryAccessToken:n,recoveryMethod:e});let t=E.getPrivyEthereumWallet(await nr.refreshSessionAndUser());if(!t)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),ue.emitPrivyEvent(_t,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=E.getPrivyPrimaryWallet(Ae);if(!t)throw ue.emitPrivyEvent(_t,"setWalletRecovery","onError",L.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");w.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(t);await nt.setRecovery({accessToken:a,entropyId:r,entropyIdVerifier:i,recoveryMethod:e,recoveryAccessToken:n});let o=E.getPrivyPrimaryWallet(await nr.refreshSessionAndUser());if(!o)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),ue.emitPrivyEvent(_t,"setWalletRecovery","onSuccess",{method:e,wallet:o});break}default:throw new L.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,a;if(!(w.authFlow instanceof me.OAuthFlow))throw new L.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let n=g.default.get(m.STATE_CODE_KEY),i=w.authFlow.meta.stateCode;if(n!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:n??"",returnedStateCode:i??""}}),new L.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,L.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await w.getAccessToken())try{let r=await w.link();t=r.user,a=r.oAuthTokens,Wt.current=e}catch(t){throw ue.emitPrivyEvent(_t,"linkAccount","onError",t.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let n=await w.authenticate();t=n.user,r=n.isNewUser,a=n.oAuthTokens,Wt.current=e}catch(t){throw"login"===St.current?ue.emitPrivyEvent(_t,"login","onError",t.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===St.current&&ue.emitPrivyEvent(_t,"linkAccount","onError",t.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return Pe(t),Ue(r||!1),Ce(!0),a&&t&&ue.emitPrivyEvent(_t,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),a},passkeyAuthState:Le,setPasskeyAuthState:xe,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new c.PasskeyFlow({captchaToken:e,setPasskeyAuthState:xe});w.startAuthFlow(r),St.current="login";try{Wt.current="passkey",xe({status:"generating-challenge"}),await r.initRegisterFlow(t),xe({status:"awaiting-passkey"})}catch(e){throw xe({status:"error",error:e}),ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!P)throw new L.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new L.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Wt.current){let e=new L.PrivyClientError("Must init login with Passkey flow first.");throw xe({status:"error",error:e}),e}let r=await Qe();try{Wt.current="passkey",xe({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await w.authenticate())}catch(e){throw xe({status:"error",error:e}),ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Pe(e),Ue(t||!1),Ce(!0),xe({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 c.PasskeyFlow({captchaToken:e,setPasskeyAuthState:xe});w.startAuthFlow(r),St.current="login";try{Wt.current="passkey",xe({status:"generating-challenge"}),await r.initAuthenticationFlow(t),xe({status:"awaiting-passkey"})}catch(e){throw xe({status:"error",error:e}),ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(){let e,t;if(!P)throw new L.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new L.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Wt.current){let e=new L.PrivyClientError("Must init login with Passkey flow first.");throw xe({status:"error",error:e}),e}let r=await Qe();try{Wt.current="passkey",xe({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await w.authenticate())}catch(e){throw xe({status:"error",error:e}),ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Pe(e),Ue(t||!1),Ce(!0),xe({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 c.PasskeyFlow({captchaToken:e});w.startAuthFlow(t),St.current="link",Wt.current="passkey",xe({status:"generating-challenge"});try{await t.initLinkFlow(),xe({status:"awaiting-passkey"})}catch(e){throw ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),xe({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!P)throw new L.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new L.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Wt.current)throw new L.PrivyClientError("Must init login with Passkey flow first.");try{Wt.current="passkey",({user:e}=await w.link())}catch(e){throw ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return Pe(e||Ae||null),xe({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!g.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&&Y.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 me.OAuthFlow({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&a.addCaptchaToken(t),at({status:"loading"});let n=await w.startAuthFlow(a).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,r,a;Me(!0),at({status:"loading"}),w.startAuthFlow(new me.OAuthFlow(e));let n=g.default.get(m.STATE_CODE_KEY),i=e.stateCode;if(n!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:n??"",returnedStateCode:i??""}}),Me(!1),new L.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,L.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await w.getAccessToken())try{({user:t,oAuthTokens:a}=await w.link()),Wt.current=e.provider;let r=Zt(t);t&&r&&ue.emitPrivyEvent(_t,"linkAccount","onSuccess",{user:t,linkMethod:Wt.current,linkedAccount:r})}catch(t){throw Me(!1),ue.emitPrivyEvent(_t,"linkAccount","onError",t.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:a}=await w.authenticate()),Wt.current=e.provider;let n=Zt(t);t&&n&&void 0!==r&&ue.emitPrivyEvent(_t,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:Wt.current,loginAccount:n})}catch(e){throw Me(!1),at({status:"error",error:e}),ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return Pe(t),Ue(r||!1),Ce(!0),Me(!1),at({status:"done"}),a&&t&&ue.emitPrivyEvent(_t,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{let n=new o.EmailFlow({email:e,captchaToken:t,disableSignup:r});w.startAuthFlow(n);try{Wt.current="email",je({status:"sending-code"}),await n.sendCodeEmail({withPrivyUi:a}),je({status:"awaiting-code-input"})}catch(e){throw je({status:"error",error:e}),"login"===St.current?ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===St.current&&ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let a=new o.UpdateEmailFlow(e,t,r);w.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){ue.emitPrivyEvent(_t,"update","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Wt.current})}},initUpdatePhone:async(e,t,r)=>{let a=new h.UpdateSmsFlow(e,t,r);w.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){ue.emitPrivyEvent(_t,"update","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Wt.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{Ze({status:"sending-code"});let n=new h.SmsFlow({phoneNumber:e,captchaToken:t,disableSignup:r});w.startAuthFlow(n);try{Wt.current="sms",await n.sendSmsCode({withPrivyUi:a}),Ze({status:"awaiting-code-input"})}catch(e){throw Ze({status:"error",error:e}),"login"===St.current?ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===St.current&&ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(w.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(w.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function a(e){w.authFlow instanceof o.EmailFlow?je(e):w.authFlow instanceof h.SmsFlow&&Ze(e)}if(a({status:"submitting-code"}),!P){let e=new L.PrivyNotReadyError;throw a({status:"error",error:e}),e}if(w.authFlow instanceof o.EmailFlow)w.authFlow.meta.emailCode=e.trim();else{if(!(w.authFlow instanceof h.SmsFlow)){let e=new L.PrivyClientError("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}w.authFlow.meta.smsCode=e.trim()}let n=await Qe();if("link"===St.current)try{({user:t}=await w.link())}catch(e){throw a({status:"error",error:e}),ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:Wt.current}),e}else if("update"===St.current)try{({user:t}=await w.link())}catch(e){throw a({status:"error",error:e}),ue.emitPrivyEvent(_t,"update","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:Wt.current}),e}else try{({user:t,isNewUser:r}=await w.authenticate())}catch(e){throw a({status:"error",error:e}),ue.emitPrivyEvent(_t,"login","onError",e.privyErrorCode||L.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let i=t||Ae;Pe(i||null),Ue(r||!1),Ce(!0),a({status:"done"});let s=null;return w.authFlow instanceof o.EmailFlow?s=i?.linkedAccounts.find((({type:e})=>"email"===e))||null:w.authFlow instanceof h.SmsFlow&&(s=i?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:i,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{St.current="link",Wt.current="siwe",tt({status:"generating-message"});let a=await w.generateSiweNonce({address:e,captchaToken:r});return tt({status:"awaiting-signature"}),J.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await w.generateSiweNonce({address:e});return J.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let a;a=await w.linkSmartWallet({message:e,signature:t,smartWalletType:r}),Pe((a=await nr.refreshSessionAndUser()??a)||Ae||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})=>{let i;jt("siwe");let o=null;try{tt({status:"submitting-signature"}),i=await w.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}),i=await nr.refreshSessionAndUser()??i,tt({status:"done"}),(o=Zt(i)||null)&&ue.emitPrivyEvent(_t,"linkAccount","onSuccess",{user:i,linkMethod:"siwe",linkedAccount:o})}catch(e){throw ue.emitPrivyEvent(_t,"linkAccount","onError",e.privyErrorCode||L.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),St.current=null,Wt.current=null,tt({status:"error",error:e}),e}let s=i||Ae;return Pe(s||null),St.current=null,Wt.current=null,{user:s,linkedAccount:o}},refreshSessionAndUser:async()=>{let e=await w.getAuthenticatedUser();return Ce(!!e),Pe(e),e},walletProxy:nt,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>w.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await w.acceptTerms();return Pe(e),e},getUsdTokenPrice:e=>w.getUsdTokenPrice(e),getUsdPriceForSol:()=>w.getUsdPriceForSol(),getSplTokenMetadata:e=>w.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let a=E.getPrivyPrimaryWallet(e?.user??Ae)||E.getImportedPrivyEthereumWallet(e?.user??Ae)||E.getImportedPrivySolanaWallet(e?.user??Ae),n=await Qe();if(!n||!nt||!a)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));ct(!0);let{entropyId:i,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(a);try{await nt.connect({accessToken:n,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){D.errorIndicatesRecoveryIsNeeded(e)&&"privy"===a.recoveryMethod?(w.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}}),(await nt.recover({entropyId:i,entropyIdVerifier:o,accessToken:n})).entropyId||r(Error("Unable to recover wallet")),w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)):D.errorIndicatesRecoveryIsNeeded(e)&&"privy"!==a.recoveryMethod?(ut({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover"}}),Ut(V.embeddedWalletRecoveryScreen(a.recoveryMethod))):r(e)}})),embeddedSolanaWallets:Se,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await nr.refreshSessionAndUser();if(!fe||!t)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let a=E.getPrivyEthereumWallet(e),n=E.getPrivySolanaWallet(e),i=r&&"createAdditional"in r&&r.createAdditional,o=r&&"walletIndex"in r?r.walletIndex:void 0,s=(E.getLatestPrivySolanaWallet(e)?.walletIndex??-1)+1;if(n&&!i&&"number"!=typeof o)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof o&&o<0)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${o}) is invalid.`);let[l,c]=await Promise.all([nr.initializeWalletProxy(t),Qe()]);if(!l||!c)throw ue.emitPrivyEvent(_t,"createWallet","onError",L.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await Yt({user:e,wp:l,accessToken:c,walletIndex:o??s,ethereumWallet:a})})(t,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!fe||!Ae)return void r(Error("User must be authenticated before exporting their Privy wallet"));let a=e?.address??E.getPrivySolanaWallet(Ae)?.address;if(!a)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:n,rootWallet:i}=E.getSolanaSigningAndRootWallet(Ae,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));if(ct(!0),!await Qe()||!nt)return void r(Error("Must have valid access token to enroll in MFA"));if(!nt)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(i);ut({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:ie.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0},keyExport:{appId:p.appId,appClientId:p.clientId,origin:w.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r}}),Ut(ie.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{ge(!0),ht?.(e)},updateWallets:()=>Kt(),fundWallet:async(e,t)=>{let r=ie.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;ut({funding:Ee.prepareFundingModalData({address:e,appConfig:ot,fundWalletConfig:t,methodScreen:r})}),Ut(r)},openModal:Ut,requestFarcasterSignerStatus:async e=>{let t=await Qe(),r=Ae?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!nt||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!Ae?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let a=await w.requestFarcasterSignerStatus(e);return"approved"===a.status&&Pe(await w.getAuthenticatedUser()||Ae||null),a},connectCoinbaseSmartWallet:async()=>{ot.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=w.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||w.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Ft(e);await Dt("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 w.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return Pe(l),l}};$e=nr.recoverPrimaryWallet,Xe=nr.recoverPrimaryWallet,Je=nr.solanaSignMessage;let ir=r.useMemo((()=>({wallets:_e,ready:Et&&Tt})),[_e,Et,Tt]),or=w.authFlow instanceof y.TelegramAuthFlow,sr=!ot.headless&&ot.captchaEnabled&&!fe&&(P||or);/*#__PURE__*/return e.jsx(pe.PrivyContext.Provider,{value:ar,children:/*#__PURE__*/e.jsx(ue.PrivyEventsContext.Provider,{value:_t,children:/*#__PURE__*/e.jsx(we.UseWalletsContext.Provider,{value:ir,children:/*#__PURE__*/e.jsx(de.CaptchaProvider,{...ot,children:/*#__PURE__*/e.jsxs(he.InternalPrivyContext.Provider,{value:nr,children:[/*#__PURE__*/e.jsx(ne.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(ye.ModalProvider,{data:dt,setModalData:ut,setInitialScreen:Oe,initialScreen:be,authenticated:fe,open:C,children:[p.children,sr&&/*#__PURE__*/e.jsx(_.Captcha,{delayedExecution:!1}),/*#__PURE__*/e.jsx(se.GlobalStyle,{theme:{...ot.appearance.palette||{}}}),!ot.render.standalone&&/*#__PURE__*/e.jsx(T.LoginModal,{open:C})]})}),lt&&st?/*#__PURE__*/e.jsx(R.EmbeddedWalletIframe,{appId:p.appId,appClientId:p.clientId,clientAnalyticsId:w.clientAnalyticsId,origin:w.apiUrl,mfaMethods:Ae?.mfaMethods,mfaPromise:At,mfaSubmitPromise:Pt,onLoad:it,onLoadFailed:()=>null}):null,ot.loginConfig.telegramAuthConfiguration&&
2
- /*#__PURE__*/e.jsx(oe.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(I.TelegramLoginButton,{scriptHost:p.apiUrl||m.DEFAULT_PRIVY_API_URL,botUsername:ot.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};exports.ConnectorManager=Fe,exports.Embedded1193Provider=De,exports.EmbeddedSolanaProvider=He,exports.PrivyClient=je,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 L.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(a=r.appId)||25!==a.length)throw new L.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");Ke||(Ke=new je({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let n=Object.assign({},t);/*#__PURE__*/
3
- return e.jsx(W.PrivyAppConfigProvider,{client:Ke,clientConfig:n,children:/*#__PURE__*/e.jsx(re.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(ot,{...r,client:Ke})})})},exports.getAccessToken=Qe,exports.getCustomerAccessToken=function(){return Ke?Ke.getCustomerAccessToken():Promise.resolve(g.default.get(m.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.globalRecoverEthereumModal=at,exports.globalRecoverSolanaModal=nt,exports.globalSignMessageModal=Ze,exports.globalSignSolanaModal=it,exports.globalSignTransactionModal=tt,exports.globalSignTypedDataModal=et,exports.globalTransactModal=rt;
@@ -1,3 +0,0 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import{createStore as a}from"mipd";import{useState as r,useRef as n,useEffect as i,useMemo as o}from"react";import{isAndroid as s}from"react-device-detect";import{getAddress as l}from"viem/utils";import{CustomJwtAccountFlow as c}from"./auth-flows/custom-jwt-account.mjs";import{UpdateEmailFlow as d,EmailFlow as u}from"./auth-flows/email.mjs";import{FarcasterFlow as h}from"./auth-flows/farcaster.mjs";import{GuestFlow as p}from"./auth-flows/guest.mjs";import{PasskeyFlow as w}from"./auth-flows/passkey.mjs";import{SiweFlow as m}from"./auth-flows/siwe.mjs";import{SiwsFlow as y}from"./auth-flows/siws.mjs";import{UpdateSmsFlow as g,SmsFlow as f}from"./auth-flows/sms.mjs";import{TelegramAuthFlow as E,convertInitDataRawToTelegramWebAppData as A,detectCompletingTelegramFlow as _}from"./auth-flows/telegram.mjs";import{v4 as T}from"uuid";import{AccessToken as v}from"./accessToken.mjs";import{getEntropyDetailsFromAccount as C,convertUserResponseToUser as I,getPrivySolanaHDWallets as k,getImportedPrivySolanaWallet as W,getPrivyPrimaryWallet as N,getPrivyEthereumWallet as U,getPrivyEthereumHDWallets as b,getImportedPrivyEthereumWallet as O,shouldProceedtoEmbeddedWalletCreationFlow as S,getPrivySolanaWallet as R,getLatestPrivyEthereumWallet as D,getSolanaSigningAndRootWallet as M,getEthereumSigningAndRootWallet as P,getLatestPrivySolanaWallet as L,getEntropyDetailsFromUser as F}from"./client/user.mjs";import x from"eventemitter3";import{CONNECTORS_STATE_KEY as j,CONNECTIONS_HISTORY_KEY as B,DEFAULT_PRIVY_API_URL as V,DEFAULT_API_TIMEOUT_MS as H,CLIENT_ANALYTICS_ID_KEY as K,CUSTOMER_ACCESS_TOKEN_STORAGE_KEY as z,PRIVY_ACCESS_TOKEN_STORAGE_KEY as G,getGuestCredentialStorageKey as q,HEADLESS_OAUTH_KEY as $,OAUTH_DISABLE_SIGNUP_KEY as Y,STATE_CODE_KEY as X,WALLET_PROXY_TIMEOUT as Q,FORKED_TOKEN_STORAGE_KEY as J}from"./constants.mjs";import Z,{isLocalStorageAccessible as ee}from"./storage.mjs";import{generateTypedDataWithDomainType as te,toHex as ae,detectInjectedConnectors as re,formatChainIdToCAIP2 as ne}from"./utils/index.mjs";import{CoinbaseWalletConnector as ie}from"./connectors/coinbase.mjs";import{EmbeddedWalletConnector as oe}from"./connectors/embedded.mjs";import{isSupportedEthereumRpcMethod as se}from"./embedded-wallets/rpc/types.mjs";import{Captcha as le}from"./components/Captcha.mjs";import{LoginModal as ce}from"./components/LoginModal.mjs";import{TelegramLoginButton as de}from"./components/TelegramLoginButton.mjs";import{PrivyAppConfigProvider as ue,useAppConfig as he,useIsServerConfigLoaded as pe}from"./configuration/context.mjs";import{areWalletArraysEqual as we}from"./connectors/areWalletArraysEqual.mjs";import{PrivyProviderRpcError as me}from"./connectors/errors.mjs";import{isBaseConnectedEthereumWallet as ye}from"./connectors/isBaseConnectedEthereumWallet.mjs";import{mobileWalletsConfig as ge,getWalletConfigForConnector as fe}from"./connectors/mobile-wallets.mjs";import{isSolanaWalletConnector as Ee,isBaseConnectedSolanaWallet as Ae}from"./connectors/solana/index.mjs";import{WalletConnectV2WalletConnector as _e}from"./connectors/walletconnect-v2.mjs";import{EmbeddedWalletIframe as Te}from"./embedded-wallets/EmbeddedWalletIframe.mjs";import{isWalletDelegated as ve,getDelegatedWalletsData as Ce,getRootWalletDataForDelegation as Ie,getDelegatedWalletsForUser as ke}from"./embedded-wallets/delegated-actions.mjs";import{errorIndicatesRecoveryIsNeeded as We}from"./embedded-wallets/errors.mjs";import{signTransaction as Ne,sendTransaction as Ue}from"./embedded-wallets/rpc/index.mjs";import{PrivyClientError as be,formatApiError as Oe,formatPrivyError as Se,PrivyErrorCode as Re,PrivyNotReadyError as De,PrivyConnectorError as Me,PrivyError as Pe}from"./errors.mjs";import{signSolanaTransaction as Le,sendSolanaTransaction as Fe}from"./embedded-wallets/solana/transaction.mjs";import{extractChainIdFromCAIP2 as xe}from"./lib/caip2.mjs";import{USE_BROADCAST_CHANNEL_EVENT_TYPE as je,isPrivyTheOAuthProvider as Be,CROSS_APP_BROADCAST_CHANNEL_NAME as Ve}from"./lib/cross-app/index.mjs";import{getCrossAppAuthorizationUrl as He,authenticateCrossAppAccount as Ke,getProviderAppMetadata as ze}from"./lib/cross-app/authFlow.mjs";import{popupCrossAppAuthFlow as Ge}from"./lib/cross-app/popupCrossAppAuthFlow.mjs";import{sendCrossAppRequest as qe}from"./lib/cross-app/sendCrossAppRequest.mjs";import{getRecoveryAuthorizationUrl as $e,authenticateRecovery as Ye,embeddedWalletRecoveryScreen as Xe,toEmbeddedWalletSetRecoveryScreen as Qe}from"./lib/embeddedWalletRecovery.mjs";import{FUNDING_SCREENS as Je,fundingScreenMethodMap as Ze}from"./lib/funding/index.mjs";import{isFundingEnabled as et}from"./lib/funding/isFundingEnabled.mjs";import tt from"./lib/isEmbeddedWebview.mjs";import{triggerPopup as at}from"./lib/popup/triggerPopup.mjs";import{popupOAuthFlow as rt}from"./lib/popupOAuthFlow.mjs";import{prepareSiweMessageWithNonce as nt}from"./lib/siwe.mjs";import{hasSufficientFunds as it,createSolanaTransactionReceipt as ot}from"./lib/solana/transaction.mjs";import{toDisplayFromAccountType as st}from"./lib/toDisplayFromAccountType.mjs";import{prepareTransactionRequest as lt}from"./lib/viem/prepareTransactionRequest.mjs";import{transformResponseToSnakeCase as ct}from"./passkeys/transformResponseToSnakeCase.mjs";import{PrivyPluginProvider as dt,usePlugins as ut}from"./plugins/context/PrivyPluginContext.mjs";import{SOLANA_FUNDING_PLUGIN_ID as ht}from"./plugins/solana-funding/id.mjs";import{RecentlyUsedAccountProvider as pt}from"./recent-login/context.mjs";import{ModalScreen as wt}from"./screens/index.mjs";import{Hide as mt}from"./screens/LandingScreen/styles.mjs";import{GlobalStyle as yt}from"./styles.mjs";import{getPublicClient as gt}from"./utils/eth/getPublicClient.mjs";import{notImplemented as ft}from"./hooks/index.mjs";import{CaptchaProvider as Et}from"./hooks/captcha-context.mjs";import{privyEventsDefault as At,emitPrivyEvent as _t,PrivyEventsContext as Tt}from"./hooks/events-context.mjs";import{InternalPrivyContext as vt}from"./hooks/internal-context.mjs";import{ModalProvider as Ct}from"./hooks/modal-context.mjs";import{PrivyContext as It}from"./hooks/privy-context.mjs";import{UseWalletsContext as kt}from"./hooks/useWallets.mjs";import{prepareSolanaFundingModalData as Wt,prepareFundingModalData as Nt}from"./lib/funding/prepareFundingModalData.mjs";import{detectCompletingOAuthFlow as Ut}from"./auth-flows/oauth/detectCompletingOAuthFlow.mjs";import{OAuthFlow as bt}from"./auth-flows/oauth/OAuthFlow.mjs";import{toViemTransactionSerializable as Ot}from"./lib/viem/toViemTransactionSerializable.mjs";import{getRpcTimeout as St}from"./connectors/getRpcTimeout.mjs";import{EmbeddedProviderError as Rt}from"./connectors/providerTypes.mjs";import{isEthereumWalletConnector as Dt}from"./connectors/ethereum/index.mjs";import{EthereumNullConnector as Mt}from"./connectors/ethereum/EthereumNullConnector.mjs";import{LegacyInjectedWalletConnector as Pt,Injected6963WalletConnector as Lt}from"./connectors/injected.mjs";import{MetamaskWalletConnector as Ft}from"./connectors/metamask.mjs";import{PrivyProxyProvider as xt}from"./connectors/privyProxyProvider.mjs";import{SolanaNullConnector as jt}from"./connectors/solana/SolanaNullConnector.mjs";import{loadConnectionHistory as Bt}from"./connectors/stored-connection.mjs";import{Http as Vt}from"./http.mjs";import{getPaymasterContext as Ht}from"./lib/smart-wallet-helpers.mjs";import{transformOptionsToCamelCase as Kt}from"./passkeys/transformOptionsToCamelCase.mjs";import{mfaPasswordlessSmsInitPath as zt,mfaPasskeyInitPath as Gt,acceptTermsPath as qt,unlinkEmailPath as $t,unlinkPhonePath as Yt,unlinkWalletPath as Xt,siwsUnlinkWalletPath as Qt,unlinkOAuthPath as Jt,unlinkFarcasterPath as Zt,telegramAccountUnlinkPath as ea,delegatedActionsRevokePath as ta,analyticsEventsPath as aa,moonpayPluginOnRampPath as ra,coinbaseOnRampInitPath as na,coinbaseOnRampStatusPath as ia,siweInitPath as oa,siweAuthenticatePath as sa,siweLinkPath as la,smartWalletLinkPath as ca,siwsInitPath as da,siwsAuthenticatePath as ua,transferOAuthPath as ha,telegramAccountTransferPath as pa,transferFarcasterPath as wa,transferWalletPath as ma,transferPhonePath as ya,transferEmailPath as ga,siwsLinkPath as fa,usersMePath as Ea,transactionScanningPath as Aa}from"./paths.mjs";import{AccessTokenTypes as _a,Session as Ta}from"./session.mjs";class va extends x{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Rt(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ja()||!this.address)throw new Rt("Disconnected",4900);let{hash:a}=await Ka(t,{address:this.address});return a}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Rt(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ja()||!this.address)throw new Rt("Disconnected",4900);let{signature:a}=await Ha(t,{address:this.address});return a}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new Rt(`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 Rt(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=gt(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],a=e.params[1],{signature:r}=await Ba({message:t},{address:a});return r}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],a="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1],{signature:r}=await Va(te(a),{address:t});return r}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:ae(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...Ot(t)})}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 ae(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"eth_signTransaction":return this.handleSignTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!se(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await ja();if(await za(),!t||!this.address)throw new Rt("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 Rt("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:a,entropyIdVerifier:r,rpcConfig:n,chains:i,appId:o,chainId:s=1,walletIndex:l}){super(),this.walletProxy=e,this.address=t,this.entropyId=a,this.entropyIdVerifier=r,this.chainId=s,this.rpcConfig=n,this.chains=i,this.publicClient=gt(s,this.chains,n,{appId:o}),this.rpcTimeoutDuration=St(n,"privy"),this.appId=o,this.walletIndex=l}}class Ca extends x{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 a=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(a)&&(e.add(a),!0)})),a=t.findIndex((e=>e.address===(this.activeWallet?this.activeWallet:"unknown")));return a>=0&&t.unshift(t.splice(a,1)[0]),t}async initialize(){if(this.initialized)return;Z.get(j)&&(Z.getKeys().forEach((e=>{e.startsWith("walletconnect")&&Z.del(e)})),Z.del(j));let e=re({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:a})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:a}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),Object.values(ge)))!e.isInstalled&&this.walletList.includes(e.client)&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&e.chainTypes.includes("ethereum")&&this.createEthereumWalletConnector({connectorType:"null",walletClientType:e.client,walletConfig:e}),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&e.chainTypes.includes("solana")&&this.addWalletConnector(new jt({id:e.client,name:e.name,icon:e.logoDataUri})));this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"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(Dt).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(Dt).find((a=>a.connectorType===e&&a.walletClientType===t))??null}findSolanaWalletConnector(e,t){return this.walletConnectors.filter(Ee).find((a=>a.connectorType===e&&("unknown"===a.walletClientType?a.walletBranding.id===t:a.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&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id: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:a,defaultChain:r,appId:n}){for(let i of a){let a=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(a&&Dt(a))a.proxyProvider.walletProxy=e;else{let{entropyId:a,entropyIdVerifier:o}=C(t),s=new oe({provider:new va({walletProxy:e,address:i.address,entropyId:a,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:r,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,a,r){let n=this.findWalletConnector("embedded_imported","privy");if(n&&Dt(n))n.proxyProvider.walletProxy=e;else{let n=new oe({provider:new va({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:r,chainId:a.id}),chains:this.chains,walletIndex:0,defaultChain:a,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(n)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=Bt(),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=Bt(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:a,walletConfig:r}){let n=this.findWalletConnector(e,t);if(n&&Dt(n))return n instanceof _e&&n.resetConnection(t),n;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new ie(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new _e(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):r?new Mt({id:r.client,name:r.name,icon:r.logoDataUri,defaultChain:this.defaultChain,walletClientType:r.client}):null:"metamask"===t&&a?.eip6963InjectedProvider?new Ft(this.chains,this.defaultChain,this.rpcConfig,a?.eip6963InjectedProvider,"metamask"):"metamask"===t&&a?.legacyInjectedProvider?new Pt(this.chains,this.defaultChain,this.rpcConfig,a?.legacyInjectedProvider,"metamask"):"phantom"===t&&a?.legacyInjectedProvider?new Pt(this.chains,this.defaultChain,this.rpcConfig,a?.legacyInjectedProvider,"phantom"):a?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Pt(this.chains,this.defaultChain,this.rpcConfig,a?.legacyInjectedProvider):a?.eip6963InjectedProvider?new Lt(this.chains,this.defaultChain,this.rpcConfig,a?.eip6963InjectedProvider,t):void 0)();return i&&this.addWalletConnector(i),i||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,id:e.meta.id})));Z.put(B,e)}async activeWalletSign(e){let t=this.wallets,a=t.length>0?t[0]:null;return a&&ye(a)?a.sign(e):null}setActiveWallet(e){this.activeWallet=l(e),this.emit("walletsUpdated")}constructor(e,t,a,r,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 xt},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=a,this.chains=r,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=Bt()}}let Ia;var ka=0,Wa="__private_"+ka+++"__getOrGenerateClientAnalyticsId";class Na{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:a,defaultChain:r,store:n,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new Ca(this.appId,e,t,a,r,n,i,o,s,l,void 0,c))}generateApi(){let e=new Vt({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 be("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new be("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(zt,{action:"verify"})}catch(e){throw Oe(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(Gt,{});return Kt(e.options)}catch(e){throw Oe(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 I(e)}catch(e){throw Se(e)}}async unlinkEmail(e){try{let t=await this.api.post($t,{address:e});return await this.getAuthenticatedUser()??I(t)}catch(e){throw Se(e)}}async unlinkPhone(e){try{let t=await this.api.post(Yt,{phoneNumber:e});return await this.getAuthenticatedUser()??I(t)}catch(e){throw Se(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(Xt,{address:e});return await this.getAuthenticatedUser()??I(t)}catch(e){throw Se(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(Qt,{address:e});return await this.getAuthenticatedUser()??I(t)}catch(e){throw Se(e)}}async unlinkOAuth(e,t){try{let a=await this.api.post(Jt,{provider:e,subject:t});return await this.getAuthenticatedUser()??I(a)}catch(e){throw Se(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(Zt,{fid:e});return await this.getAuthenticatedUser()??I(t)}catch(e){throw Se(e)}}async unlinkTelegram(e){try{let t=await this.api.post(ea,{telegram_user_id:e});return await this.getAuthenticatedUser()??I(t)}catch(e){throw Se(e)}}async revokeDelegatedWallet(){try{await this.api.post(ta,{})}catch(e){throw Se(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:a,options:r}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(aa,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:a?a.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:r?.keepAlive??!1})}catch(e){}}async signMoonpayOnRampUrl(e){try{return this.api.post(ra,e)}catch(e){throw Se(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(na,e)}catch(e){throw Se(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${ia}?partnerUserId=${e}`)}catch(e){throw Se(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(_a.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(_a.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?v.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 a=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return a.enabled?{enabled:a.enabled,smartWalletType:a.smart_wallet_type,configuredNetworks:a.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:Ht(e.paymaster_url,e.paymaster_context)})))}:{enabled:a.enabled}}catch(e){throw Se(e)}}async getServerConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let a=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:e}),r=a.telegram_auth_config?{botId:a.telegram_auth_config.bot_id,botName:a.telegram_auth_config.bot_name,linkEnabled:a.telegram_auth_config.link_enabled,seamlessAuthEnabled:a.telegram_auth_config.seamless_auth_enabled}:void 0,n=a.funding_config?{methods:a.funding_config.methods,options:a.funding_config.options,defaultRecommendedAmount:a.funding_config.default_recommended_amount,defaultRecommendedCurrency:a.funding_config.default_recommended_currency,promptFundingOnWalletCreation:a.funding_config.prompt_funding_on_wallet_creation,crossChainBridgingEnabled:a.funding_config.cross_chain_bridging_enabled}:void 0;return{id:a.id,name:a.name,verificationKey:a.verification_key,logoUrl:a.logo_url||void 0,accentColor:a.accent_color||void 0,showWalletLoginFirst:a.show_wallet_login_first,allowlistConfig:{errorTitle:a.allowlist_config.error_title,errorDetail:a.allowlist_config.error_detail,errorCtaText:a.allowlist_config.cta_text,errorCtaLink:a.allowlist_config.cta_link},walletAuth:a.wallet_auth,solanaWalletAuth:a.solana_wallet_auth,emailAuth:a.email_auth,smsAuth:a.sms_auth,googleOAuth:a.google_oauth,twitterOAuth:a.twitter_oauth,discordOAuth:a.discord_oauth,githubOAuth:a.github_oauth,spotifyOAuth:a.spotify_oauth,instagramOAuth:a.instagram_oauth,tiktokOAuth:a.tiktok_oauth,linkedinOAuth:a.linkedin_oauth,appleOAuth:a.apple_oauth,farcasterAuth:a.farcaster_auth,passkeyAuth:a.passkey_auth,passkeysForSignupEnabled:a.passkeys_for_signup_enabled,telegramAuth:a.telegram_auth,disablePlusEmails:a.disable_plus_emails,termsAndConditionsUrl:a.terms_and_conditions_url,embeddedWalletConfig:{createOnLogin:a.embedded_wallet_config?.create_on_login,userOwnedRecoveryOptions:a.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:a.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:a.privacy_policy_url,requireUsersAcceptTerms:a.require_users_accept_terms,customApiUrl:a.custom_api_url,walletConnectCloudProjectId:a.wallet_connect_cloud_project_id,fiatOnRampEnabled:a.fiat_on_ramp_enabled,captchaEnabled:a.captcha_enabled,captchaSiteKey:a.captcha_site_key,createdAt:new Date(1e3*a.created_at),updatedAt:new Date(1e3*a.updated_at),mfaMethods:a.mfa_methods,enforceWalletUis:a.enforce_wallet_uis,legacyWalletUiConfig:a.legacy_wallet_ui_config,telegramAuthConfiguration:r,fundingConfig:n}}catch(e){throw Se(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(a){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(oa,{address:e,token:t})).nonce}catch(e){throw Se(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:a,walletClientType:r,connectorType:n,mode:i}){return await this.api.post(sa,{message:e,signature:t,chainId:a,walletClientType:r,connectorType:n,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:a,walletClientType:r,connectorType:n}){return await this.api.post(la,{message:e,signature:t,chainId:a,walletClientType:r,connectorType:n})}async linkSmartWallet({message:e,signature:t,smartWalletType:a}){try{let r=await this.api.post(ca,{message:e,signature:t,smart_wallet_type:a});return I(r)}catch(e){throw Se(e)}}async linkWithSiwe({message:e,signature:t,chainId:a,walletClientType:r,connectorType:n}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:a,walletClientType:r,connectorType:n});return I(i)}catch(e){throw Se(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(da,{address:e,token:t})).nonce}catch(e){throw Se(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:a,connectorType:r,mode:n}){return await this.api.post(ua,{message:e,signature:t,walletClientType:a,connectorType:r,mode:n})}async sendAccountTransferRequest({nonce:e,account:t,accountType:a,externalWalletMetadata:r,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(a){case"email":l=ga,c={nonce:e,email:t};break;case"sms":l=ya,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=ma,!r)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...r};break;case"farcaster":l=wa,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=pa,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=ha,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??I(d)}catch(e){throw Se(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:a,connectorType:r}){return await this.api.post(fa,{message:e,signature:t,walletClientType:a,connectorType:r})}async linkWithSiws({message:e,signature:t,walletClientType:a,connectorType:r}){try{let n=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:a,connectorType:r});return I(n)}catch(e){throw Se(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(Ea);return this.session.updateIdentityToken(e.identity_token),I(e.user)}catch(e){throw Se(e)}}async scanTransaction(e){try{return await this.api.post(Aa,e)}catch(e){throw Se(e)}}constructor({apiUrl:e=V,appId:t,appClientId:a,timeout:r=H}){Object.defineProperty(this,Wa,{value:Ua}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==V&&e.startsWith("https://privy."),this.timeout=r,this.appId=t,this.appClientId=a,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,Wa)[Wa](),Ia||(Ia=new Ta),this.session=Ia,this.api=this.generateApi(),this.session.client=this}}function Ua(){if("undefined"==typeof window)return null;try{let e=Z.get(K);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=T();try{return Z.put(K,e),e}catch(t){return e}}class ba{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 qa({message:e.params.message,address:this.address})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await ja())throw Error("User must be authenticated to use embedded Solana wallet");if(!await Ga())throw new be("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 Oa,Sa,Ra,Da,Ma,Pa,La,Fa;function xa(){return Oa?Oa.getCustomerAccessToken():Promise.resolve(Z.get(z)||null)}async function ja(){return Oa?Oa.getAccessToken():Promise.resolve(Z.get(G)||Z.get(z)||null)}const Ba=(e,t)=>Sa(e,t),Va=(e,t)=>Ra(e,t),Ha=(e,t)=>Da(e,t),Ka=(e,t)=>Ma(e,t),za=()=>Pa(),Ga=()=>La(),qa=({message:e,address:t})=>Fa({message:e,address:t});const $a=({config:t,...a})=>{var r;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new be("Embedded wallet is only available over HTTPS");if("string"!=typeof(r=a.appId)||25!==r.length)throw new be("Cannot initialize the Privy provider with an invalid Privy app ID");Oa||(Oa=new Na({appId:a.appId,appClientId:a.clientId,apiUrl:a.apiUrl}));let n=Object.assign({},t);/*#__PURE__*/
2
- return e(ue,{client:Oa,clientConfig:n,children:/*#__PURE__*/e(dt,{children:/*#__PURE__*/e(Ya,{...a,client:Oa})})})};let Ya=T=>{let v=T.client,I=ut(),[x,j]=r(!1),[B,H]=r(!1),[z,G]=r(!1),[re,ie]=r(null),[oe,se]=r([]),[ue,ge]=r([]),[Ee,Oe]=r([]),[Se,dt]=r(!1),[Ot,St]=r(null),[Rt,Dt]=r(!1),[Mt,Pt]=r({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:ft}),[Lt,Ft]=r({status:"initial"}),[xt,jt]=r({status:"initial"}),[Bt,Vt]=r({status:"initial"}),[Ht,Kt]=r({status:"initial"}),[zt,Gt]=r({status:"initial"}),[qt,$t]=r(null),Yt=he(),Xt=pe(),[Qt,Jt]=r(!0),[Zt,ea]=r({}),[ta,aa]=r(null),[ra,na]=r(null),[ia,oa]=r(!1),[sa,la]=r(!1),[ca,da]=r(Yt.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),ua=n(null),ha=n(null),pa=n(At),[wa,ma]=r(!1);v.onStoreCustomerAccessToken=e=>{e&&_t(pa,"accessToken","onAccessTokenGranted",{accessToken:e})},v.onDeleteCustomerAccessToken=()=>{ie(null),G(!1),_t(pa,"accessToken","onAccessTokenRemoved")};let ya=n(null),ga=n(null),fa=n(!1),Ea=({showWalletUIs:e})=>fa.current?fa.current:void 0!==e?!e:!Yt.embeddedWallets.showWalletUIs,Aa=e=>{St(e),setTimeout((()=>{j(!0)}),15),v.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},_a=e=>{"off"!==Yt.embeddedWallets.createOnLogin&&Jt(!0),Aa(e)};i((()=>{let e=[...k(re),W(re)].filter((e=>!!e));qt&&Oe(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 be("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new be("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new ba(qt,e.address),async signMessage(t){let a=await ja();if(!a||!qt)throw new be("Must have valid access token and Privy wallet to send transaction",Re.MUST_BE_AUTHENTICATED);let r=e.imported?W(re):N(re);if(!r)throw new be("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=C(r);if(!await rr.recoverPrimaryWallet().catch((()=>!1)))throw new be("Wallet couldn't be connected",Re.UNKNOWN_CONNECT_WALLET_ERROR);if(!re)throw new be("Attempting to sign a transaction with no user initialized");let{response:o}=await qt.rpc({accessToken:a,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:e.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(o.data.signature,"base64")},async sendTransaction(e,t,a){let{signature:r}=await Xa({transaction:e,connection:t,transactionOptions:a,wallet:this});return r},async signTransaction(t){let a=await ja();if(!a||!qt)throw new be("Must have valid access token and Privy wallet to send transaction",Re.MUST_BE_AUTHENTICATED);if(!await rr.recoverPrimaryWallet().catch((()=>!1)))throw new be("Wallet couldn't be connected",Re.UNKNOWN_CONNECT_WALLET_ERROR);let r=e.imported?e:N(re);if(!r)throw new be("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=C(r);return await Le({tx:t,accessToken:a,walletProxy:qt,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:this.address,transactingWalletIndex:e.walletIndex??0}),t},loginOrLink:async()=>{throw new be("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[qt,re]),i((()=>{if(!re)return void v.connectors?.removeEmbeddedWalletConnectors();let e=U(re),t=b(re),a=O(re);e&&t.length||v.connectors?.removeEmbeddedWalletConnectors(),a||v.connectors?.removeImportedWalletConnector(),v.connectors?qt?(e&&v.connectors.addEmbeddedWalletConnectors({walletProxy:qt,rootWallet:e,embeddedWallets:t,defaultChain:Yt.defaultChain,appId:T.appId}),a&&v.connectors.addImportedWalletConnector(qt,a.address,Yt.defaultChain,T.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")}),[qt,re]),i((()=>{qt&&ra?.(qt)}),[qt]);let Ta=n();i((()=>{(async()=>{if(!Yt.customAuth?.enabled)return void da({status:"not-enabled"});Jt(!0);let{getCustomAccessToken:e,isLoading:t}=Yt.customAuth;if(B&&!t&&"loading"!==ca.status){da({status:"loading"});try{let t=await e();if(t===Ta.current)return void da({status:"done"});if(!t&&z)return Ta.current=t,await ar.logout(),da({status:"done"}),void _t(pa,"customAuth","onUnauthenticated");if(!t)return Ta.current=t,void da({status:"done"});v.startAuthFlow(new c(t));let{user:a,isNewUser:r}=await v.authenticate();if(!a)return await ar.logout(),da({status:"error",error:new be("Failed to sync with custom auth provider")}),void _t(pa,"customAuth","onUnauthenticated");void 0!==r&&_t(pa,"login","onComplete",{user:a,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),Ta.current=t,_t(pa,"customAuth","onAuthenticated",{user:a}),da({status:"done"}),ie(a||null),dt(r||!1),G(!0),la(!0)}catch(e){if(console.warn(e),await ar.logout(),_t(pa,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void da({status:"initial"});_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),da({status:"error",error:e})}}})()}),["initial"===ca.status,Yt.customAuth?.enabled,Yt.customAuth?.getCustomAccessToken,Yt.customAuth?.isLoading,B,z]),i((()=>{sa&&qt&&re&&S(re,Yt.embeddedWallets.createOnLogin)&&(la(!1),Ka(re,Q).catch(console.error))}),[sa&&qt&&re]),i((()=>{if(Yt.externalWallets.solana.connectors)return Yt.externalWallets.solana.connectors.onMount(),()=>Yt.externalWallets.solana.connectors?.onUnmount()}),[Yt.externalWallets.solana.connectors]),i((()=>{!B&&Xt&&async function(){let e,t=va(),r=Ca();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;Z.put(J,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let n=a();v.initializeConnectorManager({walletConnectCloudProjectId:Yt.walletConnectCloudProjectId,rpcConfig:Yt.rpcConfig,chains:Yt.chains,defaultChain:Yt.defaultChain,store:n,walletList:Yt.appearance.walletList,shouldEnforceDefaultChainOnConnect:Yt.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Yt.externalWallets,appName:Yt.name??"Privy",walletChainType:Yt.appearance.walletChainType}),v.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=v.connectors.walletConnectors.length,a=v.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);a===t?ma(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:a,expected:t}),ma(!0)}),1500)})),v.connectors?.initialize().then((()=>{Ua()}));let i=await v.getAuthenticatedUser(),o=!!i;Yt.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await v.logout(),rr.setReadyToTrue(!0),_t(pa,"logout","onSuccess")):(Yt.customAuth?.enabled||(G(!!i),i&&_t(pa,"login","onComplete",{user:i,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),ie(i)),t?ga.current=o?"link":"login":r&&!o?(ga.current="login",ea({telegramAuthModalData:{seamlessAuth:!0}}),_a(wt.TELEGRAM_AUTH_SCREEN)):rr.setReadyToTrue(!!i))}()}),[v,ta,B,Xt]),i((()=>{if(B){if(!re||!re.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void oa(!0);oa([...oe,...Ee].some((e=>"privy"===e.walletClientType)))}}),[B,re,oe,Ee]);let va=()=>{let e=Ut();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&&Be(e.provider)&&!e.popupFlow&&(new BroadcastChannel(Ve).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(v.startAuthFlow(new bt(e)),_a(wt.AWAITING_OAUTH_SCREEN),!0))},Ca=()=>{let e=_();if(!e||!Yt.loginMethods.telegram||!Yt.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new E;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},Ia=async(e,t,a,r)=>{if("solana_adapter"!==e)ka(await(v.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,a,r);else{let n=v.connectors?.findSolanaWalletConnector(e,t);if(!n)return;ka(n,t,a,r)}};async function ka(e,t,a,r){if(!e)return Pt({status:"disconnected",connectedWallet:null,connectError:new Me("Unable to connect to wallet."),connector:null,connectRetry:ft}),r?.(null,a);Pt({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:ft}),e instanceof _e&&t&&await e.resetConnection(t),Pt({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>ka(e,t,a,r)});try{let t=await e.connect({showPrompt:!0});if((!t||ye(t))&&Yt.shouldEnforceDefaultChainOnConnect&&!Yt.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){Pt((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:ft})));try{await(t?.switchChain(Yt.defaultChain.id)),t&&(t.chainId=ne(ae(Yt.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Yt.defaultChain.id}`)}}return Pt((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:ft}))),t&&_t(pa,"connectWallet","onSuccess",{wallet:t}),r?.(t,a)}catch(e){return e instanceof Pe?(console.warn(e.cause?e.cause:e.message),_t(pa,"connectWallet","onError",e.privyErrorCode||Re.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),_t(pa,"connectWallet","onError",Re.UNKNOWN_CONNECT_WALLET_ERROR)),Pt((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),r?.(null,a)}}let Wa=async(e,t,a)=>{if(null===e||!ye(e))return;let r=new m(e,v,t,a);v.startAuthFlow(r)},Na=async(e,t,a)=>{if(null===e||!Ae(e))return;let r=new y(e,v,t,a);v.startAuthFlow(r)},Ua=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),a=e.get("privy_wallet_client"),r="true"===e.get("privy_connect_only");if(!t||!a)return;let n=fe({connectorType:t,walletClientType:a});if(!n||!n.isInstalled)return _a(wt.LOGIN_FAILED_SCREEN);if(!v.connectors)throw new be("Connector not initialized");Aa(r?wt.AWAITING_CONNECT_ONLY_CONNECTION:wt.AWAITING_CONNECTION);let i=new URL(window.location.href);i.searchParams.delete("privy_connector"),i.searchParams.delete("privy_wallet_client"),i.searchParams.delete("privy_connect_only"),window.history.pushState({},"",i),Ia(t,a,void 0,r?void 0:"solana_adapter"===t?Na:Wa)};i((()=>{B&&z&&null===re&&v.getAuthenticatedUser().then(ie)}),[B,z,re,v]);let xa=e=>{if(!z)throw _t(pa,"linkAccount","onError",Re.MUST_BE_AUTHENTICATED,{linkMethod:e}),new be("User must be authenticated before linking an account.")},Ba=e=>{if(!z||!re)return!1;if("privy"===e.walletClientType)return!0;for(let t of re.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Va=async e=>{let t;if(!v.connectors)throw new be("Connector not initialized");t="ethereum"===e.type?v.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:v.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,Pt((a=>({...a,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:ft}))),Yt.captchaEnabled&&!z?(ea({captchaModalData:{callback:t=>ye(e)?Wa(e,t):Na(e,t),userIntentRequired:!1,onSuccessNavigateTo:wt.AWAITING_CONNECTION,onErrorNavigateTo:wt.ERROR_SCREEN}}),_a(wt.CAPTCHA_SCREEN)):(ye(e)?await Wa(e):await Na(e),_a(wt.AWAITING_CONNECTION))},Ha=()=>{se((e=>{let t=v.connectors?.wallets.filter(ye).map((e=>({...e,linked:Ba(e),loginOrLink:async()=>{if(!await e.isConnected())throw new be("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new be("Cannot link or login with embedded wallet");Va(e)},fund:async t=>{await rr.fundWallet(e.address,t)},unlink:async()=>{if(!z)throw new be("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new be("Cannot unlink an embedded wallet");ie(await v.unlinkEthereumWallet(e.address))}})))||[];return we(e,t)?e:t})),ge((e=>{let t=(v.connectors?.wallets??[]).filter(Ae).map((e=>({...e,linked:Ba(e),loginOrLink:async()=>{if(!await e.isConnected())throw new be("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new be("Cannot link or login with embedded wallet");Va(e)},fund:async()=>{throw new be("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!z)throw new be("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new be("Cannot unlink an embedded wallet");ie(await v.unlinkSolanaWallet(e.address))}})));return we(e,t)?e:t}))};i((()=>{Ha()}),[re?.linkedAccounts,z,B]),i((()=>{if(B){if(!v.connectors)throw new be("Connector not initialized");Ha(),v.connectors.on("walletsUpdated",Ha)}}),[B]),i((()=>{[...Yt.loginMethodsAndOrder?.primary??[],...Yt.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>v.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!v]);let Ka=async(e,t,a)=>{let r=U(e),n=R(e);if(a&&"walletIndex"in a)return Ga(e,t,a.walletIndex,r,n);let i=a&&"createAdditional"in a&&a.createAdditional;if(r&&!i)throw _t(pa,"createWallet","onError",Re.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[o,s]=await Promise.all([rr.initializeWalletProxy(t),ja()]);if(!o&&Yt.customAuth?.enabled)throw _t(pa,"createWallet","onError",Re.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||Yt.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return za();if(!r)return n&&await rr.recoverPrimaryWallet(),await o.create({accessToken:s,solanaAddress:n?.address}),$a(0,"ethereum");{let t=(D(e)?.walletIndex??0)+1,{entropyId:a,entropyIdVerifier:r}=C(N(e));return await rr.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:a,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:t}),$a(t,"ethereum")}},za=async()=>new Promise(((e,t)=>{Jt(!0),ea({createWallet:{onSuccess:t=>{_t(pa,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{_t(pa,"createWallet","onError",Re.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),Aa(wt.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),Ga=async(e,t,a,r,n)=>{if(a<0)throw _t(pa,"createWallet","onError",Re.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${a}) is invalid.`);let[i,o]=await Promise.all([rr.initializeWalletProxy(t),ja()]);if(!i&&Yt.customAuth?.enabled)throw _t(pa,"createWallet","onError",Re.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!i||!o||Yt.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==a)return za();throw _t(pa,"createWallet","onError",Re.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==a){if(r)return r;await i.create({accessToken:o,solanaAddress:n?.address})}else{if(!r)throw _t(pa,"createWallet","onError",Re.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=b(e).find((e=>e.walletIndex===a));if(t)return t;let{entropyId:n,entropyIdVerifier:s}=C(N(e));await rr.recoverPrimaryWallet(),await i.addWallet({accessToken:o,entropyId:n,entropyIdVerifier:s,chainType:"ethereum",hdWalletIndex:a})}return $a(a,"ethereum")},qa=async({user:e,wp:t,accessToken:a,walletIndex:r,ethereumWallet:n})=>{let i=k(e).find((e=>e.walletIndex===r));if(i)return i;if(0===r)n&&await rr.recoverPrimaryWallet(),await t.createSolana({accessToken:a,ethereumAddress:n?.address});else{let n=N(e);if(!n)throw _t(pa,"createWallet","onError",Re.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}=C(n);await rr.recoverPrimaryWallet(),await t.addWallet({accessToken:a,entropyId:i,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:r})}return $a(r,"solana")},$a=async(e,t)=>{let a=await rr.refreshSessionAndUser(),r=("ethereum"===t?b(a):k(a)).find((t=>t.walletIndex===e));if(!r)throw _t(pa,"createWallet","onError",Re.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return _t(pa,"createWallet","onSuccess",{wallet:r}),r},Ya=({transaction:e,uiOptions:t,fundWalletConfig:a,address:r,signOnly:n})=>new Promise((async(i,o)=>{let{requesterAppId:s}=t||{},c=n?"signTransaction":"sendTransaction";if(!z||!re)return _t(pa,c,"onError",Re.MUST_BE_AUTHENTICATED),void o(Error("User must be authenticated before signing with a Privy wallet"));let d=r??U(re)?.address;if(!d)throw new be("User must have an embedded wallet to send a transaction.");let{signingWallet:u,rootWallet:h}=P(re,d);if(!h||!u)return _t(pa,c,"onError",Re.EMBEDDED_WALLET_NOT_FOUND),void o(Error("Must have a Privy wallet before signing"));Jt(!0);let p=nr.wallets.find((e=>"privy"===e.walletClientType&&l(e.address)===l(u.address))),w=await(p?.getEthereumProvider());if(!p||!w)throw new be(`Cannot sendTransaction before embedded wallet ${u.address} is connected`);let m=e.chainId?Number(e.chainId):xe(p.chainId);(e=>{if(!Yt.chains.map((e=>e.id)).includes(e))throw new Me(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,Re.UNSUPPORTED_CHAIN_ID)})(m);let y={...e,from:e.from??u.address,chainId:m},g=await ja();if(!g||!qt)return _t(pa,c,"onError",Re.EMBEDDED_WALLET_NOT_FOUND),void o(Error("Must have valid access token and Privy wallet to send transaction"));let f=gt(y.chainId,Yt.chains,Yt.rpcConfig,{appId:T.appId});if(Ea({showWalletUIs:t?.showWalletUIs}))(async()=>{try{if(!await rr.recoverPrimaryWallet())return _t(pa,c,"onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),void o(Error("Unable to connect to wallet"));let e=await lt(y,f,y.from),{entropyId:t,entropyIdVerifier:a}=C(h),r=n?await Ne({accessToken:g,entropyId:t,entropyIdVerifier:a,transactingWallet:u,walletProxy:qt,transactionRequest:y,requesterAppId:s}):await Ue({accessToken:g,entropyId:t,entropyIdVerifier:a,transactingWallet:u,walletProxy:qt,transactionRequest:e,publicClient:f,requesterAppId:s});n?_t(pa,"signTransaction","onSuccess",{signature:r}):_t(pa,"sendTransaction","onSuccess",{hash:r}),i({hash:r})}catch(e){_t(pa,c,"onError",Re.TRANSACTION_FAILURE),o(e)}})();else{let{entropyId:e,entropyIdVerifier:r}=C(h),l={entropyId:e,entropyIdVerifier:r,onCompleteNavigateTo:wt.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{_t(pa,c,"onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}},d=et(Yt)?Nt({address:u.address,appConfig:Yt,fundWalletConfig:a,methodScreen:wt.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:y.chainId,comingFromSendTransactionScreen:!0}):void 0;ea({connectWallet:l,sendTransaction:{transactionRequest:y,transactingWallet:u,entropyId:e,entropyIdVerifier:r,signOnly:n,onConfirm:n?async()=>await Ne({accessToken:g,entropyId:e,entropyIdVerifier:r,transactingWallet:u,walletProxy:qt,transactionRequest:y,requesterAppId:s}):void 0,onSuccess:e=>{n?_t(pa,"signTransaction","onSuccess",{signature:e.hash}):_t(pa,"sendTransaction","onSuccess",{hash:e.hash}),i(e)},onFailure:e=>{_t(pa,c,"onError",Re.TRANSACTION_FAILURE),o(e)},uiOptions:t||{},fundWalletConfig:a,requesterAppId:s},funding:d}),Aa(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),Xa=({transaction:e,connection:t,transactionOptions:a,fundWalletConfig:r,uiOptions:n,wallet:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=n||{};if(!z||!re)return _t(pa,"sendSolanaTransaction","onError",Re.MUST_BE_AUTHENTICATED),void s(new be("User must be authenticated before signing with a Privy wallet",Re.MUST_BE_AUTHENTICATED));let c=i?re.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):R(re);if(!c)return _t(pa,"sendSolanaTransaction","onError",Re.EMBEDDED_WALLET_NOT_FOUND),void s(new be("Must have a Privy wallet before signing",Re.EMBEDDED_WALLET_NOT_FOUND));Jt(!0);let{rootWallet:d}=M(re,c.address);if(!await rr.recoverPrimaryWallet().catch((()=>!1))||!d)throw _t(pa,"sendSolanaTransaction","onError",Re.EMBEDDED_WALLET_NOT_FOUND),new be(`Cannot sendSolanaTransaction before embedded wallet ${c.address} is connected`,Re.EMBEDDED_WALLET_NOT_FOUND);if(Ea({showWalletUIs:n?.showWalletUIs}))(async()=>{let r=await ja();if(!r||!qt)return _t(pa,"sendSolanaTransaction","onError",Re.EMBEDDED_WALLET_NOT_FOUND),void s(new be("Must have valid access token and Privy wallet to send transaction",Re.EMBEDDED_WALLET_NOT_FOUND));try{if(!await rr.recoverPrimaryWallet())return _t(pa,"sendSolanaTransaction","onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),void s(new be("Unable to connect to wallet",Re.UNKNOWN_CONNECT_WALLET_ERROR));if(Ea({showWalletUIs:n?.showWalletUIs})&&!await it(e,t))return _t(pa,"sendSolanaTransaction","onError",Re.INSUFFICIENT_BALANCE),void s(new be("Solana wallet has insufficient funds for this transaction.",Re.INSUFFICIENT_BALANCE));let{entropyId:i,entropyIdVerifier:l}=F(re),{signature:d,receipt:u}=await Fe({accessToken:r,tx:e,connection:t,walletProxy:qt,transactionOptions:a,entropyId:i,entropyIdVerifier:l,transactingWalletAddress:c.address,transactingWalletIndex:c.walletIndex??0}),h=ot(d,u);_t(pa,"sendSolanaTransaction","onSuccess",{response:h}),o(h)}catch(e){_t(pa,"sendSolanaTransaction","onError",Re.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:i,entropyIdVerifier:u}=C(d),h={entropyId:i,entropyIdVerifier:u,onCompleteNavigateTo:wt.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{_t(pa,"sendSolanaTransaction","onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},p=et(Yt)?Wt({address:c.address,appConfig:Yt,methodScreen:wt.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:r,comingFromSendTransactionScreen:!0}):void 0;ea({connectWallet:h,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:a,transactingWallet:c,onSuccess:e=>{_t(pa,"sendSolanaTransaction","onSuccess",{response:e}),o(e)},onFailure:e=>{_t(pa,"sendSolanaTransaction","onError",Re.TRANSACTION_FAILURE),s(e)},uiOptions:n||{},requesterAppId:l},funding:p}),Aa(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function Qa(){return new Promise((async(e,t)=>{let a=await ja();if(!a||!qt)throw Error("Must have valid access token to enroll in MFA");try{await qt.verifyMfa({accessToken:a}),e()}catch(e){t(e)}}))}let Ja=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],Za=e=>{let t=re?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:a,loginMethod:r}=st(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw _t(pa,"linkAccount","onError",Re.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:r}),new be(`User already has an account of type ${a} linked.`)};async function er({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){St(null);let a=t?"setWalletPassword":"setWalletRecovery";if(!z||!re)throw _t(pa,a,"onError",Re.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let r=N(re);if(!r||!qt)throw _t(pa,a,"onError",Re.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await Qa()}catch(e){throw _t(pa,a,"onError",Re.MISSING_MFA_CREDENTIALS),e}return new Promise(((n,i)=>{Jt(!0);let o={onSuccess:e=>{_t(pa,a,"onSuccess",{method:"user-passcode",wallet:e}),n(e)},onFailure:e=>{_t(pa,a,"onError",Re.USER_EXITED_SET_PASSWORD_FLOW),i(e)},callAuthOnSuccessOnClose:!1},s="user-passcode"===r.recoveryMethod,l=Qe({walletAction:"update",availableRecoveryMethods:Yt.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:d}=C(r);ea({setWalletPassword:o,recoverWallet:{entropyId:c,entropyIdVerifier:d,onFailure:i},createWallet:o,connectWallet:{onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,entropyIdVerifier:d,onFailure:e=>{_t(pa,a,"onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s}}),Aa(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function tr({appId:e,action:t}){let a=await ja();if("link"===t&&!a)throw _t(pa,"linkAccount","onError",Re.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new be("User must be authenticated before linking an account.");if("login"===t&&a)throw _t(pa,"login","onError",Re.UNKNOWN_AUTH_ERROR),new be("Attempted to log in, but user is already logged in. Use a `link` helper instead.");ya.current=`privy:${e}`,ga.current=t;let r=at();return v.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(a,n)=>{let{name:i,logoUrl:o}=await ze({api:v.api,providerAppId:e,requesterAppId:Yt.id});ea({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:r,onSuccess:a,onError:n}}),_a(wt.CROSS_APP_AUTH_SCREEN)}))}let ar={ready:B,authenticated:z,user:re,walletConnectors:v.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),ea({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress}}),Aa(z?wt.CONNECT_ONLY_AUTHENTICATED_SCREEN:wt.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:()=>{xa("siwe"),ya.current="siwe",ga.current="link",Aa(wt.LINK_WALLET_SCREEN)},startCrossAppAuthFlow:tr,linkEmail:()=>{xa("email"),Za("email"),ya.current="email",ga.current="link",Aa(wt.LINK_EMAIL_SCREEN)},linkPhone:()=>{xa("sms"),Za("phone"),ya.current="sms",ga.current="link",Aa(wt.LINK_PHONE_SCREEN)},linkGoogle:async()=>{xa("google"),Za("google_oauth"),ga.current="link",await rr.initLoginWithOAuth("google")},linkTwitter:async()=>{xa("twitter"),Za("twitter_oauth"),ga.current="link",await rr.initLoginWithOAuth("twitter")},linkDiscord:async()=>{xa("discord"),Za("discord_oauth"),ga.current="link",await rr.initLoginWithOAuth("discord")},linkGithub:async()=>{xa("github"),Za("github_oauth"),ga.current="link",await rr.initLoginWithOAuth("github")},linkSpotify:async()=>{xa("spotify"),Za("spotify_oauth"),ga.current="link",await rr.initLoginWithOAuth("spotify")},linkInstagram:async()=>{xa("instagram"),Za("instagram_oauth"),ga.current="link",await rr.initLoginWithOAuth("instagram")},linkTiktok:async()=>{xa("tiktok"),Za("tiktok_oauth"),ga.current="link",await rr.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{xa("linkedin"),Za("linkedin_oauth"),ga.current="link",await rr.initLoginWithOAuth("linkedin")},linkApple:async()=>{xa("apple"),Za("apple_oauth"),ga.current="link",await rr.initLoginWithOAuth("apple")},linkPasskey:async()=>{xa("passkey"),Za("passkey"),await rr.initLinkWithPasskey(),Aa(wt.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if(xa("telegram"),Za("telegram"),ga.current="link",ya.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new E;v.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=A(e.launchParams.initDataRaw),ea({telegramAuthModalData:{seamlessAuth:!0}}),_a(wt.TELEGRAM_AUTH_SCREEN)}else _t(pa,"linkAccount","onError",Re.INVALID_DATA,{linkMethod:"telegram"});else await rr.initLoginWithTelegram();Aa(wt.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{xa("farcaster"),Za("farcaster"),await rr.initLoginWithFarcaster(),ga.current="link",ya.current="farcaster",Aa(wt.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(xa("email"),!re?.email)throw new be("User does not have an email linked to their account.");ga.current="update",ya.current="email",Aa(wt.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(xa("sms"),!re?.phone)throw new be("User does not have a phone number linked to their account.");ga.current="update",ya.current="sms",Aa(wt.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(!B){let e=await new Promise((e=>{aa((t=>e.bind(t)))}));if(aa(null),e)return void console.warn(t)}!re||re.isGuest?(ga.current="login",ea({login:e}),_a(wt.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{B||(await new Promise((e=>{aa((()=>e))})),aa(null)),z?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(ga.current="login",_a(wt.CONNECT_OR_CREATE))},logout:async()=>{if(ga.current=null,ya.current=null,re&&v.clearProviderAcccessTokens(re),St(null),await v.logout(),re&&qt)try{await qt.clearMfa({userId:re.id})}catch(e){}ie(null),G(!1),_t(pa,"logout","onSuccess"),j(!1),Z.del(K),Z.del(q(Yt.id))},getAccessToken:()=>v.getCustomerAccessToken(),unlinkWallet:async e=>{let t;return ie(t=e.startsWith("0x")?await v.unlinkEthereumWallet(e):await v.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await v.unlinkEmail(e);return ie(t),t},unlinkPhone:async e=>{let t=await v.unlinkPhone(e);return ie(t),t},unlinkGoogle:async e=>{let t=await v.unlinkOAuth("google",e);return ie(t),t},unlinkTwitter:async e=>{let t=await v.unlinkOAuth("twitter",e);return ie(t),t},unlinkDiscord:async e=>{let t=await v.unlinkOAuth("discord",e);return ie(t),t},unlinkGithub:async e=>{let t=await v.unlinkOAuth("github",e);return ie(t),t},unlinkSpotify:async e=>{let t=await v.unlinkOAuth("spotify",e);return ie(t),t},unlinkInstagram:async e=>{let t=await v.unlinkOAuth("instagram",e);return ie(t),t},unlinkTiktok:async e=>{let t=await v.unlinkOAuth("tiktok",e);return ie(t),t},unlinkLinkedIn:async e=>{let t=await v.unlinkOAuth("linkedin",e);return ie(t),t},unlinkApple:async e=>{let t=await v.unlinkOAuth("apple",e);return ie(t),t},unlinkFarcaster:async e=>{let t=await v.unlinkFarcaster(e);return ie(t),t},unlinkTelegram:async e=>{let t=await v.unlinkTelegram(e);return ie(t),t},unlinkPasskey:async e=>{let t=await ja();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!qt)throw Error("Wallet proxy not initialized.");let a=Yt.passkeys.shouldUnenrollMfaOnUnlink;await qt.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:a});let r=await v.getAuthenticatedUser();return ie(r),r},unlinkCrossAppAccount:async({subject:e})=>{let t=re?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new be("Invalid subject");v.storeProviderAccessToken(t.id,null);let a=await v.unlinkOAuth(`privy:${t.id}`,e);return ie(a),a},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await rr.refreshSessionAndUser();if(!t)throw _t(pa,"createWallet","onError",Re.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return Ka(t,15e3,e)},setWalletRecovery:async e=>er({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>er({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(a,r)=>{let{requesterAppId:n}=t?.uiOptions||{},i=e.message;if(!z||!re)return _t(pa,"signMessage","onError",Re.MUST_BE_AUTHENTICATED),void r(Error("User must be authenticated before signing with a Privy wallet"));let o=t?.address??U(re)?.address;if(!o)throw new be("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=P(re,o);if(!s||!l)return _t(pa,"signMessage","onError",Re.EMBEDDED_WALLET_NOT_FOUND),void r(Error("Must have a Privy wallet before signing"));if("string"!=typeof i||i.length<1)return _t(pa,"signMessage","onError",Re.INVALID_MESSAGE),void r(Error("Message must be a non-empty string"));Jt(!0);let c=async()=>{if(!z)throw Error("User must be authenticated before signing with a Privy wallet");let e=await ja();if(!qt||!e||!await rr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");v.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:s.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:a}=C(l),{response:r}=await qt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:n,request:{method:"personal_sign",params:[i,s.address]}}),o=r.data;return v.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:s.address,requesterAppId:n}}),o};if(Ea({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();_t(pa,"signMessage","onSuccess",{signature:e}),a({signature:e})}catch(e){_t(pa,"signMessage","onError",Re.UNABLE_TO_SIGN),r(e??new me("Unable to sign message"))}else{let e={method:"personal_sign",data:i,confirmAndSign:c,onSuccess:e=>{_t(pa,"signMessage","onSuccess",{signature:e}),a({signature:e})},onFailure:e=>{_t(pa,"signMessage","onError",Re.UNABLE_TO_SIGN),r(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:o}=C(l);ea({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:o,onCompleteNavigateTo:wt.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{_t(pa,"signMessage","onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),r(e)}}}),Aa(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t)=>new Promise((async(a,r)=>{let{requesterAppId:n}=t?.uiOptions||{};if(!z||!re)return _t(pa,"signTypedData","onError",Re.MUST_BE_AUTHENTICATED),void r(Error("User must be authenticated before signing with a Privy wallet"));let i=t?.address??U(re)?.address;if(!i)throw new be("User must have an embedded wallet to sign a message.");let{signingWallet:o,rootWallet:s}=P(re,i);if(!s||!o)return _t(pa,"signTypedData","onError",Re.EMBEDDED_WALLET_NOT_FOUND),void r(Error("Must have a Privy wallet before signing"));Jt(!0);let l=te(e),c=async()=>{if(!z)throw Error("User must be authenticated before signing with a Privy wallet");let e=await ja();if(!qt||!e||!await rr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");v.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:o.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:a}=C(s),{response:r}=await qt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:o.walletIndex??0,requesterAppId:n,request:{method:"eth_signTypedData_v4",params:[o.address,l]}}),i=r.data;return v.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:o.address,requesterAppId:n}}),i};if(Ea({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();_t(pa,"signTypedData","onSuccess",{signature:e}),a({signature:e})}catch(e){_t(pa,"signTypedData","onError",Re.UNABLE_TO_SIGN),r(e??new me("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:l,confirmAndSign:c,onSuccess:e=>{_t(pa,"signTypedData","onSuccess",{signature:e}),a({signature:e})},onFailure:e=>{_t(pa,"signTypedData","onError",Re.UNABLE_TO_SIGN),r(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:i}=C(s);ea({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:i,onCompleteNavigateTo:wt.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{_t(pa,"signMessage","onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),r(e)}}}),Aa(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t)=>await Ya({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await Ya({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,a)=>{if(!z||!re)return void a(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let r=e?.address??U(re)?.address;if(!r)return void a(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}=P(re,r);if(!n||!i)return void a(Error("Must have a Privy wallet before exporting"));Jt(!0);let{entropyId:o,entropyIdVerifier:s}=C(i),l={entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:wt.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:a,shouldForceMFA:!0};ea(Zt),await ja()&&qt?qt?(ea({keyExport:{appId:T.appId,appClientId:T.clientId,origin:v.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:a},connectWallet:l}),Aa(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)):a(Error("Must have a Privy wallet before exporting")):a(Error("Must have valid access token to enroll in MFA"))})),promptMfa:Qa,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 be("Invalid MFA code");ua.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{ha.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new be("Invalid authenticator response");let a=await import("@simplewebauthn/browser"),r=ct(await a.startAuthentication(t));ua.current?.resolve({mfaMethod:e,mfaCode:r,relyingParty:window.origin}),await new Promise(((e,t)=>{ha.current={resolve:e,reject:t}}));break;default:throw ua.current?.reject(new be("Unsupported MFA method")),new be(`Unsupported MFA method: ${e}`)}},cancel(){ua.current?.reject(new be("MFA canceled"))},async initEnrollmentWithSms(e){let t=await ja();if(!t||!qt)throw Error("Must have valid access token to enroll in MFA");await qt.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,a)=>{if(!e)return rr.closePrivyModal(),void t();Yt.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."),ea({mfaEnrollmentFlow:{mfaMethods:Yt.mfa.methods,shouldUnlinkOnUnenrollMfa:Yt.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:a}}),Aa(wt.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await ja();if(!e||!qt)throw Error("Must have valid access token to enroll in MFA");let t=await qt.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await ja();if(!t||!qt)throw Error("Must have valid access token to enroll in MFA");await qt.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),ie(await v.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await ja();if(!t||!qt)throw Error("Must have valid access token to enroll in MFA");await qt.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),ie(await v.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let a=await ja();if(!a||!qt)throw Error("Must have valid access token to enroll in MFA");await qt.submitEnrollMfa({method:"passkey",accessToken:a,credentialIds:e,removeForLogin:t.removeForLogin}),ie(await v.getAuthenticatedUser())},async unenroll(e,t={}){let a=await ja();if(!a||!qt)throw Error("Must have valid access token to remove MFA");"passkey"===e?await qt.submitEnrollMfa({method:"passkey",accessToken:a,credentialIds:[],removeForLogin:t.removeForLogin}):await qt.unenrollMfa({method:e,accessToken:a}),ie(await v.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await ja(),t=re?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!qt||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!re?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await rr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let a=await qt.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===a.status&&ie(await v.getAuthenticatedUser()||re||null),ea({farcasterSigner:a}),Aa(wt.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await ja(),a=re?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!qt||!a)throw Error("Must have an embedded wallet to use Farcaster signers");if(!re?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await rr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!re.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=re.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await ja(),a=re?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!qt||!a)throw Error("Must have an embedded wallet to use Farcaster signers");if(!re?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await rr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!re.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let r=await import("@simplewebauthn/browser"),n=await qt.signFarcasterMessage({address:a.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:r.bufferToBase64URLString(e)},fid:BigInt(re.farcaster.fid),relyingParty:window.origin});return new Uint8Array(r.base64URLStringToBuffer(n.signature))},createGuestAccount:async()=>{if(re&&!re.isGuest)throw Error("User cannot already be authenticated to create a guest account");return re?.isGuest?re:rr.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:a}){let r=re?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return qe({user:re,client:v,address:t,requesterAppId:Yt.id,request:{method:r?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:a},reconnect:tr})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:a}){let r=re?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),n=te(e);return qe({user:re,client:v,address:t,requesterAppId:Yt.id,request:{method:r?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,n],chainId:a},reconnect:tr})},sendTransactionWithCrossAppWallet(e,{address:t}){let a=re?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return qe({user:re,client:v,address:t,requesterAppId:Yt.id,request:{method:a?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:tr})},isModalOpen:x,mfaMethods:Yt.mfa.methods};Sa=ar.signMessage,Ra=ar.signTypedData,Ma=async(e,t)=>await Ya({transaction:e,...t,signOnly:!1}),Da=async(e,t)=>({signature:(await Ya({transaction:e,...t,signOnly:!0})).hash});let rr={setAuthenticated:G,setUser:ie,isNewUserThisSession:Se,pendingTransaction:null,walletConnectionStatus:Mt,connectors:v.connectors?.walletConnectors??[],solanaWallets:ue,rpcConfig:Yt.rpcConfig,chains:Yt.chains,appId:T.appId,showFiatPrices:"native-token"!==Yt.embeddedWallets.priceDisplay.primary,clientAnalyticsId:v.clientAnalyticsId,customAuthStatus:ca,hideWalletUIs:fa,emailOtpState:xt,setEmailOtpState:jt,smsOtpState:Bt,setSmsOtpState:Vt,oAuthState:zt,setOAuthState:Gt,siweState:Ht,setSiweState:Kt,isHeadlessOAuthLoading:Rt,nativeTokenSymbolForChainId:e=>Yt.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(qt)return qt;let t=new Promise((e=>{na((()=>t=>e(t)))})),a=new Promise((t=>setTimeout((()=>t(null)),e))),r=await Promise.race([t,a]);return na(null),r},getAuthFlow:()=>v.authFlow,getAuthMeta:()=>v.authFlow?.meta,client:v,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,a=B&&z&&re;a&&ya.current&&(t=Ja(re)),"login"===ga.current?e.shouldCallAuthOnSuccess&&a&&ya.current?_t(pa,"login","onComplete",{user:re,isNewUser:Se,wasAlreadyAuthenticated:!1,loginMethod:ya.current,loginAccount:t??null}):_t(pa,"login","onError",Re.USER_EXITED_AUTH_FLOW):"link"===ga.current&&t?e.isSuccess&&a&&ya.current?_t(pa,"linkAccount","onSuccess",{user:re,linkMethod:ya.current,linkedAccount:t}):ya.current&&_t(pa,"linkAccount","onError",Re.USER_EXITED_LINK_FLOW,{linkMethod:ya.current}):"update"===ga.current&&t&&(e.isSuccess&&a&&ya.current?_t(pa,"update","onSuccess",{user:re,updateMethod:ya.current,updatedAccount:t}):ya.current&&_t(pa,"update","onError",Re.USER_EXITED_UPDATE_FLOW,{linkMethod:ya.current}));let r=Ot&&Je.includes(Ot),n=Ot===wt.ERROR_SCREEN&&Zt.errorModalData&&Je.includes(Zt.errorModalData.previousScreen);if((r||n)&&Zt.funding){let e,t=Ze[Ot]??null;if("solana"===Zt.funding.chainType){let a=I(ht);if(!a)return void console.warn("Unable to load solana plugin, skipping balance");try{e=BigInt(await a.getBalance({address:Zt.funding.address,cluster:Zt.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}_t(pa,"fundSolanaWallet","onUserExited",{address:Zt.funding.address,cluster:Zt.funding.cluster,fundingMethod:t,balance:e})}else{let a=gt(Zt.funding.chain.id,Yt.chains,Yt.rpcConfig,{appId:T.appId});try{e=await a.getBalance({address:Zt.funding.address})}catch{console.error("Unable to pull wallet balance")}_t(pa,"fundWallet","onUserExited",{address:Zt.funding.address,chain:Zt.funding.chain,fundingMethod:t,balance:e})}}ea({...Zt,externalConnectWallet:{suggestedAddress:void 0}}),ga.current=null,ya.current=null,dt(!1),j(!1),setTimeout((()=>{v.authFlow=void 0}),200),v.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:({message:e,address:t})=>new Promise((async(a,r)=>{if(!z||!re)return _t(pa,"signMessage","onError",Re.MUST_BE_AUTHENTICATED),void r(Error("User must be authenticated before signing with a Privy wallet"));let n=t??R(re)?.address;if(!n)throw new be("User must have an embedded wallet to sign a message.");let{signingWallet:i,rootWallet:o}=M(re,n);if(!i||!o)return _t(pa,"signMessage","onError",Re.EMBEDDED_WALLET_NOT_FOUND),void r(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return _t(pa,"signMessage","onError",Re.INVALID_MESSAGE),void r(Error("Message must be a non-empty string"));Jt(!0);let s=async()=>{if(!z)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 a=rr.walletProxy??await rr.initializeWalletProxy(15e3);if(!a)throw Error("Failed to initialize embedded wallet proxy.");if(!await rr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!o)throw Error("No root wallet for signing wallet found");let{entropyId:r,entropyIdVerifier:n}=C(o),{response:s}=await a.rpc({accessToken:t,entropyId:r,entropyIdVerifier:n,chainType:"solana",hdWalletIndex:i.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return s.data.signature};if(Ea({showWalletUIs:void 0}))try{let e=await s();a({signature:e})}catch(e){r(e)}else{let{entropyId:t,entropyIdVerifier:n}=C(o);ea({signMessage:{method:"solana_signMessage",data:e,confirmAndSign:s,onSuccess:e=>{a({signature:e})},onFailure:e=>{r(e)},uiOptions:{}},connectWallet:{entropyId:t,entropyIdVerifier:n,onCompleteNavigateTo:wt.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{_t(pa,"signMessage","onError",Re.UNKNOWN_CONNECT_WALLET_ERROR),r(e)}}}),_a(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:a,transactionOptions:r,fundWalletConfig:n,address:i})=>{let o=i?Ee.find((e=>e.address===i)):Ee.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw _t(pa,"sendSolanaTransaction","onError",Re.EMBEDDED_WALLET_NOT_FOUND),new be("Embedded wallet not found",Re.EMBEDDED_WALLET_NOT_FOUND);return await Xa({transaction:e,connection:t,transactionOptions:r,uiOptions:a,fundWalletConfig:n,wallet:o})},openPrivyModal:Aa,connectWallet:ka,initLoginWithWallet:async(e,t,a)=>{ye(e)?(ya.current="siwe",Wa(e,t,a)):(ya.current="siws",Na(e,t,a))},loginWithWallet:async()=>{let e,t,a;if(!B)throw new De;if(v.authFlow instanceof m?e="siwe":v.authFlow instanceof y&&(e="siws"),!e)throw new be("Must initialize SIWE/SIWS flow first.");if(null!==await v.getAccessToken())try{({user:t}=await v.link()),ya.current=e}catch(t){throw _t(pa,"linkAccount","onError",t.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:a}=await v.authenticate()),ya.current=e}catch(e){throw _t(pa,"login","onError",e.privyErrorCode||Re.GENERIC_CONNECT_WALLET_ERROR),e}ie(t||re||null),dt(a||!1),G(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:a})=>new Promise((async(r,n)=>{let i=await ja();if(!z||!re||!i)throw new be("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new be("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=rr.walletProxy??await rr.initializeWalletProxy(15e3);if(!o)throw new be("Wallet proxy not initialized.");if(ve({address:e,chainType:t,user:re}))return r();let s=Ce({address:e,user:re}),l=Ie({address:e,user:re}),c=async()=>{await o.createDelegatedAction({accessToken:i,rootWallet:l,delegatedWallets:[s]}),await rr.refreshSessionAndUser()};if(!a){try{await c(),r()}catch(e){n(e)}return}await rr.recoverPrimaryWallet(),ea({delegatedActions:{consent:{address:e,onDelegate:c,onSuccess:async()=>{r()},onError:async e=>{n(e)}}}}),Aa(wt.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,a)=>{if(!z||!re)throw new be("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===ke(re).length)throw new be("User has no delegated wallets to revoke.");let r=async()=>{await v.revokeDelegatedWallet(),await rr.refreshSessionAndUser()};if(e)ea({delegatedActions:{revoke:{onRevoke:r,onSuccess:async()=>{t()},onError:async e=>{a(e)}}}}),Aa(wt.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN);else try{await r(),t()}catch(e){a(e)}})),initLoginWithFarcaster:async(e,t)=>{let a=new h(e,t);v.startAuthFlow(a);try{ya.current="farcaster",await a.initializeFarcasterConnect()}catch(e){throw"login"===ga.current?_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR):"link"===ga.current&&_t(pa,"linkAccount","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!B)throw new De;if(!(v.authFlow instanceof h))throw new be("Must initialize Farcaster flow first.");if(null!==await v.getAccessToken())try{({user:e}=await v.link()),ya.current="farcaster"}catch(e){throw _t(pa,"linkAccount","onError",e.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await v.authenticate()),ya.current="farcaster"}catch(e){throw _t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}ie(e||null),dt(t||!1),G(!0)},async loginWithGuestAccountFlow(){let e=new p(this.appId);v.startAuthFlow(e);try{ga.current="login",ya.current="guest";let{user:e,isNewUser:t}=await v.authenticate();if(t=t||!1,!e)throw new be("Unable to authenticate guest account");if(S(e,Yt.embeddedWallets.createOnLogin))try{await Ka(e,15e3),e=await rr.refreshSessionAndUser()}catch(t){ie(e),console.warn("Unable to create embedded wallet for guest account")}else ie(e);return dt(t),G(!0),_t(pa,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw _t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:a}){let r=`privy:${e}`;ya.current=r;let{url:n,stateCode:i,codeVerifier:o}=await He({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 be("No authorization URL returned for cross-app auth.");try{let s=await Ge({url:n,popup:t,provider:r}),l=s.stateCode,c=s.authorizationCode;if(l!==i)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:r,storedStateCode:i??"",returnedStateCode:l??""}}),new be("Unexpected auth flow. This may be a phishing attempt.",void 0,Re.OAUTH_UNEXPECTED);let d=await Ke({appId:e,codeVerifier:o,stateCode:l,authorizationCode:c,action:a,client:v});d&&v.storeProviderAccessToken(e,d);let u=await rr.refreshSessionAndUser();if(!u)throw new be("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:r}}),e}},async initLoginWithOAuth(e,t,a){if(ya.current=e,!ee())return void _a(wt.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&tt(window.navigator.userAgent))return void _a(wt.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:je},"*"),Z.del($),Z.del(Y);let r=new bt({provider:e,disableSignup:!!a,withPrivyUi:!0});t&&r.addCaptchaToken(t),v.startAuthFlow(r);let n=await v.authFlow.getAuthorizationUrl();n&&n.url&&("twitter"===e&&s&&(n.url=n.url.replace("x.com","twitter.com")),window.location.assign(n.url))},async initLoginWithTelegram(e,t){if(!B)throw new De;ya.current="telegram";let a=new E(e,t);v.startAuthFlow(a),a.meta.telegramWebAppData=void 0,a.meta.telegramAuthResult=await new Promise(((e,t)=>Yt.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Yt.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(a=>a?e(a):t(new be("Telegram auth failed or was canceled by the client")))):t(new be("Telegram was not initialized")):t(new be("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,a;if(!(v.authFlow instanceof E))throw new be("Must initialize Telegram flow before calling loginWithTelegram");if(v.authFlow.meta.captchaToken||=e,"login"===ga.current)try{let e=await v.authenticate();t=e.user,a=e.isNewUser,ya.current="telegram"}catch(e){throw _t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}else{if("link"!==ga.current)throw new be("Unknown auth intent");try{t=(await v.link()).user,ya.current="telegram"}catch(e){throw _t(pa,"linkAccount","onError",e.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}ie(t),dt(a||!1),G(!0)},async recoveryOAuthFlow(e,t,a){let r,n;function i(t){if(!t)throw v.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new be("Recovery OAuth failed")}switch(e){case"google-drive":{let t,o,{url:s,codeVerifier:l,stateCode:c}=await $e({api:Oa.api,provider:e});i(s);try{let r=await rt({url:s,popup:a,provider:e});if(t=r.stateCode,o=r.authorizationCode,t!==c)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:c??"",returnedStateCode:t??""}}),new be("Unexpected auth flow. This may be a phishing attempt.",void 0,Re.OAUTH_UNEXPECTED)}catch(t){throw v.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new be("Recovery OAuth failed")}[r,n]=await Promise.all([ja(),Ye({api:Oa.api,provider:e,codeVerifier:l,stateCode:t,authorizationCode:o})]);break}case"icloud":{let{url:t}=await $e({api:Oa.api,provider:e});i(t);let{ckWebAuthToken:o}=await rt({url:t,popup:a,provider:e});n=o,r=await ja()}}if(!qt)throw new be("Cannot connect to wallet proxy");if(!r)throw new be("Unable to authorize user");switch(t){case"recover":{let t=Zt.recoverWallet?.entropyId,a=Zt.recoverWallet?.entropyIdVerifier;if(!t||!a)throw new be("Recovery OAuth failed");v.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await qt.recover({accessToken:r,entropyId:t,entropyIdVerifier:a,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 qt.create({accessToken:r,recoveryAccessToken:n,recoveryMethod:e});let t=U(await rr.refreshSessionAndUser());if(!t)throw _t(pa,"createWallet","onError",Re.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");v.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),_t(pa,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=N(re);if(!t)throw _t(pa,"setWalletRecovery","onError",Re.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:a,entropyIdVerifier:i}=C(t);await qt.setRecovery({accessToken:r,entropyId:a,entropyIdVerifier:i,recoveryMethod:e,recoveryAccessToken:n});let o=N(await rr.refreshSessionAndUser());if(!o)throw _t(pa,"createWallet","onError",Re.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}}),_t(pa,"setWalletRecovery","onSuccess",{method:e,wallet:o});break}default:throw new be("Unsupported recovery action")}},async loginWithOAuth(e){let t,a,r;if(!(v.authFlow instanceof bt))throw new be("Must initialize OAuth flow before calling loginWithOAuth");let n=Z.get(X),i=v.authFlow.meta.stateCode;if(n!==i)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:n??"",returnedStateCode:i??""}}),new be("Unexpected auth flow. This may be a phishing attempt.",void 0,Re.OAUTH_UNEXPECTED);if(null!==await v.getAccessToken())try{let a=await v.link();t=a.user,r=a.oAuthTokens,ya.current=e}catch(t){throw _t(pa,"linkAccount","onError",t.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let n=await v.authenticate();t=n.user,a=n.isNewUser,r=n.oAuthTokens,ya.current=e}catch(t){throw"login"===ga.current?_t(pa,"login","onError",t.privyErrorCode||Re.UNKNOWN_AUTH_ERROR):"link"===ga.current&&_t(pa,"linkAccount","onError",t.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return ie(t),dt(a||!1),G(!0),r&&t&&_t(pa,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:r,user:t}),r},passkeyAuthState:Lt,setPasskeyAuthState:Ft,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let a=new w({captchaToken:e,setPasskeyAuthState:Ft});v.startAuthFlow(a),ga.current="login";try{ya.current="passkey",Ft({status:"generating-challenge"}),await a.initRegisterFlow(t),Ft({status:"awaiting-passkey"})}catch(e){throw Ft({status:"error",error:e}),_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!B)throw new De;if(!(v.authFlow instanceof w))throw new be("Must initialize Passkey flow first.");if("passkey"!==ya.current){let e=new be("Must init login with Passkey flow first.");throw Ft({status:"error",error:e}),e}let a=await ja();try{ya.current="passkey",Ft({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await v.authenticate())}catch(e){throw Ft({status:"error",error:e}),_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}ie(e),dt(t||!1),G(!0),Ft({status:"done"});let r=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!a,loginAccount:r}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let a=new w({captchaToken:e,setPasskeyAuthState:Ft});v.startAuthFlow(a),ga.current="login";try{ya.current="passkey",Ft({status:"generating-challenge"}),await a.initAuthenticationFlow(t),Ft({status:"awaiting-passkey"})}catch(e){throw Ft({status:"error",error:e}),_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(){let e,t;if(!B)throw new De;if(!(v.authFlow instanceof w))throw new be("Must initialize Passkey flow first.");if("passkey"!==ya.current){let e=new be("Must init login with Passkey flow first.");throw Ft({status:"error",error:e}),e}let a=await ja();try{ya.current="passkey",Ft({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await v.authenticate())}catch(e){throw Ft({status:"error",error:e}),_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}ie(e),dt(t||!1),G(!0),Ft({status:"done"});let r=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!a,loginAccount:r}},async initLinkWithPasskey(e){let t=new w({captchaToken:e});v.startAuthFlow(t),ga.current="link",ya.current="passkey",Ft({status:"generating-challenge"});try{await t.initLinkFlow(),Ft({status:"awaiting-passkey"})}catch(e){throw _t(pa,"linkAccount","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),Ft({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!B)throw new De;if(!(v.authFlow instanceof w))throw new be("Must initialize Passkey flow first.");if("passkey"!==ya.current)throw new be("Must init login with Passkey flow first.");try{ya.current="passkey",({user:e}=await v.link())}catch(e){throw _t(pa,"linkAccount","onError",e.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return ie(e||re||null),Ft({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,a){if(!ee())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&&tt(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 r=new bt({provider:e,withPrivyUi:!1,disableSignup:a??!1});t&&r.addCaptchaToken(t),Gt({status:"loading"});let n=await v.startAuthFlow(r).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,a,r;Dt(!0),Gt({status:"loading"}),v.startAuthFlow(new bt(e));let n=Z.get(X),i=e.stateCode;if(n!==i)throw v.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:n??"",returnedStateCode:i??""}}),Dt(!1),new be("Unexpected auth flow. This may be a phishing attempt.",void 0,Re.OAUTH_UNEXPECTED);if(null!==await v.getAccessToken())try{({user:t,oAuthTokens:r}=await v.link()),ya.current=e.provider;let a=Ja(t);t&&a&&_t(pa,"linkAccount","onSuccess",{user:t,linkMethod:ya.current,linkedAccount:a})}catch(t){throw Dt(!1),_t(pa,"linkAccount","onError",t.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:a,oAuthTokens:r}=await v.authenticate()),ya.current=e.provider;let n=Ja(t);t&&n&&void 0!==a&&_t(pa,"login","onComplete",{user:t,isNewUser:a,wasAlreadyAuthenticated:!1,loginMethod:ya.current,loginAccount:n})}catch(e){throw Dt(!1),Gt({status:"error",error:e}),_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}return ie(t),dt(a||!1),G(!0),Dt(!1),Gt({status:"done"}),r&&t&&_t(pa,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:r,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:a,withPrivyUi:r})=>{let n=new u({email:e,captchaToken:t,disableSignup:a});v.startAuthFlow(n);try{ya.current="email",jt({status:"sending-code"}),await n.sendCodeEmail({withPrivyUi:r}),jt({status:"awaiting-code-input"})}catch(e){throw jt({status:"error",error:e}),"login"===ga.current?_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR):"link"===ga.current&&_t(pa,"linkAccount","onError",e.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,a)=>{let r=new d(e,t,a);v.startAuthFlow(r);try{await r.sendCodeEmail({withPrivyUi:!0})}catch(e){_t(pa,"update","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR,{linkMethod:ya.current})}},initUpdatePhone:async(e,t,a)=>{let r=new g(e,t,a);v.startAuthFlow(r);try{await r.sendSmsCode({withPrivyUi:!0})}catch(e){_t(pa,"update","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR,{linkMethod:ya.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:a,withPrivyUi:r})=>{Vt({status:"sending-code"});let n=new f({phoneNumber:e,captchaToken:t,disableSignup:a});v.startAuthFlow(n);try{ya.current="sms",await n.sendSmsCode({withPrivyUi:r}),Vt({status:"awaiting-code-input"})}catch(e){throw Vt({status:"error",error:e}),"login"===ga.current?_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR):"link"===ga.current&&_t(pa,"linkAccount","onError",e.privyErrorCode||Re.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,a;function r(e){v.authFlow instanceof u?jt(e):v.authFlow instanceof f&&Vt(e)}if(r({status:"submitting-code"}),!B){let e=new De;throw r({status:"error",error:e}),e}if(v.authFlow instanceof u)v.authFlow.meta.emailCode=e.trim();else{if(!(v.authFlow instanceof f)){let e=new be("Must initialize a passwordless code flow first");throw r({status:"error",error:e}),e}v.authFlow.meta.smsCode=e.trim()}let n=await ja();if("link"===ga.current)try{({user:t}=await v.link())}catch(e){throw r({status:"error",error:e}),_t(pa,"linkAccount","onError",e.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:ya.current}),e}else if("update"===ga.current)try{({user:t}=await v.link())}catch(e){throw r({status:"error",error:e}),_t(pa,"update","onError",e.privyErrorCode||Re.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:ya.current}),e}else try{({user:t,isNewUser:a}=await v.authenticate())}catch(e){throw r({status:"error",error:e}),_t(pa,"login","onError",e.privyErrorCode||Re.UNKNOWN_AUTH_ERROR),e}let i=t||re;ie(i||null),dt(a||!1),G(!0),r({status:"done"});let o=null;return v.authFlow instanceof u?o=i?.linkedAccounts.find((({type:e})=>"email"===e))||null:v.authFlow instanceof f&&(o=i?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:i,isNewUser:a||!1,wasAlreadyAuthenticated:!!n,linkedAccount:o}},generateSiweMessage:async({address:e,chainId:t,captchaToken:a})=>{ga.current="link",ya.current="siwe",Kt({status:"generating-message"});let r=await v.generateSiweNonce({address:e,captchaToken:a});return Kt({status:"awaiting-signature"}),nt({address:e,chainId:t.replace("eip155:",""),nonce:r})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let a=await v.generateSiweNonce({address:e});return nt({address:e,chainId:t.replace("eip155:",""),nonce:a})},linkSmartWallet:async({message:e,signature:t,smartWalletType:a})=>{let r;r=await v.linkSmartWallet({message:e,signature:t,smartWalletType:a}),ie((r=await rr.refreshSessionAndUser()??r)||re||null)},linkWithSiwe:async({message:e,signature:t,chainId:a,walletClientType:r,connectorType:n})=>{let i;xa("siwe");let o=null;try{Kt({status:"submitting-signature"}),i=await v.linkWithSiwe({message:e,signature:t,chainId:a,walletClientType:r,connectorType:n}),i=await rr.refreshSessionAndUser()??i,Kt({status:"done"}),(o=Ja(i)||null)&&_t(pa,"linkAccount","onSuccess",{user:i,linkMethod:"siwe",linkedAccount:o})}catch(e){throw _t(pa,"linkAccount","onError",e.privyErrorCode||Re.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),ga.current=null,ya.current=null,Kt({status:"error",error:e}),e}let s=i||re;return ie(s||null),ga.current=null,ya.current=null,{user:s,linkedAccount:o}},refreshSessionAndUser:async()=>{let e=await v.getAuthenticatedUser();return G(!!e),ie(e),e},walletProxy:qt,createAnalyticsEvent:({eventName:e,payload:t,timestamp:a})=>v.createAnalyticsEvent({eventName:e,payload:t,timestamp:a}),acceptTerms:async()=>{let e=await v.acceptTerms();return ie(e),e},getUsdTokenPrice:e=>v.getUsdTokenPrice(e),getUsdPriceForSol:()=>v.getUsdPriceForSol(),getSplTokenMetadata:e=>v.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,a)=>{let r=N(e?.user??re)||O(e?.user??re)||W(e?.user??re),n=await ja();if(!n||!qt||!r)return void a(Error("Must have valid access token and Privy wallet to recover wallet"));Jt(!0);let{entropyId:i,entropyIdVerifier:o}=C(r);try{await qt.connect({accessToken:n,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){We(e)&&"privy"===r.recoveryMethod?(v.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:r.address}}),(await qt.recover({entropyId:i,entropyIdVerifier:o,accessToken:n})).entropyId||a(Error("Unable to recover wallet")),v.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:r.address}}),t(!0)):We(e)&&"privy"!==r.recoveryMethod?(ea({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:a,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:r.recoveryMethod,action:"recover"}}),Aa(Xe(r.recoveryMethod))):a(e)}})),embeddedSolanaWallets:Ee,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await rr.refreshSessionAndUser();if(!z||!t)throw _t(pa,"createWallet","onError",Re.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,a)=>{let r=U(e),n=R(e),i=a&&"createAdditional"in a&&a.createAdditional,o=a&&"walletIndex"in a?a.walletIndex:void 0,s=(L(e)?.walletIndex??-1)+1;if(n&&!i&&"number"!=typeof o)throw _t(pa,"createWallet","onError",Re.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof o&&o<0)throw _t(pa,"createWallet","onError",Re.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${o}) is invalid.`);let[l,c]=await Promise.all([rr.initializeWalletProxy(t),ja()]);if(!l||!c)throw _t(pa,"createWallet","onError",Re.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await qa({user:e,wp:l,accessToken:c,walletIndex:o??s,ethereumWallet:r})})(t,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,a)=>{if(!z||!re)return void a(Error("User must be authenticated before exporting their Privy wallet"));let r=e?.address??R(re)?.address;if(!r)return void a(Error("User does not have an HD Solana wallet."));let{signingWallet:n,rootWallet:i}=M(re,r);if(!n||!i)return void a(Error("Must have a Privy wallet before exporting"));if(Jt(!0),!await ja()||!qt)return void a(Error("Must have valid access token to enroll in MFA"));if(!qt)return void a(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=C(i);ea({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:wt.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:a,shouldForceMFA:!0},keyExport:{appId:T.appId,appClientId:T.clientId,origin:v.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:a}}),Aa(wt.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{H(!0),ta?.(e)},updateWallets:()=>Ha(),fundWallet:async(e,t)=>{let a=wt.FUNDING_METHOD_SELECTION_SCREEN;ea({funding:Nt({address:e,appConfig:Yt,fundWalletConfig:t,methodScreen:a})}),Aa(a)},openModal:Aa,requestFarcasterSignerStatus:async e=>{let t=await ja(),a=re?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!qt||!a)throw Error("Must have an embedded wallet to use Farcaster signers");if(!re?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let r=await v.requestFarcasterSignerStatus(e);return"approved"===r.status&&ie(await v.getAuthenticatedUser()||re||null),r},connectCoinbaseSmartWallet:async()=>{Yt.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"),ka(e);await Ia("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:a,externalWalletMetadata:r,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await v.sendAccountTransferRequest({nonce:e,account:t,accountType:a,externalWalletMetadata:r,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return ie(l),l}};Pa=rr.recoverPrimaryWallet,La=rr.recoverPrimaryWallet,Fa=rr.solanaSignMessage;let nr=o((()=>({wallets:oe,ready:ia&&wa})),[oe,ia,wa]),ir=v.authFlow instanceof E,or=!Yt.headless&&Yt.captchaEnabled&&!z&&(B||ir);/*#__PURE__*/return e(It.Provider,{value:ar,children:/*#__PURE__*/e(Tt.Provider,{value:pa,children:/*#__PURE__*/e(kt.Provider,{value:nr,children:/*#__PURE__*/e(Et,{...Yt,children:/*#__PURE__*/t(vt.Provider,{value:rr,children:[/*#__PURE__*/e(pt,{children:/*#__PURE__*/t(Ct,{data:Zt,setModalData:ea,setInitialScreen:St,initialScreen:Ot,authenticated:z,open:x,children:[T.children,or&&/*#__PURE__*/e(le,{delayedExecution:!1}),/*#__PURE__*/e(yt,{theme:{...Yt.appearance.palette||{}}}),!Yt.render.standalone&&/*#__PURE__*/e(ce,{open:x})]})}),Qt&&Xt?/*#__PURE__*/e(Te,{appId:T.appId,appClientId:T.clientId,clientAnalyticsId:v.clientAnalyticsId,origin:v.apiUrl,mfaMethods:re?.mfaMethods,mfaPromise:ua,mfaSubmitPromise:ha,onLoad:$t,onLoadFailed:()=>null}):null,Yt.loginConfig.telegramAuthConfiguration&&
3
- /*#__PURE__*/e(mt,{$if:!0,children:/*#__PURE__*/e(de,{scriptHost:T.apiUrl||V,botUsername:Yt.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};export{Ca as C,va as E,$a as P,Na as a,ba as b,ja as c,Ba as d,Va as e,Ha as f,xa as g,Ka as h,za as i,Ga as j,qa as k};