@privy-io/react-auth 2.6.0 → 2.6.1

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 (25) hide show
  1. package/dist/cjs/abstract-smart-wallets.js +1 -1
  2. package/dist/cjs/{importWallet-D3s13-Ir.js → importWallet-CqIkwxB-.js} +1 -1
  3. package/dist/cjs/index.js +4 -4
  4. package/dist/cjs/{prepareFundingModalData-CT2XWfw3.js → prepareFundingModalData-BCNQSbXb.js} +1 -1
  5. package/dist/cjs/{smart-wallets-BggeovZV.js → smart-wallets-BJE1oUqH.js} +1 -1
  6. package/dist/cjs/smart-wallets.js +1 -1
  7. package/dist/cjs/solana.js +1 -1
  8. package/dist/cjs/ui.js +1 -1
  9. package/dist/cjs/{useActiveWallet-mT7IempW.js → useActiveWallet-CLPPplpC.js} +4 -4
  10. package/dist/cjs/{useFundWallet-C1OiqVXT.js → useFundWallet-BLEO3WzQ.js} +1 -1
  11. package/dist/cjs/{useWallets-qEcpULZl.js → useWallets-Dmyb5a0t.js} +1 -1
  12. package/dist/dts/index.d.mts +2 -1
  13. package/dist/dts/index.d.ts +2 -1
  14. package/dist/esm/abstract-smart-wallets.mjs +1 -1
  15. package/dist/esm/{importWallet-Db-TmI57.mjs → importWallet-CJLTGjPg.mjs} +1 -1
  16. package/dist/esm/index.mjs +21 -21
  17. package/dist/esm/{prepareFundingModalData-kNpmfOTp.mjs → prepareFundingModalData-due26ueW.mjs} +1 -1
  18. package/dist/esm/{smart-wallets-BF48FIHR.mjs → smart-wallets-dP5AzE1-.mjs} +1 -1
  19. package/dist/esm/smart-wallets.mjs +1 -1
  20. package/dist/esm/solana.mjs +1 -1
  21. package/dist/esm/ui.mjs +1 -1
  22. package/dist/esm/{useActiveWallet-C89-c9e3.mjs → useActiveWallet-C8nSK6cE.mjs} +3 -3
  23. package/dist/esm/{useFundWallet-DYXHQOzn.mjs → useFundWallet-DR5oafbj.mjs} +1 -1
  24. package/dist/esm/{useWallets-DhD2VeRF.mjs → useWallets-DTpjk5Rk.mjs} +1 -1
  25. package/package.json +2 -2
package/dist/cjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("mipd"),r=require("react"),n=require("react-device-detect"),a=require("viem/utils"),i=require("./internal-context-DV3MljLU.js"),o=require("./paths-BGBZ-6Nl.js"),s=require("./useActiveWallet-mT7IempW.js"),l=require("jose"),c=require("./useWallets-qEcpULZl.js"),d=require("./prepareFundingModalData-CT2XWfw3.js"),u=require("uuid"),h=require("eventemitter3"),p=require("@coinbase/wallet-sdk"),y=require("viem"),m=require("./getPublicClient-hVv5ZSWd.js"),g=require("ofetch"),f=require("js-cookie"),w=require("zustand"),v=require("@marsidev/react-turnstile"),C=require("styled-components"),x=require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),E=require("@heroicons/react/24/outline/ExclamationTriangleIcon"),S=require("@heroicons/react/24/outline/WalletIcon"),T=require("@heroicons/react/24/outline/ExclamationCircleIcon"),A=require("@heroicons/react/24/outline/Square2StackIcon"),b=require("@heroicons/react/24/outline/ArrowTopRightOnSquareIcon"),_=require("@heroicons/react/24/solid/DocumentCheckIcon"),I=require("@heroicons/react/20/solid/CheckIcon"),P=require("@heroicons/react/24/outline/EnvelopeIcon"),j=require("@heroicons/react/24/outline/PhoneIcon"),k=require("@heroicons/react/24/solid/CheckCircleIcon"),N=require("@heroicons/react/24/solid/XCircleIcon"),M=require("@heroicons/react/24/outline/CheckCircleIcon"),R=require("@heroicons/react/24/outline/CloudArrowUpIcon"),O=require("@heroicons/react/24/outline/NoSymbolIcon"),W=require("fast-password-entropy"),L=require("secure-password-utilities"),U=require("secure-password-utilities/wordlists"),F=require("@heroicons/react/24/outline/ArrowPathIcon"),D=require("@heroicons/react/24/outline/EyeIcon"),B=require("@heroicons/react/24/outline/EyeSlashIcon"),H=require("@heroicons/react/24/outline/KeyIcon"),z=require("@heroicons/react/24/outline/ArrowDownTrayIcon"),q=require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),V=require("@heroicons/react/24/outline/DocumentDuplicateIcon"),G=require("@heroicons/react/24/outline/UserCircleIcon"),$=require("@heroicons/react/24/solid/LockClosedIcon"),K=require("@privy-io/js-sdk-core"),Y=require("@headlessui/react"),Z=require("@heroicons/react/24/outline/ChevronDownIcon"),X=require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),Q=require("@heroicons/react/24/outline/CreditCardIcon"),J=require("@heroicons/react/24/outline/QrCodeIcon"),ee=require("@heroicons/react/24/outline/InformationCircleIcon"),te=require("@heroicons/react/24/outline/ChevronRightIcon"),re=require("@heroicons/react/24/outline/FingerPrintIcon"),ne=require("@heroicons/react/24/outline/ClockIcon"),ae=require("@heroicons/react/24/outline/TrashIcon"),ie=require("@heroicons/react/24/solid/CheckBadgeIcon"),oe=require("@heroicons/react/24/outline/ShieldCheckIcon"),se=require("@heroicons/react/24/solid/IdentificationIcon"),le=require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),ce=require("@heroicons/react/24/outline/MinusCircleIcon"),de=require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),ue=require("@heroicons/react/24/solid/ShieldCheckIcon"),he=require("@heroicons/react/24/outline/CalendarIcon"),pe=require("@heroicons/react/24/outline/GlobeAltIcon"),ye=require("@heroicons/react/24/outline/LockClosedIcon"),me=require("@heroicons/react/24/outline/PencilSquareIcon"),ge=require("@heroicons/react/24/outline"),fe=require("@heroicons/react/24/outline/ClipboardDocumentIcon"),we=require("./importWallet-D3s13-Ir.js"),ve=require("viem/experimental"),Ce=require("./getEmbeddedConnectedWallet-DTU4T9TJ.js");function xe(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function Ee(e){if(e&&"object"==typeof e&&"default"in e)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@walletconnect/ethereum-provider"),require("@heroicons/react/24/outline/CheckIcon"),require("qrcode"),require("zustand/shallow"),require("zustand/traditional"),require("tinycolor2");var Se=/*#__PURE__*/xe(r),Te=/*#__PURE__*/Ee(n),Ae=/*#__PURE__*/Ee(l),be=/*#__PURE__*/xe(h),_e=/*#__PURE__*/xe(f),Ie=/*#__PURE__*/xe(x),Pe=/*#__PURE__*/xe(E),je=/*#__PURE__*/xe(S),ke=/*#__PURE__*/xe(T),Ne=/*#__PURE__*/xe(A),Me=/*#__PURE__*/xe(b),Re=/*#__PURE__*/xe(_),Oe=/*#__PURE__*/xe(I),We=/*#__PURE__*/xe(P),Le=/*#__PURE__*/xe(j),Ue=/*#__PURE__*/xe(k),Fe=/*#__PURE__*/xe(N),De=/*#__PURE__*/xe(M),Be=/*#__PURE__*/xe(R),He=/*#__PURE__*/xe(O),ze=/*#__PURE__*/xe(W),qe=/*#__PURE__*/Ee(L),Ve=/*#__PURE__*/xe(F),Ge=/*#__PURE__*/xe(D),$e=/*#__PURE__*/xe(B),Ke=/*#__PURE__*/xe(H),Ye=/*#__PURE__*/xe(z),Ze=/*#__PURE__*/xe(q),Xe=/*#__PURE__*/xe(V),Qe=/*#__PURE__*/xe(G),Je=/*#__PURE__*/xe($),et=/*#__PURE__*/xe(Z),tt=/*#__PURE__*/xe(X),rt=/*#__PURE__*/xe(Q),nt=/*#__PURE__*/xe(J),at=/*#__PURE__*/xe(ee),it=/*#__PURE__*/xe(te),ot=/*#__PURE__*/xe(re),st=/*#__PURE__*/xe(ne),lt=/*#__PURE__*/xe(ae),ct=/*#__PURE__*/xe(ie),dt=/*#__PURE__*/xe(oe),ut=/*#__PURE__*/xe(se),ht=/*#__PURE__*/xe(le),pt=/*#__PURE__*/xe(ce),yt=/*#__PURE__*/xe(de),mt=/*#__PURE__*/xe(ue),gt=/*#__PURE__*/xe(he),ft=/*#__PURE__*/xe(pe),wt=/*#__PURE__*/xe(ye),vt=/*#__PURE__*/xe(me),Ct=/*#__PURE__*/xe(fe);class xt{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.customJwtAccountAuthenticatePath,{token:this.meta.token})}catch(e){throw i.formatApiError(e)}}async link(){throw Error("Unimplemented")}constructor(e){this.meta={token:e}}}function Et(e){return e?{"privy-ui":"t"}:void 0}class St{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new i.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessAuthenticatePath,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new i.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessLinkPath,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw i.formatApiError(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new i.PrivyClientError("Email must be set when initialzing authentication.");let n=Et(r);try{return await this.api.post(o.passwordlessInitPath,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw i.formatApiError(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class Tt extends St{async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new i.PrivyClientError("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(o.updateEmailPath,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw i.formatApiError(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class At{get meta(){return this._meta}async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new i.PrivyClientError("Auth flow must be initialized first");try{let e=await this.api.post(o.farcasterAuthenticatePath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});if(!e)throw new i.PrivyClientError("No response from authentication");return e}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.farcasterLinkPath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw i.formatApiError(e)}}async _startChannelOnce(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");let e=await this.api.post(o.farcasterInitPath,{token:this.captchaToken});n.isMobile&&!n.isIOS&&e.connect_uri&&s.openHref(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new i.PrivyClientError("Auth flow must be initialized first");let e=await this.api.get(o.farcasterStatusPath,{headers:{"farcaster-channel-token":this.meta.channelToken}});return"completed"===e.state&&(this.message=e.message,this.signature=e.signature,this.fid=e.fid,!0)}constructor(e,t=!1){this._meta={disableSignup:!1},this.captchaToken=e,this.startChannelOnce=new s.RunEffectOnce(this._startChannelOnce.bind(this)),this.pollForReady=new s.RunEffectOnce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function bt(e){return crypto.getRandomValues(new Uint8Array(e))}class _t{getOrCreateGuestCredential(e){let t=c.getGuestCredentialStorageKey(e);if(d.e()){if(d.i.get(t))return d.i.get(t);{let e=l.base64url.encode(bt(32));return d.i.put(t,e),e}}return l.base64url.encode(bt(32))}async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.guestAccountAuthenticatePath,{guest_credential:this.meta.guestCredential})}catch(e){throw i.formatApiError(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function It(){return l.base64url.encode(bt(36))}function Pt(){return It()}async function jt(e,t="S256"){if("S256"!=t)return e;{let t=await async function(e){let t=(new TextEncoder).encode(e);return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}(e);return l.base64url.encode(t)}}class kt{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new i.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new i.PrivyClientError("User denied confirmation during OAuth flow");let e=function(){let e=d.i.get(c.CODE_VERIFIER_KEY);if(!e)throw new i.PrivyClientError("Authentication error.");return e}();try{let t=await this.api.post(o.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return d.i.del(c.CODE_VERIFIER_KEY),d.i.del(c.HEADLESS_OAUTH_KEY),d.i.del(c.OAUTH_DISABLE_SIGNUP_KEY),t}catch(e){let t=i.formatApiError(e);if(t.privyErrorCode)throw new i.PrivyClientError(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new i.PrivyClientError("Invalid code during oauth flow.",void 0,i.PrivyErrorCode.OAUTH_USER_DENIED);throw new i.PrivyClientError("Invalid code during OAuth flow.",void 0,i.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new i.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new i.PrivyClientError("User denied confirmation during OAuth flow");let e=d.i.get(c.CODE_VERIFIER_KEY);if(!e)throw new i.PrivyClientError("Authentication error.");try{let t=await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return d.i.del(c.CODE_VERIFIER_KEY),t}catch(e){throw i.formatApiError(e)}}async getAuthorizationUrl(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.provider)throw new i.PrivyClientError("Provider must be set when initializing OAuth authentication.");let e=It();d.i.put(c.CODE_VERIFIER_KEY,e);let t=Pt();d.i.put(c.STATE_CODE_KEY,t);let r=await jt(e);this.meta.withPrivyUi||d.i.put(c.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup&&d.i.put(c.OAUTH_DISABLE_SIGNUP_KEY,!0);let n=Et(this.meta.withPrivyUi);try{return await this.api.post(o.oAuthInitPath,{provider:this.meta.provider,redirect_to:window.location.href,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw i.formatApiError(e)}}constructor(e){this.meta=e}}function Nt(e){return e.charAt(0).toUpperCase()+e.slice(1)}const Mt=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 24 24",style:{height:"24px",...t},...r,children:[/*#__PURE__*/e.jsx("path",{d:"M17.0722 11.6888C17.0471 8.90571 19.3263 7.56847 19.429 7.50274C18.1466 5.60938 16.153 5.35154 15.4417 5.3212C13.7461 5.14678 12.1306 6.32982 11.269 6.32982C10.4074 6.32982 9.08004 5.34648 7.67246 5.37429C5.82158 5.40209 4.11595 6.45874 3.16171 8.13218C1.24068 11.4942 2.6708 16.4817 4.54423 19.2143C5.46091 20.549 6.55041 22.0531 7.98554 21.9975C9.36803 21.9419 9.88905 21.095 11.5571 21.095C13.2251 21.095 13.696 21.9975 15.1537 21.9697C16.6389 21.9393 17.5806 20.6046 18.4897 19.2648C19.5392 17.7153 19.9725 16.2137 19.9975 16.1354C19.965 16.1228 17.1022 15.0155 17.0722 11.6888Z",fill:"currentColor"}),/*#__PURE__*/e.jsx("path",{d:"M14.3295 3.51373C15.0909 2.58347 15.6043 1.28921 15.4641 0C14.3671 0.0455014 13.0396 0.738135 12.2532 1.66838C11.5494 2.48994 10.9307 3.80695 11.0986 5.07089C12.3183 5.16694 13.5681 4.44145 14.3295 3.51373Z",fill:"currentColor"})]}),Rt=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 71 55",style:{height:"24px",...t},...r,children:[/*#__PURE__*/e.jsx("g",{clipPath:"url(#clip0)",children:/*#__PURE__*/e.jsx("path",{d:"M60.1045 4.8978C55.5792 2.8214 50.7265 1.2916 45.6527 0.41542C45.5603 0.39851 45.468 0.440769 45.4204 0.525289C44.7963 1.6353 44.105 3.0834 43.6209 4.2216C38.1637 3.4046 32.7345 3.4046 27.3892 4.2216C26.905 3.0581 26.1886 1.6353 25.5617 0.525289C25.5141 0.443589 25.4218 0.40133 25.3294 0.41542C20.2584 1.2888 15.4057 2.8186 10.8776 4.8978C10.8384 4.9147 10.8048 4.9429 10.7825 4.9795C1.57795 18.7309 -0.943561 32.1443 0.293408 45.3914C0.299005 45.4562 0.335386 45.5182 0.385761 45.5576C6.45866 50.0174 12.3413 52.7249 18.1147 54.5195C18.2071 54.5477 18.305 54.5139 18.3638 54.4378C19.7295 52.5728 20.9469 50.6063 21.9907 48.5383C22.0523 48.4172 21.9935 48.2735 21.8676 48.2256C19.9366 47.4931 18.0979 46.6 16.3292 45.5858C16.1893 45.5041 16.1781 45.304 16.3068 45.2082C16.679 44.9293 17.0513 44.6391 17.4067 44.3461C17.471 44.2926 17.5606 44.2813 17.6362 44.3151C29.2558 49.6202 41.8354 49.6202 53.3179 44.3151C53.3935 44.2785 53.4831 44.2898 53.5502 44.3433C53.9057 44.6363 54.2779 44.9293 54.6529 45.2082C54.7816 45.304 54.7732 45.5041 54.6333 45.5858C52.8646 46.6197 51.0259 47.4931 49.0921 48.2228C48.9662 48.2707 48.9102 48.4172 48.9718 48.5383C50.038 50.6034 51.2554 52.5699 52.5959 54.435C52.6519 54.5139 52.7526 54.5477 52.845 54.5195C58.6464 52.7249 64.529 50.0174 70.6019 45.5576C70.6551 45.5182 70.6887 45.459 70.6943 45.3942C72.1747 30.0791 68.2147 16.7757 60.1968 4.9823C60.1772 4.9429 60.1437 4.9147 60.1045 4.8978ZM23.7259 37.3253C20.2276 37.3253 17.3451 34.1136 17.3451 30.1693C17.3451 26.225 20.1717 23.0133 23.7259 23.0133C27.308 23.0133 30.1626 26.2532 30.1066 30.1693C30.1066 34.1136 27.28 37.3253 23.7259 37.3253ZM47.3178 37.3253C43.8196 37.3253 40.9371 34.1136 40.9371 30.1693C40.9371 26.225 43.7636 23.0133 47.3178 23.0133C50.9 23.0133 53.7545 26.2532 53.6986 30.1693C53.6986 34.1136 50.9 37.3253 47.3178 37.3253Z",fill:"#5865F2"})}),/*#__PURE__*/e.jsx("defs",{children:/*#__PURE__*/e.jsx("clipPath",{id:"clip0",children:/*#__PURE__*/e.jsx("rect",{width:"71",height:"55",fill:"white"})})})]}),Ot=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"24",y:"24",viewBox:"0 0 98 96",style:{height:"24px",...t},...r,children:/*#__PURE__*/e.jsx("path",{d:"M48.854 0C21.839 0 0 22 0 49.217c0 21.756 13.993 40.172 33.405 46.69 2.427.49 3.316-1.059 3.316-2.362 0-1.141-.08-5.052-.08-9.127-13.59 2.934-16.42-5.867-16.42-5.867-2.184-5.704-5.42-7.17-5.42-7.17-4.448-3.015.324-3.015.324-3.015 4.934.326 7.523 5.052 7.523 5.052 4.367 7.496 11.404 5.378 14.235 4.074.404-3.178 1.699-5.378 3.074-6.6-10.839-1.141-22.243-5.378-22.243-24.283 0-5.378 1.94-9.778 5.014-13.2-.485-1.222-2.184-6.275.486-13.038 0 0 4.125-1.304 13.426 5.052a46.97 46.97 0 0 1 12.214-1.63c4.125 0 8.33.571 12.213 1.63 9.302-6.356 13.427-5.052 13.427-5.052 2.67 6.763.97 11.816.485 13.038 3.155 3.422 5.015 7.822 5.015 13.2 0 18.905-11.404 23.06-22.324 24.283 1.78 1.548 3.316 4.481 3.316 9.126 0 6.6-.08 11.897-.08 13.526 0 1.304.89 2.853 3.316 2.364 19.412-6.52 33.405-24.935 33.405-46.691C97.707 22 75.788 0 48.854 0z",fill:"currentColor"})}),Wt=({style:t})=>/*#__PURE__*/e.jsx(ft.default,{style:{color:"var(--privy-color-error)",...t}}),Lt=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"26px",width:"26px",...t},...r,children:[/*#__PURE__*/e.jsx("path",{d:"M22.56 12.25C22.56 11.47 22.49 10.72 22.36 10H12V14.255H17.92C17.665 15.63 16.89 16.795 15.725 17.575V20.335H19.28C21.36 18.42 22.56 15.6 22.56 12.25Z",fill:"#4285F4"}),/*#__PURE__*/e.jsx("path",{d:"M12 23C14.97 23 17.46 22.015 19.28 20.335L15.725 17.575C14.74 18.235 13.48 18.625 12 18.625C9.13504 18.625 6.71004 16.69 5.84504 14.09H2.17004V16.94C3.98004 20.535 7.70004 23 12 23Z",fill:"#34A853"}),/*#__PURE__*/e.jsx("path",{d:"M5.845 14.09C5.625 13.43 5.5 12.725 5.5 12C5.5 11.275 5.625 10.57 5.845 9.91V7.06H2.17C1.4 8.59286 0.999321 10.2846 1 12C1 13.775 1.425 15.455 2.17 16.94L5.845 14.09Z",fill:"#FBBC05"}),/*#__PURE__*/e.jsx("path",{d:"M12 5.375C13.615 5.375 15.065 5.93 16.205 7.02L19.36 3.865C17.455 2.09 14.965 1 12 1C7.70004 1 3.98004 3.465 2.17004 7.06L5.84504 9.91C6.71004 7.31 9.13504 5.375 12 5.375Z",fill:"#EA4335"})]});function Ut(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",width:26,height:26,viewBox:"0 0 140 140",x:"0px",y:"0px",fill:"none",...t,children:[/*#__PURE__*/e.jsxs("defs",{children:[/*#__PURE__*/e.jsxs("linearGradient",{id:"b",children:[/*#__PURE__*/e.jsx("stop",{offset:"0",stopColor:"#3771c8"}),/*#__PURE__*/e.jsx("stop",{stopColor:"#3771c8",offset:".128"}),/*#__PURE__*/e.jsx("stop",{offset:"1",stopColor:"#60f",stopOpacity:"0"})]}),/*#__PURE__*/e.jsxs("linearGradient",{id:"a",children:[/*#__PURE__*/e.jsx("stop",{offset:"0",stopColor:"#fd5"}),/*#__PURE__*/e.jsx("stop",{offset:".1",stopColor:"#fd5"}),/*#__PURE__*/e.jsx("stop",{offset:".5",stopColor:"#ff543e"}),/*#__PURE__*/e.jsx("stop",{offset:"1",stopColor:"#c837ab"})]}),/*#__PURE__*/e.jsx("radialGradient",{id:"c",cx:"158.429",cy:"578.088",r:"65",xlinkHref:"#a",gradientUnits:"userSpaceOnUse",gradientTransform:"matrix(0 -1.98198 1.8439 0 -1031.402 454.004)",fx:"158.429",fy:"578.088"}),/*#__PURE__*/e.jsx("radialGradient",{id:"d",cx:"147.694",cy:"473.455",r:"65",xlinkHref:"#b",gradientUnits:"userSpaceOnUse",gradientTransform:"matrix(.17394 .86872 -3.5818 .71718 1648.348 -458.493)",fx:"147.694",fy:"473.455"})]}),/*#__PURE__*/e.jsx("path",{fill:"url(#c)",d:"M65.03 0C37.888 0 29.95.028 28.407.156c-5.57.463-9.036 1.34-12.812 3.22-2.91 1.445-5.205 3.12-7.47 5.468C4 13.126 1.5 18.394.595 24.656c-.44 3.04-.568 3.66-.594 19.188-.01 5.176 0 11.988 0 21.125 0 27.12.03 35.05.16 36.59.45 5.42 1.3 8.83 3.1 12.56 3.44 7.14 10.01 12.5 17.75 14.5 2.68.69 5.64 1.07 9.44 1.25 1.61.07 18.02.12 34.44.12 16.42 0 32.84-.02 34.41-.1 4.4-.207 6.955-.55 9.78-1.28 7.79-2.01 14.24-7.29 17.75-14.53 1.765-3.64 2.66-7.18 3.065-12.317.088-1.12.125-18.977.125-36.81 0-17.836-.04-35.66-.128-36.78-.41-5.22-1.305-8.73-3.127-12.44-1.495-3.037-3.155-5.305-5.565-7.624C116.9 4 111.64 1.5 105.372.596 102.335.157 101.73.027 86.19 0H65.03z",transform:"translate(1.004 1)"}),/*#__PURE__*/e.jsx("path",{fill:"url(#d)",d:"M65.03 0C37.888 0 29.95.028 28.407.156c-5.57.463-9.036 1.34-12.812 3.22-2.91 1.445-5.205 3.12-7.47 5.468C4 13.126 1.5 18.394.595 24.656c-.44 3.04-.568 3.66-.594 19.188-.01 5.176 0 11.988 0 21.125 0 27.12.03 35.05.16 36.59.45 5.42 1.3 8.83 3.1 12.56 3.44 7.14 10.01 12.5 17.75 14.5 2.68.69 5.64 1.07 9.44 1.25 1.61.07 18.02.12 34.44.12 16.42 0 32.84-.02 34.41-.1 4.4-.207 6.955-.55 9.78-1.28 7.79-2.01 14.24-7.29 17.75-14.53 1.765-3.64 2.66-7.18 3.065-12.317.088-1.12.125-18.977.125-36.81 0-17.836-.04-35.66-.128-36.78-.41-5.22-1.305-8.73-3.127-12.44-1.495-3.037-3.155-5.305-5.565-7.624C116.9 4 111.64 1.5 105.372.596 102.335.157 101.73.027 86.19 0H65.03z",transform:"translate(1.004 1)"}),/*#__PURE__*/e.jsx("path",{fill:"#fff",d:"M66.004 18c-13.036 0-14.672.057-19.792.29-5.11.234-8.598 1.043-11.65 2.23-3.157 1.226-5.835 2.866-8.503 5.535-2.67 2.668-4.31 5.346-5.54 8.502-1.19 3.053-2 6.542-2.23 11.65C18.06 51.327 18 52.964 18 66s.058 14.667.29 19.787c.235 5.11 1.044 8.598 2.23 11.65 1.227 3.157 2.867 5.835 5.536 8.503 2.667 2.67 5.345 4.314 8.5 5.54 3.054 1.187 6.543 1.996 11.652 2.23 5.12.233 6.755.29 19.79.29 13.037 0 14.668-.057 19.788-.29 5.11-.234 8.602-1.043 11.656-2.23 3.156-1.226 5.83-2.87 8.497-5.54 2.67-2.668 4.31-5.346 5.54-8.502 1.18-3.053 1.99-6.542 2.23-11.65.23-5.12.29-6.752.29-19.788 0-13.036-.06-14.672-.29-19.792-.24-5.11-1.05-8.598-2.23-11.65-1.23-3.157-2.87-5.835-5.54-8.503-2.67-2.67-5.34-4.31-8.5-5.535-3.06-1.187-6.55-1.996-11.66-2.23-5.12-.233-6.75-.29-19.79-.29zm-4.306 8.65c1.278-.002 2.704 0 4.306 0 12.816 0 14.335.046 19.396.276 4.68.214 7.22.996 8.912 1.653 2.24.87 3.837 1.91 5.516 3.59 1.68 1.68 2.72 3.28 3.592 5.52.657 1.69 1.44 4.23 1.653 8.91.23 5.06.28 6.58.28 19.39s-.05 14.33-.28 19.39c-.214 4.68-.996 7.22-1.653 8.91-.87 2.24-1.912 3.835-3.592 5.514-1.68 1.68-3.275 2.72-5.516 3.59-1.69.66-4.232 1.44-8.912 1.654-5.06.23-6.58.28-19.396.28-12.817 0-14.336-.05-19.396-.28-4.68-.216-7.22-.998-8.913-1.655-2.24-.87-3.84-1.91-5.52-3.59-1.68-1.68-2.72-3.276-3.592-5.517-.657-1.69-1.44-4.23-1.653-8.91-.23-5.06-.276-6.58-.276-19.398s.046-14.33.276-19.39c.214-4.68.996-7.22 1.653-8.912.87-2.24 1.912-3.84 3.592-5.52 1.68-1.68 3.28-2.72 5.52-3.592 1.692-.66 4.233-1.44 8.913-1.655 4.428-.2 6.144-.26 15.09-.27zm29.928 7.97c-3.18 0-5.76 2.577-5.76 5.758 0 3.18 2.58 5.76 5.76 5.76 3.18 0 5.76-2.58 5.76-5.76 0-3.18-2.58-5.76-5.76-5.76zm-25.622 6.73c-13.613 0-24.65 11.037-24.65 24.65 0 13.613 11.037 24.645 24.65 24.645C79.617 90.645 90.65 79.613 90.65 66S79.616 41.35 66.003 41.35zm0 8.65c8.836 0 16 7.163 16 16 0 8.836-7.164 16-16 16-8.837 0-16-7.164-16-16 0-8.837 7.163-16 16-16z"})]})}function Ft({style:t,...r}){/*#__PURE__*/return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",viewBox:"0,0,256,256",style:{height:"26px",width:"26px",...t},...r,children:/*#__PURE__*/e.jsx("g",{fill:"#0077b5",strokeWidth:"1",strokeLinecap:"butt",strokeLinejoin:"miter",strokeMiterlimit:"10",style:{mixBlendMode:"normal"},children:/*#__PURE__*/e.jsx("g",{transform:"scale(5.12,5.12)",children:/*#__PURE__*/e.jsx("path",{d:"M41,4h-32c-2.76,0 -5,2.24 -5,5v32c0,2.76 2.24,5 5,5h32c2.76,0 5,-2.24 5,-5v-32c0,-2.76 -2.24,-5 -5,-5zM17,20v19h-6v-19zM11,14.47c0,-1.4 1.2,-2.47 3,-2.47c1.8,0 2.93,1.07 3,2.47c0,1.4 -1.12,2.53 -3,2.53c-1.8,0 -3,-1.13 -3,-2.53zM39,39h-6c0,0 0,-9.26 0,-10c0,-2 -1,-4 -3.5,-4.04h-0.08c-2.42,0 -3.42,2.06 -3.42,4.04c0,0.91 0,10 0,10h-6v-19h6v2.56c0,0 1.93,-2.56 5.81,-2.56c3.97,0 7.19,2.73 7.19,8.26z"})})})})}function Dt(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 496 512",...t,children:[/*#__PURE__*/e.jsx("path",{fill:"#1ed760",d:"M248 8C111.1 8 0 119.1 0 256s111.1 248 248 248 248-111.1 248-248S384.9 8 248 8Z"}),/*#__PURE__*/e.jsx("path",{d:"M406.6 231.1c-5.2 0-8.4-1.3-12.9-3.9-71.2-42.5-198.5-52.7-280.9-29.7-3.6 1-8.1 2.6-12.9 2.6-13.2 0-23.3-10.3-23.3-23.6 0-13.6 8.4-21.3 17.4-23.9 35.2-10.3 74.6-15.2 117.5-15.2 73 0 149.5 15.2 205.4 47.8 7.8 4.5 12.9 10.7 12.9 22.6 0 13.6-11 23.3-23.2 23.3zm-31 76.2c-5.2 0-8.7-2.3-12.3-4.2-62.5-37-155.7-51.9-238.6-29.4-4.8 1.3-7.4 2.6-11.9 2.6-10.7 0-19.4-8.7-19.4-19.4s5.2-17.8 15.5-20.7c27.8-7.8 56.2-13.6 97.8-13.6 64.9 0 127.6 16.1 177 45.5 8.1 4.8 11.3 11 11.3 19.7-.1 10.8-8.5 19.5-19.4 19.5zm-26.9 65.6c-4.2 0-6.8-1.3-10.7-3.6-62.4-37.6-135-39.2-206.7-24.5-3.9 1-9 2.6-11.9 2.6-9.7 0-15.8-7.7-15.8-15.8 0-10.3 6.1-15.2 13.6-16.8 81.9-18.1 165.6-16.5 237 26.2 6.1 3.9 9.7 7.4 9.7 16.5s-7.1 15.4-15.2 15.4z"})]})}function Bt(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fillRule:"evenodd",clipRule:"evenodd",imageRendering:"optimizeQuality",shapeRendering:"geometricPrecision",textRendering:"geometricPrecision",viewBox:"0 0 293768 333327",width:24,height:24,...t,children:[/*#__PURE__*/e.jsx("path",{fill:"#26f4ee",d:"M204958 0c5369 45832 32829 78170 77253 81022v43471l-287 27V87593c-44424-2850-69965-30183-75333-76015l-47060-1v192819c6791 86790-60835 89368-86703 56462 30342 18977 79608 6642 73766-68039V0h58365zM78515 319644c-26591-5471-50770-21358-64969-44588-34496-56437-3401-148418 96651-157884v54345l-164 27v-40773C17274 145544 7961 245185 33650 286633c9906 15984 26169 27227 44864 33011z"}),/*#__PURE__*/e.jsx("path",{fill:"#fb2c53",d:"M218434 11587c3505 29920 15609 55386 35948 70259-27522-10602-43651-34934-47791-70262l11843 3zm63489 82463c3786 804 7734 1348 11844 1611v51530c-25770 2537-48321-5946-74600-21749l4034 88251c0 28460 106 41467-15166 67648-34260 58734-95927 63376-137628 35401 54529 22502 137077-4810 136916-103049v-96320c26279 15803 48830 24286 74600 21748V94050zm-171890 37247c5390-1122 11048-1985 16998-2548v54345c-21666 3569-35427 10222-41862 22528-20267 38754 5827 69491 35017 74111-33931 5638-73721-28750-49999-74111 6434-12304 18180-18959 39846-22528v-51797zm64479-119719h1808-1808z"}),/*#__PURE__*/e.jsx("path",{d:"M206590 11578c5369 45832 30910 73164 75333 76015v51528c-25770 2539-48321-5945-74600-21748v96320c206 125717-135035 135283-173673 72939-25688-41449-16376-141089 76383-155862v52323c-21666 3569-33412 10224-39846 22528-39762 76035 98926 121273 89342-1225V11577l47060 1z",fill:"#000000"})]})}const Ht=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"24px",width:"24px",...t},...r,children:/*#__PURE__*/e.jsx("path",{d:"M 14.285156 10.171875 L 23.222656 0 L 21.105469 0 L 13.34375 8.832031 L 7.148438 0 L 0 0 L 9.371094 13.355469 L 0 24.019531 L 2.117188 24.019531 L 10.308594 14.691406 L 16.851562 24.019531 L 24 24.019531 M 2.878906 1.5625 L 6.132812 1.5625 L 21.101562 22.535156 L 17.851562 22.535156",fill:"currentColor"})});let zt={google:{name:"Google",component:Lt},discord:{name:"Discord",component:Rt},github:{name:"Github",component:Ot},linkedin:{name:"LinkedIn",component:Ft},twitter:{name:"Twitter",component:Ht},spotify:{name:"Spotify",component:Dt},instagram:{name:"Instagram",component:Ut},tiktok:{name:"Tiktok",component:Bt},apple:{name:"Apple",component:Mt}};const qt=e=>e in zt?zt[e]:{name:"Unknown",component:Wt};function Vt(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),n=e.get("privy_oauth_provider");if(!t||!r||!n)return{inProgress:!1};let a=!1;try{a=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:n,withPrivyUi:!d.i.get(c.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&a,disableSignup:!!d.i.get(c.OAUTH_DISABLE_SIGNUP_KEY)}}function Gt(){let e=new URL(window.location.href);e.searchParams.delete("privy_oauth_code"),e.searchParams.delete("privy_oauth_provider"),e.searchParams.delete("privy_oauth_state"),d.i.del(c.STATE_CODE_KEY),window.history.replaceState({},"",e)}class $t{async initRegisterFlow(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!0,this.meta.initRegisterResponse=await this.initRegisterOnce.execute(e)}async initAuthenticationFlow(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async register(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new i.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,r=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(o.passkeyRegisterPath,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new i.PrivyClientError("Passkey request timed out or rejected by user.",void 0,i.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw i.formatApiError(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new i.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());let t=this.meta.allowedCredentialsIds?.map((e=>({type:"public-key",id:e})))??this.meta.initAuthenticateResponse.options.allow_credentials;try{let r=await e.startAuthentication(this._transformInitAuthenticateOptionsToCamelCase({...this.meta.initAuthenticateResponse.options,allow_credentials:t}));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(o.passkeyAuthenticatePath,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new i.PrivyClientError("Passkey request timed out or rejected by user.",void 0,i.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw i.formatApiError(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new i.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,r=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(o.passkeyLinkPath,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new i.PrivyClientError("Passkey request timed out or rejected by user.",void 0,i.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw i.formatApiError(e)}}async _initRegisterOnce(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");let t=Et(e);return await this.api.post(o.passkeyInitRegisterPath,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");let t=Et(e);return await this.api.post(o.passkeyInitAuthenticatePath,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");return await this.api.post(o.passkeyInitLinkPath,{})}_transformInitLinkOptionsToCamelCase(e){return{rp:e.rp,user:{id:e.user.id,name:e.user.name,displayName:e.user.display_name},challenge:e.challenge,pubKeyCredParams:e.pub_key_cred_params.map((e=>({type:e.type,alg:e.alg}))),timeout:e.timeout,excludeCredentials:e.exclude_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports}))),authenticatorSelection:{authenticatorAttachment:e.authenticator_selection?.authenticator_attachment,requireResidentKey:e.authenticator_selection?.require_resident_key,residentKey:e.authenticator_selection?.resident_key,userVerification:e.authenticator_selection?.user_verification},attestation:e.attestation,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props?.rk,hmacCreateSecret:e.extensions?.hmac_create_secret}}}_transformRegistrationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}_transformInitAuthenticateOptionsToCamelCase(e){return{rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}}_transformAuthenticationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}constructor({captchaToken:e,setPasskeyAuthState:t}){this.authenticateForRegistration=!1,this.initRegisterOnce=new s.RunEffectOnce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new s.RunEffectOnce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new s.RunEffectOnce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t}}}class Kt{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new i.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsAuthenticatePath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new i.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsLinkPath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw i.formatApiError(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new i.PrivyClientError("phone nNumber must be set when initialzing authentication.");let n=Et(r);try{return await this.api.post(o.passwordlessSmsInitPath,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw i.formatApiError(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class Yt extends Kt{async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new i.PrivyClientError("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(o.updatePhonePath,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw i.formatApiError(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class Zt{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.telegramAccountAuthenticatePath,{captcha_token:this.meta.captchaToken,telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.telegramAccountLinkPath,{telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData})}catch(e){throw i.formatApiError(e)}}constructor(e,t=!1){this.meta={disableSignup:!1},this.meta={captchaToken:e,disableSignup:!1},this.meta.disableSignup=t}}function Xt(e){let t={detail:"",retryable:!1};return e?.privyErrorCode===i.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(t.detail="This account has already been linked to another user."),e?.privyErrorCode===i.PrivyErrorCode.DISALLOWED_LOGIN_METHOD&&(t.detail="Login with Telegram not allowed."),e?.privyErrorCode===i.PrivyErrorCode.INVALID_DATA&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===i.PrivyErrorCode.INVALID_CREDENTIALS&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&(t.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("rate limit")&&(t.detail="Request limit reached for Telegram. Please wait a moment and try again."),e instanceof s.CaptchaError&&(t.retryable=!0,t.detail="Something went wrong. Try again."),t}function Qt(e){return Object.fromEntries(decodeURIComponent(e).split("&").map((e=>e.split("=").map(decodeURIComponent))))}function Jt(){let e=new URL(window.location.href);e.searchParams.delete("id"),e.searchParams.delete("hash"),e.searchParams.delete("auth_date"),e.searchParams.delete("first_name"),e.searchParams.delete("last_name"),e.searchParams.delete("username"),e.searchParams.delete("photo_url"),e.hash="",window.history.replaceState({},"",e)}class er{static parse(e){try{return new er(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return Ae.decodeJwt(e),e}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=1e3*(this.expiration-e)}constructor(e){this.value=e,this._decoded=Ae.decodeJwt(e)}}class tr extends er{static parse(e){try{return new tr(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}const rr=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{viewBox:"0 0 1024 1024",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("rect",{width:"1024",height:"1024",fill:"#0052FF",rx:100,ry:100}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z",fill:"white"})]});let nr,ar=[1,11155111,137,10,8453,84532,42161,7777777,43114,56],ir=(e,t)=>e.makeWeb3Provider({options:t});class or extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:"data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyBmaWxsPSdub25lJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHN0eWxlPSdoZWlnaHQ6MjhweDt3aWR0aDoyOHB4Jz48cmVjdCB3aWR0aD0nMTAyNCcgaGVpZ2h0PScxMDI0JyBmaWxsPScjMDA1MkZGJyByeD0nMTAwJyByeT0nMTAwJz48L3JlY3Q+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBjbGlwLXJ1bGU9J2V2ZW5vZGQnIGQ9J00xNTIgNTEyQzE1MiA3MTAuODIzIDMxMy4xNzcgODcyIDUxMiA4NzJDNzEwLjgyMyA4NzIgODcyIDcxMC44MjMgODcyIDUxMkM4NzIgMzEzLjE3NyA3MTAuODIzIDE1MiA1MTIgMTUyQzMxMy4xNzcgMTUyIDE1MiAzMTMuMTc3IDE1MiA1MTJaTTQyMCAzOTZDNDA2Ljc0NSAzOTYgMzk2IDQwNi43NDUgMzk2IDQyMFY2MDRDMzk2IDYxNy4yNTUgNDA2Ljc0NSA2MjggNDIwIDYyOEg2MDRDNjE3LjI1NSA2MjggNjI4IDYxNy4yNTUgNjI4IDYwNFY0MjBDNjI4IDQwNi43NDUgNjE3LjI1NSAzOTYgNjA0IDM5Nkg0MjBaJyBmaWxsPSd3aGl0ZSc+PC9wYXRoPjwvc3ZnPg==",id:"com.coinbase.wallet"}}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}updateConnectionPreference(e){this.connectionOptions=e,this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",this.proxyProvider.setWalletProvider(ir(nr,this.connectionOptions))}constructor(e,t,r,n,a,i){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.connectionOptions=n.coinbaseWallet.connectionOptions??"all",this.walletClientType="smartWalletOnly"===this.connectionOptions?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!nr){let r=[t.id].concat(e.map((e=>e.id))),n="eoaOnly"!==this.connectionOptions?r.filter((e=>!ar.includes(e))):[];n.length>0&&!n.every((e=>c.DEFAULT_SUPPORTED_CHAIN_IDS.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${n.join(", ")}`),nr=new p.CoinbaseWalletSDK({appName:a,appLogoUrl:i,appChainIds:r})}this.proxyProvider.setWalletProvider(ir(nr,this.connectionOptions))}}const sr=({...t})=>/*#__PURE__*/e.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t,children:/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M2.37126 11.0323C2.37126 12.696 3.90598 13.4421 5.40654 13.4468C8.91753 13.4468 12.8021 11.2897 12.7819 7.67984C12.7673 5.07728 10.3748 2.86167 7.54357 2.88296C4.8495 2.88296 2.21821 4.6411 2.21803 7.03628C2.21803 7.67951 2.58722 8.30178 3.55231 8.37184C2.74763 9.16826 2.37126 10.1225 2.37126 11.0323ZM7.55283 8.68012C8.11562 8.68012 8.57186 8.13217 8.57186 7.45624C8.57186 6.78032 8.11562 6.23237 7.55283 6.23237C6.99003 6.23237 6.53379 6.78032 6.53379 7.45624C6.53379 8.13217 6.99003 8.68012 7.55283 8.68012ZM10.4747 8.68012C11.0375 8.68012 11.4937 8.13217 11.4937 7.45625C11.4937 6.78032 11.0375 6.23237 10.4747 6.23237C9.91186 6.23237 9.45562 6.78032 9.45562 7.45625C9.45562 8.13217 9.91186 8.68012 10.4747 8.68012Z",fill:t.color||"var(--privy-color-foreground-3)"})});class lr extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[s.toHex(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:sr,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:r,rpcConfig:n,imported:a,walletIndex:i}){super("privy",t,r,n),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=i,a&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}const cr=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];let dr={0:"legacy",1:"eip2930",2:"eip1559",3:"eip4844"};const ur={legacy:0,eip2930:1,eip1559:2,eip4844:3};let hr=e=>void 0!==e?BigInt(e):void 0;function pr(e){let t,{type:r=2,...n}=e;n.accessList&&Array.isArray(n.accessList)?t=n.accessList.map((e=>Array.isArray(e)?{address:e[0],storageKeys:e[1]}:e)):n.accessList&&(t=Object.entries(n.accessList).map((e=>({address:e[0],storageKeys:e[1]}))));let a=Number(n.chainId??1),o=y.isHex(n.data)?n.data:n.data?y.toHex(Uint8Array.from(n.data)):void 0,s=n.nonce?Number(n.nonce):void 0,l={chainId:a,data:o,nonce:s,value:hr(n.value),gas:hr(n.gas??n.gasLimit)},c=Number(r);if(0===c)return{...n,type:dr[c],...l,gasPrice:hr(n.gasPrice),accessList:void 0,maxFeePerGas:void 0,maxPriorityFeePerGas:void 0};if(1===c)return{...n,type:dr[c],...l,gasPrice:hr(n.gasPrice),accessList:t,maxFeePerGas:void 0,maxPriorityFeePerGas:void 0};if(2===c)return{...n,type:dr[c],...l,nonce:s,accessList:t,maxFeePerGas:hr(n.maxFeePerGas),maxPriorityFeePerGas:hr(n.maxPriorityFeePerGas),gasPrice:void 0,maxFeePerBlobGas:void 0};throw new i.PrivyClientError(`Unsupported transaction type: ${r}`)}class yr extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class mr extends be.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new yr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Qh()||!this.address)throw new yr("Disconnected",4900);let{hash:r}=await rp(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new yr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Qh()||!this.address)throw new yr("Disconnected",4900);let{signature:r}=await tp(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new yr(`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 yr(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=m.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:n}=await Jh({message:t},{address:r});return n}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:n}=await ep(s.generateTypedDataWithDomainType(r),{address:t});return n}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:s.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...pr(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 s.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(!(e=>cr.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await Qh();if(await np(),!t||!this.address)throw new yr("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 yr("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:a,chains:i,appId:o,chainId:l=1,walletIndex:c}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=l,this.rpcConfig=a,this.chains=i,this.publicClient=m.getPublicClient(l,this.chains,a,{appId:o}),this.rpcTimeoutDuration=s.getRpcTimeout(a,"privy"),this.appId=o,this.walletIndex=c}}class gr extends s.EthereumWalletConnector{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the EthereumNullConnector")}disconnect(){throw Error("disconnect called for an uninstalled wallet via the EthereumNullConnector")}promptConnection(e){throw Error(`promptConnection called for an uninstalled wallet via the EthereumNullConnector for ${e}`)}constructor({id:e,name:t,icon:r,walletClientType:n,defaultChain:a}){super(n,[],a,{}),this.connectorType="null",this.proxyProvider=new s.PrivyProxyProvider(void 0,c.DEFAULT_RPC_TIMEOUT),this.id=e,this.name=t,this.icon=r,this.connectorType=n}}const fr=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlSpace:"preserve",x:0,y:0,viewBox:"0 0 318.6 318.6",width:"28",height:"28",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("style",{children:".s1{stroke-linecap:round;stroke-linejoin:round}.s2{fill:#e4761b;stroke:#e4761b}.s3{fill:#f6851b;stroke:#f6851b}"}),/*#__PURE__*/e.jsx("path",{fill:"#e2761b",stroke:"#e2761b",className:"s1",d:"m274.1 35.5-99.5 73.9L193 65.8z"}),/*#__PURE__*/e.jsx("path",{d:"m44.4 35.5 98.7 74.6-17.5-44.3zm193.9 171.3-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z",className:"s1 s2"}),/*#__PURE__*/e.jsx("path",{d:"m103.6 138.2-15.8 23.9 56.3 2.5-2-60.5zm111.3 0-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5 33.9 16.5-4.7-39.3z",className:"s1 s2"}),/*#__PURE__*/e.jsx("path",{fill:"#d7c1b3",stroke:"#d7c1b3",className:"s1",d:"m211.8 247.4-33.9-16.5 2.7 22.1-.3 9.3zm-105 0 31.5 14.9-.2-9.3 2.5-22.1z"}),/*#__PURE__*/e.jsx("path",{fill:"#233447",stroke:"#233447",className:"s1",d:"m138.8 193.5-28.2-8.3 19.9-9.1zm40.9 0 8.3-17.4 20 9.1z"}),/*#__PURE__*/e.jsx("path",{fill:"#cd6116",stroke:"#cd6116",className:"s1",d:"m106.8 247.4 4.8-40.6-31.3.9zM207 206.8l4.8 40.6 26.5-39.7zm23.8-44.7-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1 20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"}),/*#__PURE__*/e.jsx("path",{fill:"#e4751f",stroke:"#e4751f",className:"s1",d:"m87.8 162.1 23.6 46-.8-22.9zm120.3 23.1-1 22.9 23.7-46zm-64-20.6-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0-2.7 18 1.2 45 6.7-34.1z"}),/*#__PURE__*/e.jsx("path",{d:"m179.8 193.5-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z",className:"s3"}),/*#__PURE__*/e.jsx("path",{fill:"#c0ad9e",stroke:"#c0ad9e",className:"s1",d:"m180.3 262.3.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"}),/*#__PURE__*/e.jsx("path",{fill:"#161616",stroke:"#161616",className:"s1",d:"m177.9 230.9-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"}),/*#__PURE__*/e.jsx("path",{fill:"#763d16",stroke:"#763d16",className:"s1",d:"m278.3 114.2 8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"}),/*#__PURE__*/e.jsx("path",{d:"m267.2 153.5-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4 3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z",className:"s3"})]}),wr=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M46.5267 69.9229C42.0054 76.8509 34.4292 85.6182 24.348 85.6182C19.5824 85.6182 15 83.6563 15 75.1342C15 53.4305 44.6326 19.8327 72.1268 19.8327C87.768 19.8327 94 30.6846 94 43.0079C94 58.8258 83.7355 76.9122 73.5321 76.9122C70.2939 76.9122 68.7053 75.1342 68.7053 72.314C68.7053 71.5783 68.8275 70.7812 69.0719 69.9229C65.5893 75.8699 58.8685 81.3878 52.5754 81.3878C47.993 81.3878 45.6713 78.5063 45.6713 74.4598C45.6713 72.9884 45.9768 71.4556 46.5267 69.9229ZM83.6761 42.5794C83.6761 46.1704 81.5575 47.9658 79.1875 47.9658C76.7816 47.9658 74.6989 46.1704 74.6989 42.5794C74.6989 38.9885 76.7816 37.1931 79.1875 37.1931C81.5575 37.1931 83.6761 38.9885 83.6761 42.5794ZM70.2103 42.5795C70.2103 46.1704 68.0916 47.9658 65.7216 47.9658C63.3157 47.9658 61.233 46.1704 61.233 42.5795C61.233 38.9885 63.3157 37.1931 65.7216 37.1931C68.0916 37.1931 70.2103 38.9885 70.2103 42.5795Z",fill:"#FFFDF8"})]});function vr(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var Cr=0;class xr extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return{name:this.providerDetail.info.name,icon:this.providerDetail.info.icon,id:this.providerDetail.info.rdns}}disconnect(){console.warn(`Programmatic disconnect with ${this.providerDetail.info.name} is not yet supported.`)}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}constructor(e,t,r,n,a){super(a||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let i=n.provider;this.proxyProvider.setWalletProvider(i)}}var Er="__private_"+Cr+++"__walletBranding";class Sr extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return vr(this,Er)[Er]??{name:"Browser Extension",icon:s.BrowserExtensionWallet,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}constructor(e,t,r,n,a){super(a??"unknown",e,t,r),Object.defineProperty(this,Er,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===a?vr(this,Er)[Er]={name:"MetaMask",icon:fr,id:"io.metamask"}:"phantom"===a&&(vr(this,Er)[Er]={name:"Phantom",icon:wr,id:"phantom"})}}class Tr extends xr{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{n.isMobile||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}}const Ar=["metamask","phantom","brave_wallet","rainbow","uniswap_wallet_extension","uniswap_extension","rabby_wallet","bybit_wallet","ronin_wallet","crypto.com_wallet_extension","crypto.com_onchain","coinbase_wallet","coinbase_smart_wallet","metamask","trust","safe","rainbow","uniswap","zerion","argent","spot","omni","cryptocom","blockchain","safepal","bitkeep","zengo","1inch","binance","exodus","mew_wallet","alphawallet","keyring_pro","mathwallet","unstoppable","obvious","ambire","internet_money_wallet","coin98","abc_wallet","arculus_wallet","haha","cling_wallet","broearn","copiosa","burrito_wallet","enjin_wallet","plasma_wallet","avacus","bee","pitaka","pltwallet","minerva","kryptogo","prema","slingshot","kriptonio","timeless","secux","bitizen","blocto","okx_wallet","safemoon","rabby_wallet","bybit_wallet","ronin_wallet","privy","unknown","phantom","solflare","glow","backpack"],br=Object.freeze({phantom:{client:"phantom",name:"Phantom",installLink:Te.isFirefox?"https://addons.mozilla.org/en-US/firefox/addon/phantom-app/":"https://chrome.google.com/webstore/detail/phantom/bfnaelmomeimhlpmgjnjophhpkkoljpa?hl=en",chainTypes:["ethereum","solana"],get isInstalled(){if("phantom"in window){let e=window;if(e?.phantom?.ethereum?.isPhantom&&e?.phantom?.ethereum?.chainId||e?.phantom?.solana?.isPhantom)return!0}return!1},getMobileRedirect({useUniversalLink:e,isSolana:t,connectOnly:r}){let n=Ir({client:this.client,isSolana:t,connectOnly:r});return`${e?"phantom://":"https://phantom.app/ul/"}browse/${n}?ref=${n}`}},solflare:{client:"solflare",name:"Solflare",installLink:Te.isFirefox?"https://addons.mozilla.org/es/firefox/addon/solflare-wallet/":"https://chromewebstore.google.com/detail/solflare-wallet/bhhhlbepdkbapadjdnnojkbgioiodbic",chainTypes:["solana"],get isInstalled(){return"solflare"in window&&!!window?.solflare?.isSolflare},getMobileRedirect({useUniversalLink:e,isSolana:t,connectOnly:r}){let n=Ir({client:this.client,isSolana:t,connectOnly:r});return`${e?"solflare://ul/v1/":"https://solflare.com/ul/v1/"}browse/${n}?ref=${n}`}},backpack:{client:"backpack",name:"Backpack",installLink:"https://chromewebstore.google.com/detail/backpack/aflkmfhebedbjioipglgcbcmnbpgliof",chainTypes:["ethereum","solana"],get isInstalled(){return!(!("backpack"in window)||!window?.backpack?.ethereum?.isBackpack&&!window?.backpack?.solana?.isBackpack)},getMobileRedirect({useUniversalLink:e,isSolana:t,connectOnly:r}){let n=Ir({client:this.client,isSolana:t,connectOnly:r});return`${e?"backpack://ul/v1/":"https://backpack.com/ul/v1/"}browse/${n}?ref=${n}`}},okx_wallet:{client:"okx_wallet",name:"OKX Wallet",installLink:"https://chromewebstore.google.com/detail/okx-wallet/mcohilncbfahbmgdjkbpemcciiolgcge",chainTypes:["solana"],get isInstalled(){return"okxwallet"in window&&!!window?.okxwallet?.isOkxWallet},getMobileRedirect({isSolana:e,connectOnly:t}){return"https://www.okx.com/download?deeplink="+encodeURIComponent("okx://wallet/dapp/url?dappUrl="+Ir({client:this.client,isSolana:e,connectOnly:t}))}}});function _r({connectorType:e,walletClientType:t}){for(let r of Ar)if(e===r||t===r)return br[r]}function Ir({client:e,isSolana:t,connectOnly:r}){let n=new URL(window.location.href);return n.searchParams.set("privy_connector",t?"solana_adapter":"injected"),n.searchParams.set("privy_wallet_client",e),n.searchParams.set("privy_connect_only",String(r)),encodeURIComponent(n.href.replace(/\/$/g,""))}class Pr extends d.SolanaWalletConnector{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the SolanaNullConnector")}constructor({id:e,name:t,icon:r}){super({name:t},!1),this.connectorType="null",this.proxyProvider=new s.PrivyProxyProvider(void 0,c.DEFAULT_RPC_TIMEOUT),this.disconnect=async()=>{throw Error("disconnect called for an uninstalled wallet via the SolanaNullConnector")},this.promptConnection=async()=>{throw Error("promptConnection called for an uninstalled wallet via the SolanaNullConnector")},this.id=e,this.name=t,this.icon=r}}class jr extends be.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(e){if(this.initialized&&!e)return;e&&this.removeAllConnectors(),d.i.get(c.CONNECTORS_STATE_KEY)&&(d.i.getKeys().forEach((e=>{e.startsWith("walletconnect")&&d.i.del(e)})),d.i.del(c.CONNECTORS_STATE_KEY));let t=s.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(br)))!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.addSolanaWalletConnector(new Pr({id:e.client,name:e.name})));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 t,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(s.isEthereumWalletConnector).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(s.isEthereumWalletConnector).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(d.isSolanaWalletConnector).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??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:n,appId:a}){for(let i of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(r&&s.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let{entropyId:r,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(t),s=new lr({provider:new mr({walletProxy:e,address:i.address,entropyId:r,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:n.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,r,n){let a=this.findWalletConnector("embedded_imported","privy");if(a&&s.isEthereumWalletConnector(a))a.proxyProvider.walletProxy=e;else{let a=new lr({provider:new mr({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(a)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=d.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=d.loadConnectionHistory(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let a=this.findWalletConnector(e,t);if(a&&s.isEthereumWalletConnector(a))return a instanceof s.WalletConnectV2WalletConnector&&a.resetConnection(t),a;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new or(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new s.WalletConnectV2WalletConnector(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):n?new gr({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Tr(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Sr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Sr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Sr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new xr(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})));d.i.put(c.CONNECTIONS_HISTORY_KEY,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&s.isBaseConnectedEthereumWallet(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=a.getAddress(e),this.emit("walletsUpdated")}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,r,n,a,i,o,l,c,u,h,p){super(),this.addSolanaWalletConnector=async e=>{let t=this.findSolanaWalletConnector(e.walletClientType);if(!t||"null"===t.connectorType){if("null"===t?.connectorType){let e=this.walletConnectors.indexOf(t);this.walletConnectors.splice(e,1)}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 s.PrivyProxyProvider},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=a,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=l,this.externalWalletConfig=c,this.privyAppName=u,this.privyAppLogo=h,this.walletChainType=p||"ethereum-only",this.storedConnections=d.loadConnectionHistory()}}let kr=[o.sessionsRefreshPath,o.sessionsLogoutPath,o.analyticsEventsPath];class Nr{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw i.formatApiError(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw i.formatApiError(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw i.formatApiError(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=c.VERSION,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=g.ofetch.create({baseURL:this.defaults.baseURL,timeout:this.defaults.timeout,retry:3,retryDelay:500,retryStatusCodes:[408,409,425,500,502,503,504],credentials:"include",onRequest:async({request:e,options:t})=>{let r=new Headers(t.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-ca-id",this.clientAnalyticsId||""),r.set("privy-client",`react-auth:${this.sdkVersion}`);let n=kr.includes(e.toString());if(!r.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:n});null!==e&&r.set("authorization",`Bearer ${e}`)}t.headers=r,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new i.PrivyTimeoutError}})}}let Mr=/paymaster\.biconomy\.io\/api/i,Rr={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const Or=(e,t)=>e&&Mr.test(e)?Rr:t&&t.policy_id?{policyId:t.policy_id}:void 0;function Wr(){return!(n.isSafari&&window.location.origin.startsWith("http://localhost"))}const Lr=w.create((()=>({identityToken:null})));var Ur,Fr=((Ur={}).PRIVY="privy_access_token",Ur.CUSTOMER="customer_access_token",Ur);class Dr{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)}get privyAccessToken(){return this._getToken(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}_getToken(e){try{let t=d.i.get(e);return"string"==typeof t?er.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=d.i.get(c.REFRESH_TOKEN_STORAGE_KEY);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=d.i.get(c.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new er(t);return r.isExpired()?(d.i.del(c.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=_e.default.get(c.SESSION_COOKIE_KEY);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e="privy_access_token"){let t="string"==typeof this.getToken(e),r="string"==typeof this.refreshToken&&this.refreshToken!==c.DEPRECATED_REFRESH_TOKEN;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=er.parse(this.getToken(e));return null!==t&&!t.isExpired(30)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(e,t){"string"==typeof t?d.i.put(c.getProviderAccessTokenStorageKey(e),t):d.i.del(c.getProviderAccessTokenStorageKey(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:r,is_new_user:n,oauth_tokens:a}=t;this.handleTokenResponse(t);let i=a?{provider:a.provider,accessToken:a.access_token,accessTokenExpiresInSeconds:a.access_token_expires_in_seconds,refreshToken:a.refresh_token,refreshTokenExpiresInSeconds:a.refresh_token_expires_in_seconds,scopes:a.scopes}:void 0;return this._trackAuthenticateEvents(e,n),{user:c.convertUserResponseToUser(r),isNewUser:n,oAuthTokens:i}}catch(e){throw console.warn("Error authenticating session"),i.formatPrivyError(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof St?"email":e instanceof Kt?"sms":e instanceof s.SiweFlow?"siwe":e instanceof _t?"guest":e instanceof xt?"custom_auth":e instanceof kt?e.meta.provider:null}(e);r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:r,isNewUser:t}}),"siwe"===r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:e.meta.connectorType,walletClientType:e.meta.walletClientType}})}async _link(e){try{let t=await e.link(),r=t.oauth_tokens,n=r?{provider:r.provider,accessToken:r.access_token,accessTokenExpiresInSeconds:r.access_token_expires_in_seconds,refreshToken:r.refresh_token,refreshTokenExpiresInSeconds:r.refresh_token_expires_in_seconds,scopes:r.scopes}:void 0;return{user:c.convertUserResponseToUser(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),i.formatPrivyError(e)}}async _refresh(){if(!this.api)throw new i.PrivyClientError("Session has no API instance");if(!this.client)throw new i.PrivyClientError("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,t=this.refreshToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let r;if(!(e&&t||this.mightHaveServerCookies))return null;{let n={};e&&(n.authorization=`Bearer ${e}`),r=await this.api.post(o.sessionsRefreshPath,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),c.convertUserResponseToUser(r.user)}catch(e){if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw i.formatPrivyError(e)}}handleTokenResponse(e){e.session_update_action&&"set"!==e.session_update_action?"clear"===e.session_update_action?this.destroyLocalState():"ignore"===e.session_update_action&&(e.token&&(this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token)),e.identity_token&&this.storeIdentityToken(e.identity_token)):this._storeAllTokens(e)}_storeAllTokens(e){this.storeRefreshToken(e.refresh_token),this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token),e.identity_token&&this.storeIdentityToken(e.identity_token)}async _destroy(){try{await(this.api?.post(o.sessionsLogoutPath,{refresh_token:this.refreshToken}))}catch(e){console.warn("Error destroying session")}this.destroyLocalState()}destroyLocalState(){this.storeRefreshToken(null),this.storeCustomerAccessToken(null),this.storePrivyAccessToken(null),this.clearIdentityToken()}storeCustomerAccessToken(e){if("string"==typeof e){let t=d.i.get(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(d.i.put(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=er.parse(e)?.expiration;_e.default.set(c.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:Wr(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else d.i.del(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),_e.default.remove(c.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(d.i.put(c.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||_e.default.set(c.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:Wr(),expires:30})):(d.i.del(c.REFRESH_TOKEN_STORAGE_KEY),_e.default.remove(c.REFRESH_TOKEN_COOKIE_KEY),_e.default.remove(c.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?d.i.put(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):d.i.del(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(Lr.setState({identityToken:e}),this.client?.useServerCookies)return;d.i.put(c.IDENTITY_TOKEN_STORAGE_KEY,e);let t=er.parse(e)?.expiration;_e.default.set(c.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:Wr(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){d.i.del(c.IDENTITY_TOKEN_STORAGE_KEY),Lr.setState({identityToken:null}),_e.default.remove(c.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new s.RunEffectOnce((async e=>this._authenticate(e))),this.linkOnce=new s.RunEffectOnce((async e=>this._link(e))),this.refreshOnce=new s.RunEffectOnce(this._refresh.bind(this)),this.destroyOnce=new s.RunEffectOnce(this._destroy.bind(this))}}let Br;var Hr=0,zr="__private_"+Hr+++"__getOrGenerateClientAnalyticsId";class qr{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:a,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new jr(this.appId,e,t,r,n,a,i,o,s,l,void 0,c))}generateApi(){let e=new Nr({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 i.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new i.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(o.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw i.formatApiError(e)}}async initMfaPasskeyVerification(){try{return(e=>({rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}))((await this.api.post(o.mfaPasskeyInitPath,{})).options)}catch(e){throw i.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(o.acceptTermsPath,{});return c.convertUserResponseToUser(e)}catch(e){throw i.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(o.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(o.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(o.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(o.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(o.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(r)}catch(e){throw i.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(o.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(o.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(o.delegatedActionsRevokePath,{})}catch(e){throw i.formatPrivyError(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:n}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(o.analyticsEventsPath,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(o.moonpayPluginOnRampPath,e)}catch(e){throw i.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(o.coinbaseOnRampInitPath,e)}catch(e){throw i.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${o.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw i.formatPrivyError(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(Fr.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Fr.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?tr.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:Or(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw i.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}),n=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,a=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:{ethereum:{createOnLogin:r.embedded_wallet_config.ethereum?.create_on_login??r.embedded_wallet_config.create_on_login},solana:{createOnLogin:r.embedded_wallet_config.solana?.create_on_login??"off"},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:n,fundingConfig:a}}catch(e){throw i.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 generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(o.siweInitPath,{address:e,token:t})).nonce}catch(e){throw i.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i}){return await this.api.post(o.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){return await this.api.post(o.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})}async linkSmartWallet({message:e,signature:t,smartWalletType:r}){try{let n=await this.api.post(o.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r});return c.convertUserResponseToUser(n)}catch(e){throw i.formatPrivyError(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a});return c.convertUserResponseToUser(i)}catch(e){throw i.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(o.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw i.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:a}){return await this.api.post(o.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:n,mode:a})}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:s,farcasterEmbeddedAddress:l,oAuthUserInfo:d}){try{let i,u;switch(r){case"email":i=o.transferEmailPath,u={nonce:e,email:t};break;case"sms":i=o.transferPhonePath,u={nonce:e,phoneNumber:t};break;case"siwe":if(i=o.transferWalletPath,!n)throw Error("Wallet parameters must be defined");u={nonce:e,address:t,...n};break;case"farcaster":i=o.transferFarcasterPath,u={nonce:e,farcaster_id:t,farcaster_embedded_address:l};break;case"telegram":i=o.telegramAccountTransferPath,u={nonce:e,telegram_auth_result:a,telegram_web_app_data:s};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:i=o.transferOAuthPath,u={nonce:e,userInfo:d}}let h=await this.api.post(i,u);return await this.getAuthenticatedUser()??c.convertUserResponseToUser(h)}catch(e){throw i.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n}){return await this.api.post(o.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:n})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n}){try{let a=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n});return c.convertUserResponseToUser(a)}catch(e){throw i.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(o.usersMePath);return this.session.updateIdentityToken(e.identity_token),c.convertUserResponseToUser(e.user)}catch(e){throw i.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(o.transactionScanningPath,e)}catch(e){throw i.formatPrivyError(e)}}constructor({apiUrl:e=c.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:n=c.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,zr,{value:Vr}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==c.DEFAULT_PRIVY_API_URL&&e.startsWith("https://privy."),this.timeout=n,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,zr)[zr](),Br||(Br=new Dr),this.session=Br,this.api=this.generateApi(),this.session.client=this}}function Vr(){if("undefined"==typeof window)return null;try{let e=d.i.get(c.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=u.v4();try{return d.i.put(c.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}const Gr=t=>{let{enabled:n,siteKey:a,appId:i,setError:o,setToken:l,setExecuting:c,ref:d}=s.useCaptcha(),[,u]=r.useMemo((()=>a?.split("t:")||[]),[a]);if(r.useEffect((()=>d.current?.remove),[]),!n)return null;if(!u)throw Error("Unsupported captcha site key");/*#__PURE__*/return e.jsx("div",{className:"hidden h-0 w-0",children:/*#__PURE__*/e.jsx(v.Turnstile,{...t,ref:d,siteKey:u,options:{action:i,size:"invisible",...t.delayedExecution?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{t.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{t.onError?.(),o("Captcha failed"),c(!1)},onSuccess:e=>{t.onSuccess?.(e),l(e),c(!1)},onExpire:()=>{t.onExpire?.();try{d.current?.reset(),o(void 0),l(void 0)}catch(e){o("expired_and_failed_reset")}}})})};function $r(e){d.usePrivyEventSubscription("configureMfa",e)}const Kr=/*#__PURE__*/C.styled.span.withConfig({displayName:"CircleBackground",componentId:"sc-c9f33cd-0"})(["&&{width:82px;height:82px;border-width:4px;border-style:solid;border-color:",";background-color:",";border-radius:50%;display:inline-block;box-sizing:border-box;}"],(e=>e.color??"var(--privy-color-accent)"),(e=>e.color??"var(--privy-color-accent)"));let Yr=/*#__PURE__*/C.styled.div.withConfig({displayName:"StackedContainer",componentId:"sc-f7e7d474-0"})(["display:flex;flex-direction:column;justify-content:center;align-items:center;width:100%;height:82px;> div{position:relative;}> div > span{position:absolute;left:-41px;top:-41px;}> div > :last-child{position:absolute;left:-19px;top:-19px;}"]);const Zr=/*#__PURE__*/C.styled.div.withConfig({displayName:"Grow",componentId:"sc-ddbf22b4-0"})(["text-align:left;flex-grow:1;"]),Xr=/*#__PURE__*/C.styled.div.withConfig({displayName:"AlignBottom",componentId:"sc-ddbf22b4-1"})(["display:flex;flex-direction:column;justify-content:flex-end;flex-grow:1;"]),Qr=/*#__PURE__*/C.styled.div.withConfig({displayName:"LoginMethodContainer",componentId:"sc-ddbf22b4-2"})(["display:flex;flex-direction:column;gap:12px;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}"]),Jr=/*#__PURE__*/C.styled(Qr).withConfig({displayName:"LoginMethodContainerWithScrollShadows",componentId:"sc-ddbf22b4-3"})([""," background-repeat:no-repeat;background-size:100% 32px,100% 16px;background-attachment:local,scroll;max-height:400px;overflow-y:auto;scrollbar-width:none;padding:2px;"],(e=>"light"===e.$colorScheme?"background: linear-gradient(var(--privy-color-background), var(--privy-color-background) 70%) bottom, linear-gradient(rgba(0, 0, 0, 0) 20%, rgba(0, 0, 0, 0.06)) bottom;":"dark"===e.$colorScheme?"background: linear-gradient(var(--privy-color-background), var(--privy-color-background) 70%) bottom, linear-gradient(rgba(255, 255, 255, 0) 20%, rgba(255, 255, 255, 0.06)) bottom;":void 0));let en=/*#__PURE__*/C.css(["&&{width:100%;font-size:16px;line-height:24px;@media (min-width:440px){font-size:14px;}display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--privy-color-foreground-4) !important;border-radius:var(--privy-border-radius-mdlg);transition:background-color 200ms ease;cursor:pointer;&:hover{background-color:var(--privy-color-background-2);}&:disabled{cursor:pointer;background-color:var(--privy-color-background-2);}svg{height:24px;max-height:24px;max-width:24px;}}"]);const tn=/*#__PURE__*/C.styled.div.withConfig({displayName:"Subtitle",componentId:"sc-ddbf22b4-4"})(["text-align:center;font-size:14px;margin-bottom:24px;"]),rn=/*#__PURE__*/C.styled.button.attrs({className:"login-method-button"}).withConfig({displayName:"LoginMethodButton",componentId:"sc-ddbf22b4-5"})(["",""],en),nn=/*#__PURE__*/C.styled.a.withConfig({displayName:"LoginMethodButtonLink",componentId:"sc-ddbf22b4-6"})(["",""],en),an=/*#__PURE__*/C.styled.div.withConfig({displayName:"Hide",componentId:"sc-ddbf22b4-7"})(["width:100%;height:100%;min-height:inherit;display:flex;flex-direction:column;",""],(e=>e.$if?"display: none;":"")),on=/*#__PURE__*/C.styled.div.withConfig({displayName:"EmptyWalletState",componentId:"sc-ddbf22b4-8"})(["width:100%;height:100%;padding:",";"],(e=>e.$withPadding?"64px 0px":"0px")),sn=/*#__PURE__*/C.styled.div.withConfig({displayName:"Header",componentId:"sc-ddbf22b4-9"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-bottom:32px;gap:12px;& h3{font-size:18px;font-style:normal;font-weight:600;line-height:24px;}& p{max-width:300px;font-size:14px;font-style:normal;font-weight:400;line-height:20px;}"]);let ln=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-a3e74b9e-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;padding-bottom:16px;margin-top:24px;"]),cn=/*#__PURE__*/C.styled.div.withConfig({displayName:"GappedContainer",componentId:"sc-a3e74b9e-1"})(["display:flex;flex-direction:column;gap:8px;"]);const dn=/*#__PURE__*/C.styled.span.withConfig({displayName:"CircleBorder",componentId:"sc-9056b8b8-0"})(["&&{width:82px;height:82px;border-width:4px;border-style:solid;border-color:",";border-bottom-color:transparent;border-radius:50%;display:inline-block;box-sizing:border-box;animation:rotation 1.2s linear infinite;transition:border-color 800ms;border-bottom-color:",";}"],(e=>e.color??"var(--privy-color-accent)"),(e=>e.color??"var(--privy-color-accent)"));function un(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:[/*#__PURE__*/e.jsx("circle",{cx:"12",cy:"12",r:"10"}),/*#__PURE__*/e.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),/*#__PURE__*/e.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}const hn=({onTransfer:t,isTransferring:r,transferSuccess:n})=>/*#__PURE__*/e.jsx(s.PrimaryButton,{...n?{success:!0,children:"Success!"}:{warn:!0,loading:r,onClick:t,children:"Transfer and delete account"}}),pn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-aa2e65ff-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;width:100%;padding-bottom:16px;"]),yn=/*#__PURE__*/C.styled.div.withConfig({displayName:"GappedContainer",componentId:"sc-aa2e65ff-1"})(["display:flex;flex-direction:column;&& p{font-size:14px;}width:100%;gap:16px;"]),mn=/*#__PURE__*/C.styled.div.withConfig({displayName:"DisclosedAccountContainer",componentId:"sc-aa2e65ff-2"})(["display:flex;cursor:pointer;align-items:center;width:100%;border:1px solid var(--privy-color-foreground-4) !important;border-radius:var(--privy-border-radius-md);padding:8px 10px;font-size:14px;font-weight:500;gap:8px;"]),gn=/*#__PURE__*/C.styled(ke.default).withConfig({displayName:"StyledExclamationCircleIcon",componentId:"sc-aa2e65ff-3"})(["position:relative;width:",";height:",";color:var(--privy-color-foreground-3);margin-left:auto;"],(e=>`${e.iconSize}px`),(e=>`${e.iconSize}px`)),fn=/*#__PURE__*/C.styled(Ne.default).withConfig({displayName:"StyledCopyIcon",componentId:"sc-aa2e65ff-4"})(["position:relative;width:15px;height:15px;color:var(--privy-color-foreground-3);margin-left:auto;"]),wn=/*#__PURE__*/C.styled.ol.withConfig({displayName:"ListContainer",componentId:"sc-aa2e65ff-5"})(["display:flex;flex-direction:column;font-size:14px;width:100%;text-align:left;"]),vn=/*#__PURE__*/C.styled.li.withConfig({displayName:"ListItem",componentId:"sc-aa2e65ff-6"})(["font-size:14px;list-style-type:auto;list-style-position:outside;margin-left:1rem;margin-bottom:0.5rem;&:last-child{margin-bottom:0;}"]),Cn=/*#__PURE__*/C.styled.div.withConfig({displayName:"CircleContainer",componentId:"sc-aa2e65ff-7"})(["position:relative;width:60px;height:60px;margin:10px;display:flex;justify-content:center;align-items:center;"]);let xn=()=>/*#__PURE__*/e.jsx(Cn,{children:/*#__PURE__*/e.jsx(gn,{iconSize:60})});const En=({address:t,onClose:r,onRetry:n,onTransfer:a,isTransferring:i,transferSuccess:o})=>{let{defaultChain:l}=c.useAppConfig(),d=l.blockExplorers?.default.url??"https://etherscan.io";/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:r,backFn:n}),/*#__PURE__*/e.jsxs(pn,{children:[/*#__PURE__*/e.jsx(xn,{}),/*#__PURE__*/e.jsxs(yn,{children:[/*#__PURE__*/e.jsx("h3",{children:"Check account assets before transferring"}),/*#__PURE__*/e.jsx("p",{children:"Before transferring, ensure there are no assets in the other account. Assets in that account will not transfer automatically and may be lost."}),/*#__PURE__*/e.jsxs(wn,{children:[/*#__PURE__*/e.jsx("p",{children:" To check your balance, you can:"}),/*#__PURE__*/e.jsx(vn,{children:"Log out and log back into the other account, or "}),/*#__PURE__*/e.jsxs(vn,{children:["Copy your wallet address and use a"," ",/*#__PURE__*/e.jsx("u",{children:/*#__PURE__*/e.jsx("a",{target:"_blank",href:d,children:"block explorer"})})," ","to see if the account holds any assets."]})]}),/*#__PURE__*/e.jsxs(mn,{onClick:()=>navigator.clipboard.writeText(t).catch(console.error),children:[/*#__PURE__*/e.jsx(je.default,{color:"var(--privy-color-foreground-1)",strokeWidth:2,height:"28px",width:"28px"}),/*#__PURE__*/e.jsx(s.Address,{address:t,showCopyIcon:!1}),/*#__PURE__*/e.jsx(fn,{})]}),/*#__PURE__*/e.jsx(hn,{onTransfer:a,isTransferring:i,transferSuccess:o})]})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},Sn=({onClose:t,onContinue:r,onInfo:n,onTransfer:a,transferSuccess:i,isTransferring:o,data:l})=>{if(!l?.accountTransfer?.linkMethod||!l?.accountTransfer?.displayName)return;let c={method:l?.accountTransfer?.linkMethod,handle:l?.accountTransfer?.displayName,disclosedAccount:l?.accountTransfer?.embeddedWalletAddress?{type:"wallet",handle:l?.accountTransfer?.embeddedWalletAddress}:void 0};/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{closeable:!0}),/*#__PURE__*/e.jsxs(pn,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(dn,{color:"var(--privy-color-error)"}),/*#__PURE__*/e.jsx(Pe.default,{height:38,width:38,stroke:"var(--privy-color-error)"})]})}),/*#__PURE__*/e.jsxs(yn,{children:[/*#__PURE__*/e.jsxs("h3",{children:[function(e){switch(e){case"sms":return"Phone number";case"email":return"Email address";case"siwe":return"Wallet address";case"linkedin":return"LinkedIn profile";case"google":case"apple":case"discord":case"github":case"instagram":case"spotify":case"tiktok":case"twitter":case"telegram":case"farcaster":return`${Nt(e.replace("_oauth",""))} profile`;default:return e}}(c.method)," is associated with another account"]}),/*#__PURE__*/e.jsxs("p",{children:["Do you want to transfer",/*#__PURE__*/e.jsx("b",{children:c.handle?` ${c.handle}`:""})," to this account instead? This will delete your other account."]}),/*#__PURE__*/e.jsx(Tn,{onClick:n,disclosedAccount:c.disclosedAccount})]}),/*#__PURE__*/e.jsxs(yn,{style:{gap:12,marginTop:12},children:[l?.accountTransfer?.embeddedWalletAddress?/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:r,children:"Continue"}):/*#__PURE__*/e.jsx(hn,{onTransfer:a,transferSuccess:i,isTransferring:o}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:t,children:"No thanks"})]})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})};function Tn({disclosedAccount:t,onClick:r}){return t?/*#__PURE__*/e.jsxs(mn,{onClick:r,children:[/*#__PURE__*/e.jsx(je.default,{color:"var(--privy-color-foreground-1)",strokeWidth:2,height:"28px",width:"28px"}),/*#__PURE__*/e.jsx(s.Address,{address:t.handle,showCopyIcon:!1}),/*#__PURE__*/e.jsx(un,{width:15,height:15,color:"var(--privy-color-foreground-3)",style:{marginLeft:"auto"}})]}):null}const An=/*#__PURE__*/C.styled.div.withConfig({displayName:"AppLogoContainer",componentId:"sc-a63b1990-0"})(["display:flex;flex-direction:column;align-items:center;padding:0px 0px 30px;@media (max-width:440px){padding:10px 10px 20px;}"]),bn=/*#__PURE__*/C.styled.div.withConfig({displayName:"Title",componentId:"sc-a63b1990-1"})(["font-size:18px;line-height:30px;text-align:center;font-weight:600;margin-bottom:10px;"]),_n=/*#__PURE__*/C.styled.div.withConfig({displayName:"SubTitle",componentId:"sc-a63b1990-2"})(["font-size:0.875rem;text-align:center;"]),In=/*#__PURE__*/C.styled.div.withConfig({displayName:"Container",componentId:"sc-a63b1990-3"})(["display:flex;flex-direction:column;align-items:center;gap:10px;flex-grow:1;padding:20px 0;@media (max-width:440px){padding:10px 10px 20px;}"]),Pn=/*#__PURE__*/C.styled.div.withConfig({displayName:"List",componentId:"sc-a63b1990-4"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.75rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),jn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ListItemIcon",componentId:"sc-a63b1990-5"})(["width:25px;display:flex;align-items:center;justify-content:flex-start;> svg{z-index:2;height:25px !important;width:25px !important;color:var(--privy-color-accent);}"]),kn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ListItem",componentId:"sc-a63b1990-6"})(["display:flex;align-items:center;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;"]),Nn=/*#__PURE__*/C.styled.div.withConfig({displayName:"BottomSection",componentId:"sc-a63b1990-7"})(["display:flex;flex-direction:column;gap:10px;padding-top:20px;"]),Mn=/*#__PURE__*/C.styled.div.withConfig({displayName:"MethodList",componentId:"sc-a63b1990-8"})(["display:flex;flex-direction:column;align-items:stretch;gap:1rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),Rn=/*#__PURE__*/C.styled.div.withConfig({displayName:"MethodListItem",componentId:"sc-a63b1990-9"})(["display:flex;gap:5px;width:100%;position:relative;"]),On=/*#__PURE__*/C.styled.button.withConfig({displayName:"RemoveMethodButton",componentId:"sc-a63b1990-10"})(["&&{background-color:transparent;color:var(--privy-color-foreground-3);padding:0 0.75rem;display:flex;align-items:center;height:100%;> svg{z-index:2;height:20px !important;width:20px !important;}}&&:hover{color:var(--privy-color-error);}"]),Wn=/*#__PURE__*/C.styled.div.withConfig({displayName:"MethodText",componentId:"sc-a63b1990-11"})(["display:flex;align-items:center;gap:0.5rem;> svg{z-index:2;height:20px !important;width:20px !important;}"]),Ln=/*#__PURE__*/C.styled.div.withConfig({displayName:"ExtraText",componentId:"sc-a63b1990-12"})(["display:flex;align-items:center;gap:6px;font-weight:400 !important;color:",";> svg{z-index:2;height:18px !important;width:18px !important;display:flex !important;align-items:flex-end;}"],(e=>e.isAccent?"var(--privy-color-accent)":"var(--privy-color-foreground-3)")),Un=/*#__PURE__*/C.styled.div.withConfig({displayName:"SmsInsecureText",componentId:"sc-a63b1990-13"})(["width:100%;display:flex;justify-content:space-between;"]),Fn=/*#__PURE__*/C.styled.p.withConfig({displayName:"TermsText",componentId:"sc-a63b1990-14"})(["text-align:left;width:100%;color:var(--privy-color-foreground-3) !important;"]),Dn=/*#__PURE__*/C.styled.button.withConfig({displayName:"PrimaryTextButton",componentId:"sc-a63b1990-15"})(["display:flex;flex-direction:row;align-items:center;justify-content:center;user-select:none;&{width:100%;cursor:pointer;border-radius:var(--privy-border-radius-md);font-size:0.875rem;line-height:1rem;font-style:normal;font-weight:500;line-height:22px;letter-spacing:-0.016px;}&&{color:",";background-color:transparent;padding:0.5rem 0px;}&:hover{text-decoration:underline;}"],(e=>"dark"===e.theme?"var(--privy-color-foreground-2)":"var(--privy-color-accent)")),Bn=/*#__PURE__*/C.styled.div.withConfig({displayName:"IconWrapper",componentId:"sc-a63b1990-16"})(["display:flex;align-items:center;justify-content:center;color:var(--privy-color-accent);width:100%;> svg{z-index:2;width:3rem;height:3rem;}"]),Hn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ErrorMessage",componentId:"sc-a63b1990-17"})(["color:var(--privy-color-error);"]),zn=({termsAndConditionsUrl:t,privacyPolicyUrl:r,onAccept:n,onDecline:a})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{closeable:!1}),/*#__PURE__*/e.jsx(Re.default,{width:56,height:56,fill:"var(--privy-color-accent)",style:{margin:"auto"}}),/*#__PURE__*/e.jsx(bn,{style:{marginTop:24},children:"One last step"}),/*#__PURE__*/e.jsx(_n,{children:"By signing up, you agree to our terms and privacy policy."}),/*#__PURE__*/e.jsxs(Qr,{style:{marginTop:24},children:[t&&/*#__PURE__*/e.jsxs(nn,{target:"_blank",href:t,children:["View Terms ",/*#__PURE__*/e.jsx(Me.default,{style:{marginLeft:"auto"}})]}),r&&/*#__PURE__*/e.jsxs(nn,{target:"_blank",href:r,children:["View Privacy Policy ",/*#__PURE__*/e.jsx(Me.default,{style:{marginLeft:"auto"}})]})]}),/*#__PURE__*/e.jsxs(qn,{style:{marginTop:24},children:[/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:a,children:"No thanks"}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:n,children:"Accept"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let qn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ButtonsContainer",componentId:"sc-d601b243-0"})(["display:flex;gap:10px;"]);const Vn=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...r,children:/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",d:"M12 1.5a5.25 5.25 0 00-5.25 5.25v3a3 3 0 00-3 3v6.75a3 3 0 003 3h10.5a3 3 0 003-3v-6.75a3 3 0 00-3-3v-3c0-2.9-2.35-5.25-5.25-5.25zm3.75 8.25v-3a3.75 3.75 0 10-7.5 0v3h7.5z",clipRule:"evenodd"})});let Gn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-ed4ecf-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;padding-bottom:16px;"]),$n=/*#__PURE__*/C.styled.div.withConfig({displayName:"GappedContainer",componentId:"sc-ed4ecf-1"})(["display:flex;flex-direction:column;gap:8px;"]);const Kn=({title:t,description:r,children:n,...a})=>
1
+ "use strict";var e=require("react/jsx-runtime"),t=require("mipd"),r=require("react"),n=require("react-device-detect"),a=require("viem/utils"),i=require("./internal-context-DV3MljLU.js"),o=require("./paths-BGBZ-6Nl.js"),s=require("./useActiveWallet-CLPPplpC.js"),l=require("jose"),c=require("./useWallets-Dmyb5a0t.js"),d=require("./prepareFundingModalData-BCNQSbXb.js"),u=require("uuid"),h=require("eventemitter3"),p=require("@coinbase/wallet-sdk"),y=require("viem"),m=require("./getPublicClient-hVv5ZSWd.js"),g=require("ofetch"),f=require("js-cookie"),w=require("zustand"),v=require("@marsidev/react-turnstile"),C=require("styled-components"),x=require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),E=require("@heroicons/react/24/outline/ExclamationTriangleIcon"),S=require("@heroicons/react/24/outline/WalletIcon"),T=require("@heroicons/react/24/outline/ExclamationCircleIcon"),A=require("@heroicons/react/24/outline/Square2StackIcon"),b=require("@heroicons/react/24/outline/ArrowTopRightOnSquareIcon"),_=require("@heroicons/react/24/solid/DocumentCheckIcon"),I=require("@heroicons/react/20/solid/CheckIcon"),P=require("@heroicons/react/24/outline/EnvelopeIcon"),j=require("@heroicons/react/24/outline/PhoneIcon"),k=require("@heroicons/react/24/solid/CheckCircleIcon"),N=require("@heroicons/react/24/solid/XCircleIcon"),M=require("@heroicons/react/24/outline/CheckCircleIcon"),R=require("@heroicons/react/24/outline/CloudArrowUpIcon"),O=require("@heroicons/react/24/outline/NoSymbolIcon"),W=require("fast-password-entropy"),L=require("secure-password-utilities"),U=require("secure-password-utilities/wordlists"),F=require("@heroicons/react/24/outline/ArrowPathIcon"),D=require("@heroicons/react/24/outline/EyeIcon"),B=require("@heroicons/react/24/outline/EyeSlashIcon"),H=require("@heroicons/react/24/outline/KeyIcon"),z=require("@heroicons/react/24/outline/ArrowDownTrayIcon"),q=require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),V=require("@heroicons/react/24/outline/DocumentDuplicateIcon"),G=require("@heroicons/react/24/outline/UserCircleIcon"),$=require("@heroicons/react/24/solid/LockClosedIcon"),K=require("@privy-io/js-sdk-core"),Y=require("@headlessui/react"),Z=require("@heroicons/react/24/outline/ChevronDownIcon"),X=require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),Q=require("@heroicons/react/24/outline/CreditCardIcon"),J=require("@heroicons/react/24/outline/QrCodeIcon"),ee=require("@heroicons/react/24/outline/InformationCircleIcon"),te=require("@heroicons/react/24/outline/ChevronRightIcon"),re=require("@heroicons/react/24/outline/FingerPrintIcon"),ne=require("@heroicons/react/24/outline/ClockIcon"),ae=require("@heroicons/react/24/outline/TrashIcon"),ie=require("@heroicons/react/24/solid/CheckBadgeIcon"),oe=require("@heroicons/react/24/outline/ShieldCheckIcon"),se=require("@heroicons/react/24/solid/IdentificationIcon"),le=require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),ce=require("@heroicons/react/24/outline/MinusCircleIcon"),de=require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),ue=require("@heroicons/react/24/solid/ShieldCheckIcon"),he=require("@heroicons/react/24/outline/CalendarIcon"),pe=require("@heroicons/react/24/outline/GlobeAltIcon"),ye=require("@heroicons/react/24/outline/LockClosedIcon"),me=require("@heroicons/react/24/outline/PencilSquareIcon"),ge=require("@heroicons/react/24/outline"),fe=require("@heroicons/react/24/outline/ClipboardDocumentIcon"),we=require("./importWallet-CqIkwxB-.js"),ve=require("viem/experimental"),Ce=require("./getEmbeddedConnectedWallet-DTU4T9TJ.js");function xe(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function Ee(e){if(e&&"object"==typeof e&&"default"in e)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@walletconnect/ethereum-provider"),require("@heroicons/react/24/outline/CheckIcon"),require("qrcode"),require("zustand/shallow"),require("zustand/traditional"),require("tinycolor2");var Se=/*#__PURE__*/xe(r),Te=/*#__PURE__*/Ee(n),Ae=/*#__PURE__*/Ee(l),be=/*#__PURE__*/xe(h),_e=/*#__PURE__*/xe(f),Ie=/*#__PURE__*/xe(x),Pe=/*#__PURE__*/xe(E),je=/*#__PURE__*/xe(S),ke=/*#__PURE__*/xe(T),Ne=/*#__PURE__*/xe(A),Me=/*#__PURE__*/xe(b),Re=/*#__PURE__*/xe(_),Oe=/*#__PURE__*/xe(I),We=/*#__PURE__*/xe(P),Le=/*#__PURE__*/xe(j),Ue=/*#__PURE__*/xe(k),Fe=/*#__PURE__*/xe(N),De=/*#__PURE__*/xe(M),Be=/*#__PURE__*/xe(R),He=/*#__PURE__*/xe(O),ze=/*#__PURE__*/xe(W),qe=/*#__PURE__*/Ee(L),Ve=/*#__PURE__*/xe(F),Ge=/*#__PURE__*/xe(D),$e=/*#__PURE__*/xe(B),Ke=/*#__PURE__*/xe(H),Ye=/*#__PURE__*/xe(z),Ze=/*#__PURE__*/xe(q),Xe=/*#__PURE__*/xe(V),Qe=/*#__PURE__*/xe(G),Je=/*#__PURE__*/xe($),et=/*#__PURE__*/xe(Z),tt=/*#__PURE__*/xe(X),rt=/*#__PURE__*/xe(Q),nt=/*#__PURE__*/xe(J),at=/*#__PURE__*/xe(ee),it=/*#__PURE__*/xe(te),ot=/*#__PURE__*/xe(re),st=/*#__PURE__*/xe(ne),lt=/*#__PURE__*/xe(ae),ct=/*#__PURE__*/xe(ie),dt=/*#__PURE__*/xe(oe),ut=/*#__PURE__*/xe(se),ht=/*#__PURE__*/xe(le),pt=/*#__PURE__*/xe(ce),yt=/*#__PURE__*/xe(de),mt=/*#__PURE__*/xe(ue),gt=/*#__PURE__*/xe(he),ft=/*#__PURE__*/xe(pe),wt=/*#__PURE__*/xe(ye),vt=/*#__PURE__*/xe(me),Ct=/*#__PURE__*/xe(fe);class xt{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.customJwtAccountAuthenticatePath,{token:this.meta.token})}catch(e){throw i.formatApiError(e)}}async link(){throw Error("Unimplemented")}constructor(e){this.meta={token:e}}}function Et(e){return e?{"privy-ui":"t"}:void 0}class St{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new i.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessAuthenticatePath,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new i.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessLinkPath,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw i.formatApiError(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new i.PrivyClientError("Email must be set when initialzing authentication.");let n=Et(r);try{return await this.api.post(o.passwordlessInitPath,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw i.formatApiError(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class Tt extends St{async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new i.PrivyClientError("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(o.updateEmailPath,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw i.formatApiError(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class At{get meta(){return this._meta}async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new i.PrivyClientError("Auth flow must be initialized first");try{let e=await this.api.post(o.farcasterAuthenticatePath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});if(!e)throw new i.PrivyClientError("No response from authentication");return e}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.farcasterLinkPath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw i.formatApiError(e)}}async _startChannelOnce(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");let e=await this.api.post(o.farcasterInitPath,{token:this.captchaToken});n.isMobile&&!n.isIOS&&e.connect_uri&&s.openHref(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new i.PrivyClientError("Auth flow must be initialized first");let e=await this.api.get(o.farcasterStatusPath,{headers:{"farcaster-channel-token":this.meta.channelToken}});return"completed"===e.state&&(this.message=e.message,this.signature=e.signature,this.fid=e.fid,!0)}constructor(e,t=!1){this._meta={disableSignup:!1},this.captchaToken=e,this.startChannelOnce=new s.RunEffectOnce(this._startChannelOnce.bind(this)),this.pollForReady=new s.RunEffectOnce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function bt(e){return crypto.getRandomValues(new Uint8Array(e))}class _t{getOrCreateGuestCredential(e){let t=c.getGuestCredentialStorageKey(e);if(d.e()){if(d.s.get(t))return d.s.get(t);{let e=l.base64url.encode(bt(32));return d.s.put(t,e),e}}return l.base64url.encode(bt(32))}async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.guestAccountAuthenticatePath,{guest_credential:this.meta.guestCredential})}catch(e){throw i.formatApiError(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function It(){return l.base64url.encode(bt(36))}function Pt(){return It()}async function jt(e,t="S256"){if("S256"!=t)return e;{let t=await async function(e){let t=(new TextEncoder).encode(e);return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}(e);return l.base64url.encode(t)}}class kt{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new i.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new i.PrivyClientError("User denied confirmation during OAuth flow");let e=function(){let e=d.s.get(c.CODE_VERIFIER_KEY);if(!e)throw new i.PrivyClientError("Authentication error.");return e}();try{let t=await this.api.post(o.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return d.s.del(c.CODE_VERIFIER_KEY),d.s.del(c.HEADLESS_OAUTH_KEY),d.s.del(c.OAUTH_DISABLE_SIGNUP_KEY),t}catch(e){let t=i.formatApiError(e);if(t.privyErrorCode)throw new i.PrivyClientError(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new i.PrivyClientError("Invalid code during oauth flow.",void 0,i.PrivyErrorCode.OAUTH_USER_DENIED);throw new i.PrivyClientError("Invalid code during OAuth flow.",void 0,i.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new i.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new i.PrivyClientError("User denied confirmation during OAuth flow");let e=d.s.get(c.CODE_VERIFIER_KEY);if(!e)throw new i.PrivyClientError("Authentication error.");try{let t=await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return d.s.del(c.CODE_VERIFIER_KEY),t}catch(e){throw i.formatApiError(e)}}async getAuthorizationUrl(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.provider)throw new i.PrivyClientError("Provider must be set when initializing OAuth authentication.");let e=It();d.s.put(c.CODE_VERIFIER_KEY,e);let t=Pt();d.s.put(c.STATE_CODE_KEY,t);let r=await jt(e);this.meta.withPrivyUi||d.s.put(c.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup&&d.s.put(c.OAUTH_DISABLE_SIGNUP_KEY,!0);let n=Et(this.meta.withPrivyUi);try{return await this.api.post(o.oAuthInitPath,{provider:this.meta.provider,redirect_to:window.location.href,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw i.formatApiError(e)}}constructor(e){this.meta=e}}function Nt(e){return e.charAt(0).toUpperCase()+e.slice(1)}const Mt=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 24 24",style:{height:"24px",...t},...r,children:[/*#__PURE__*/e.jsx("path",{d:"M17.0722 11.6888C17.0471 8.90571 19.3263 7.56847 19.429 7.50274C18.1466 5.60938 16.153 5.35154 15.4417 5.3212C13.7461 5.14678 12.1306 6.32982 11.269 6.32982C10.4074 6.32982 9.08004 5.34648 7.67246 5.37429C5.82158 5.40209 4.11595 6.45874 3.16171 8.13218C1.24068 11.4942 2.6708 16.4817 4.54423 19.2143C5.46091 20.549 6.55041 22.0531 7.98554 21.9975C9.36803 21.9419 9.88905 21.095 11.5571 21.095C13.2251 21.095 13.696 21.9975 15.1537 21.9697C16.6389 21.9393 17.5806 20.6046 18.4897 19.2648C19.5392 17.7153 19.9725 16.2137 19.9975 16.1354C19.965 16.1228 17.1022 15.0155 17.0722 11.6888Z",fill:"currentColor"}),/*#__PURE__*/e.jsx("path",{d:"M14.3295 3.51373C15.0909 2.58347 15.6043 1.28921 15.4641 0C14.3671 0.0455014 13.0396 0.738135 12.2532 1.66838C11.5494 2.48994 10.9307 3.80695 11.0986 5.07089C12.3183 5.16694 13.5681 4.44145 14.3295 3.51373Z",fill:"currentColor"})]}),Rt=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 71 55",style:{height:"24px",...t},...r,children:[/*#__PURE__*/e.jsx("g",{clipPath:"url(#clip0)",children:/*#__PURE__*/e.jsx("path",{d:"M60.1045 4.8978C55.5792 2.8214 50.7265 1.2916 45.6527 0.41542C45.5603 0.39851 45.468 0.440769 45.4204 0.525289C44.7963 1.6353 44.105 3.0834 43.6209 4.2216C38.1637 3.4046 32.7345 3.4046 27.3892 4.2216C26.905 3.0581 26.1886 1.6353 25.5617 0.525289C25.5141 0.443589 25.4218 0.40133 25.3294 0.41542C20.2584 1.2888 15.4057 2.8186 10.8776 4.8978C10.8384 4.9147 10.8048 4.9429 10.7825 4.9795C1.57795 18.7309 -0.943561 32.1443 0.293408 45.3914C0.299005 45.4562 0.335386 45.5182 0.385761 45.5576C6.45866 50.0174 12.3413 52.7249 18.1147 54.5195C18.2071 54.5477 18.305 54.5139 18.3638 54.4378C19.7295 52.5728 20.9469 50.6063 21.9907 48.5383C22.0523 48.4172 21.9935 48.2735 21.8676 48.2256C19.9366 47.4931 18.0979 46.6 16.3292 45.5858C16.1893 45.5041 16.1781 45.304 16.3068 45.2082C16.679 44.9293 17.0513 44.6391 17.4067 44.3461C17.471 44.2926 17.5606 44.2813 17.6362 44.3151C29.2558 49.6202 41.8354 49.6202 53.3179 44.3151C53.3935 44.2785 53.4831 44.2898 53.5502 44.3433C53.9057 44.6363 54.2779 44.9293 54.6529 45.2082C54.7816 45.304 54.7732 45.5041 54.6333 45.5858C52.8646 46.6197 51.0259 47.4931 49.0921 48.2228C48.9662 48.2707 48.9102 48.4172 48.9718 48.5383C50.038 50.6034 51.2554 52.5699 52.5959 54.435C52.6519 54.5139 52.7526 54.5477 52.845 54.5195C58.6464 52.7249 64.529 50.0174 70.6019 45.5576C70.6551 45.5182 70.6887 45.459 70.6943 45.3942C72.1747 30.0791 68.2147 16.7757 60.1968 4.9823C60.1772 4.9429 60.1437 4.9147 60.1045 4.8978ZM23.7259 37.3253C20.2276 37.3253 17.3451 34.1136 17.3451 30.1693C17.3451 26.225 20.1717 23.0133 23.7259 23.0133C27.308 23.0133 30.1626 26.2532 30.1066 30.1693C30.1066 34.1136 27.28 37.3253 23.7259 37.3253ZM47.3178 37.3253C43.8196 37.3253 40.9371 34.1136 40.9371 30.1693C40.9371 26.225 43.7636 23.0133 47.3178 23.0133C50.9 23.0133 53.7545 26.2532 53.6986 30.1693C53.6986 34.1136 50.9 37.3253 47.3178 37.3253Z",fill:"#5865F2"})}),/*#__PURE__*/e.jsx("defs",{children:/*#__PURE__*/e.jsx("clipPath",{id:"clip0",children:/*#__PURE__*/e.jsx("rect",{width:"71",height:"55",fill:"white"})})})]}),Ot=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"24",y:"24",viewBox:"0 0 98 96",style:{height:"24px",...t},...r,children:/*#__PURE__*/e.jsx("path",{d:"M48.854 0C21.839 0 0 22 0 49.217c0 21.756 13.993 40.172 33.405 46.69 2.427.49 3.316-1.059 3.316-2.362 0-1.141-.08-5.052-.08-9.127-13.59 2.934-16.42-5.867-16.42-5.867-2.184-5.704-5.42-7.17-5.42-7.17-4.448-3.015.324-3.015.324-3.015 4.934.326 7.523 5.052 7.523 5.052 4.367 7.496 11.404 5.378 14.235 4.074.404-3.178 1.699-5.378 3.074-6.6-10.839-1.141-22.243-5.378-22.243-24.283 0-5.378 1.94-9.778 5.014-13.2-.485-1.222-2.184-6.275.486-13.038 0 0 4.125-1.304 13.426 5.052a46.97 46.97 0 0 1 12.214-1.63c4.125 0 8.33.571 12.213 1.63 9.302-6.356 13.427-5.052 13.427-5.052 2.67 6.763.97 11.816.485 13.038 3.155 3.422 5.015 7.822 5.015 13.2 0 18.905-11.404 23.06-22.324 24.283 1.78 1.548 3.316 4.481 3.316 9.126 0 6.6-.08 11.897-.08 13.526 0 1.304.89 2.853 3.316 2.364 19.412-6.52 33.405-24.935 33.405-46.691C97.707 22 75.788 0 48.854 0z",fill:"currentColor"})}),Wt=({style:t})=>/*#__PURE__*/e.jsx(ft.default,{style:{color:"var(--privy-color-error)",...t}}),Lt=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"26px",width:"26px",...t},...r,children:[/*#__PURE__*/e.jsx("path",{d:"M22.56 12.25C22.56 11.47 22.49 10.72 22.36 10H12V14.255H17.92C17.665 15.63 16.89 16.795 15.725 17.575V20.335H19.28C21.36 18.42 22.56 15.6 22.56 12.25Z",fill:"#4285F4"}),/*#__PURE__*/e.jsx("path",{d:"M12 23C14.97 23 17.46 22.015 19.28 20.335L15.725 17.575C14.74 18.235 13.48 18.625 12 18.625C9.13504 18.625 6.71004 16.69 5.84504 14.09H2.17004V16.94C3.98004 20.535 7.70004 23 12 23Z",fill:"#34A853"}),/*#__PURE__*/e.jsx("path",{d:"M5.845 14.09C5.625 13.43 5.5 12.725 5.5 12C5.5 11.275 5.625 10.57 5.845 9.91V7.06H2.17C1.4 8.59286 0.999321 10.2846 1 12C1 13.775 1.425 15.455 2.17 16.94L5.845 14.09Z",fill:"#FBBC05"}),/*#__PURE__*/e.jsx("path",{d:"M12 5.375C13.615 5.375 15.065 5.93 16.205 7.02L19.36 3.865C17.455 2.09 14.965 1 12 1C7.70004 1 3.98004 3.465 2.17004 7.06L5.84504 9.91C6.71004 7.31 9.13504 5.375 12 5.375Z",fill:"#EA4335"})]});function Ut(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",width:26,height:26,viewBox:"0 0 140 140",x:"0px",y:"0px",fill:"none",...t,children:[/*#__PURE__*/e.jsxs("defs",{children:[/*#__PURE__*/e.jsxs("linearGradient",{id:"b",children:[/*#__PURE__*/e.jsx("stop",{offset:"0",stopColor:"#3771c8"}),/*#__PURE__*/e.jsx("stop",{stopColor:"#3771c8",offset:".128"}),/*#__PURE__*/e.jsx("stop",{offset:"1",stopColor:"#60f",stopOpacity:"0"})]}),/*#__PURE__*/e.jsxs("linearGradient",{id:"a",children:[/*#__PURE__*/e.jsx("stop",{offset:"0",stopColor:"#fd5"}),/*#__PURE__*/e.jsx("stop",{offset:".1",stopColor:"#fd5"}),/*#__PURE__*/e.jsx("stop",{offset:".5",stopColor:"#ff543e"}),/*#__PURE__*/e.jsx("stop",{offset:"1",stopColor:"#c837ab"})]}),/*#__PURE__*/e.jsx("radialGradient",{id:"c",cx:"158.429",cy:"578.088",r:"65",xlinkHref:"#a",gradientUnits:"userSpaceOnUse",gradientTransform:"matrix(0 -1.98198 1.8439 0 -1031.402 454.004)",fx:"158.429",fy:"578.088"}),/*#__PURE__*/e.jsx("radialGradient",{id:"d",cx:"147.694",cy:"473.455",r:"65",xlinkHref:"#b",gradientUnits:"userSpaceOnUse",gradientTransform:"matrix(.17394 .86872 -3.5818 .71718 1648.348 -458.493)",fx:"147.694",fy:"473.455"})]}),/*#__PURE__*/e.jsx("path",{fill:"url(#c)",d:"M65.03 0C37.888 0 29.95.028 28.407.156c-5.57.463-9.036 1.34-12.812 3.22-2.91 1.445-5.205 3.12-7.47 5.468C4 13.126 1.5 18.394.595 24.656c-.44 3.04-.568 3.66-.594 19.188-.01 5.176 0 11.988 0 21.125 0 27.12.03 35.05.16 36.59.45 5.42 1.3 8.83 3.1 12.56 3.44 7.14 10.01 12.5 17.75 14.5 2.68.69 5.64 1.07 9.44 1.25 1.61.07 18.02.12 34.44.12 16.42 0 32.84-.02 34.41-.1 4.4-.207 6.955-.55 9.78-1.28 7.79-2.01 14.24-7.29 17.75-14.53 1.765-3.64 2.66-7.18 3.065-12.317.088-1.12.125-18.977.125-36.81 0-17.836-.04-35.66-.128-36.78-.41-5.22-1.305-8.73-3.127-12.44-1.495-3.037-3.155-5.305-5.565-7.624C116.9 4 111.64 1.5 105.372.596 102.335.157 101.73.027 86.19 0H65.03z",transform:"translate(1.004 1)"}),/*#__PURE__*/e.jsx("path",{fill:"url(#d)",d:"M65.03 0C37.888 0 29.95.028 28.407.156c-5.57.463-9.036 1.34-12.812 3.22-2.91 1.445-5.205 3.12-7.47 5.468C4 13.126 1.5 18.394.595 24.656c-.44 3.04-.568 3.66-.594 19.188-.01 5.176 0 11.988 0 21.125 0 27.12.03 35.05.16 36.59.45 5.42 1.3 8.83 3.1 12.56 3.44 7.14 10.01 12.5 17.75 14.5 2.68.69 5.64 1.07 9.44 1.25 1.61.07 18.02.12 34.44.12 16.42 0 32.84-.02 34.41-.1 4.4-.207 6.955-.55 9.78-1.28 7.79-2.01 14.24-7.29 17.75-14.53 1.765-3.64 2.66-7.18 3.065-12.317.088-1.12.125-18.977.125-36.81 0-17.836-.04-35.66-.128-36.78-.41-5.22-1.305-8.73-3.127-12.44-1.495-3.037-3.155-5.305-5.565-7.624C116.9 4 111.64 1.5 105.372.596 102.335.157 101.73.027 86.19 0H65.03z",transform:"translate(1.004 1)"}),/*#__PURE__*/e.jsx("path",{fill:"#fff",d:"M66.004 18c-13.036 0-14.672.057-19.792.29-5.11.234-8.598 1.043-11.65 2.23-3.157 1.226-5.835 2.866-8.503 5.535-2.67 2.668-4.31 5.346-5.54 8.502-1.19 3.053-2 6.542-2.23 11.65C18.06 51.327 18 52.964 18 66s.058 14.667.29 19.787c.235 5.11 1.044 8.598 2.23 11.65 1.227 3.157 2.867 5.835 5.536 8.503 2.667 2.67 5.345 4.314 8.5 5.54 3.054 1.187 6.543 1.996 11.652 2.23 5.12.233 6.755.29 19.79.29 13.037 0 14.668-.057 19.788-.29 5.11-.234 8.602-1.043 11.656-2.23 3.156-1.226 5.83-2.87 8.497-5.54 2.67-2.668 4.31-5.346 5.54-8.502 1.18-3.053 1.99-6.542 2.23-11.65.23-5.12.29-6.752.29-19.788 0-13.036-.06-14.672-.29-19.792-.24-5.11-1.05-8.598-2.23-11.65-1.23-3.157-2.87-5.835-5.54-8.503-2.67-2.67-5.34-4.31-8.5-5.535-3.06-1.187-6.55-1.996-11.66-2.23-5.12-.233-6.75-.29-19.79-.29zm-4.306 8.65c1.278-.002 2.704 0 4.306 0 12.816 0 14.335.046 19.396.276 4.68.214 7.22.996 8.912 1.653 2.24.87 3.837 1.91 5.516 3.59 1.68 1.68 2.72 3.28 3.592 5.52.657 1.69 1.44 4.23 1.653 8.91.23 5.06.28 6.58.28 19.39s-.05 14.33-.28 19.39c-.214 4.68-.996 7.22-1.653 8.91-.87 2.24-1.912 3.835-3.592 5.514-1.68 1.68-3.275 2.72-5.516 3.59-1.69.66-4.232 1.44-8.912 1.654-5.06.23-6.58.28-19.396.28-12.817 0-14.336-.05-19.396-.28-4.68-.216-7.22-.998-8.913-1.655-2.24-.87-3.84-1.91-5.52-3.59-1.68-1.68-2.72-3.276-3.592-5.517-.657-1.69-1.44-4.23-1.653-8.91-.23-5.06-.276-6.58-.276-19.398s.046-14.33.276-19.39c.214-4.68.996-7.22 1.653-8.912.87-2.24 1.912-3.84 3.592-5.52 1.68-1.68 3.28-2.72 5.52-3.592 1.692-.66 4.233-1.44 8.913-1.655 4.428-.2 6.144-.26 15.09-.27zm29.928 7.97c-3.18 0-5.76 2.577-5.76 5.758 0 3.18 2.58 5.76 5.76 5.76 3.18 0 5.76-2.58 5.76-5.76 0-3.18-2.58-5.76-5.76-5.76zm-25.622 6.73c-13.613 0-24.65 11.037-24.65 24.65 0 13.613 11.037 24.645 24.65 24.645C79.617 90.645 90.65 79.613 90.65 66S79.616 41.35 66.003 41.35zm0 8.65c8.836 0 16 7.163 16 16 0 8.836-7.164 16-16 16-8.837 0-16-7.164-16-16 0-8.837 7.163-16 16-16z"})]})}function Ft({style:t,...r}){/*#__PURE__*/return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",viewBox:"0,0,256,256",style:{height:"26px",width:"26px",...t},...r,children:/*#__PURE__*/e.jsx("g",{fill:"#0077b5",strokeWidth:"1",strokeLinecap:"butt",strokeLinejoin:"miter",strokeMiterlimit:"10",style:{mixBlendMode:"normal"},children:/*#__PURE__*/e.jsx("g",{transform:"scale(5.12,5.12)",children:/*#__PURE__*/e.jsx("path",{d:"M41,4h-32c-2.76,0 -5,2.24 -5,5v32c0,2.76 2.24,5 5,5h32c2.76,0 5,-2.24 5,-5v-32c0,-2.76 -2.24,-5 -5,-5zM17,20v19h-6v-19zM11,14.47c0,-1.4 1.2,-2.47 3,-2.47c1.8,0 2.93,1.07 3,2.47c0,1.4 -1.12,2.53 -3,2.53c-1.8,0 -3,-1.13 -3,-2.53zM39,39h-6c0,0 0,-9.26 0,-10c0,-2 -1,-4 -3.5,-4.04h-0.08c-2.42,0 -3.42,2.06 -3.42,4.04c0,0.91 0,10 0,10h-6v-19h6v2.56c0,0 1.93,-2.56 5.81,-2.56c3.97,0 7.19,2.73 7.19,8.26z"})})})})}function Dt(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 496 512",...t,children:[/*#__PURE__*/e.jsx("path",{fill:"#1ed760",d:"M248 8C111.1 8 0 119.1 0 256s111.1 248 248 248 248-111.1 248-248S384.9 8 248 8Z"}),/*#__PURE__*/e.jsx("path",{d:"M406.6 231.1c-5.2 0-8.4-1.3-12.9-3.9-71.2-42.5-198.5-52.7-280.9-29.7-3.6 1-8.1 2.6-12.9 2.6-13.2 0-23.3-10.3-23.3-23.6 0-13.6 8.4-21.3 17.4-23.9 35.2-10.3 74.6-15.2 117.5-15.2 73 0 149.5 15.2 205.4 47.8 7.8 4.5 12.9 10.7 12.9 22.6 0 13.6-11 23.3-23.2 23.3zm-31 76.2c-5.2 0-8.7-2.3-12.3-4.2-62.5-37-155.7-51.9-238.6-29.4-4.8 1.3-7.4 2.6-11.9 2.6-10.7 0-19.4-8.7-19.4-19.4s5.2-17.8 15.5-20.7c27.8-7.8 56.2-13.6 97.8-13.6 64.9 0 127.6 16.1 177 45.5 8.1 4.8 11.3 11 11.3 19.7-.1 10.8-8.5 19.5-19.4 19.5zm-26.9 65.6c-4.2 0-6.8-1.3-10.7-3.6-62.4-37.6-135-39.2-206.7-24.5-3.9 1-9 2.6-11.9 2.6-9.7 0-15.8-7.7-15.8-15.8 0-10.3 6.1-15.2 13.6-16.8 81.9-18.1 165.6-16.5 237 26.2 6.1 3.9 9.7 7.4 9.7 16.5s-7.1 15.4-15.2 15.4z"})]})}function Bt(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fillRule:"evenodd",clipRule:"evenodd",imageRendering:"optimizeQuality",shapeRendering:"geometricPrecision",textRendering:"geometricPrecision",viewBox:"0 0 293768 333327",width:24,height:24,...t,children:[/*#__PURE__*/e.jsx("path",{fill:"#26f4ee",d:"M204958 0c5369 45832 32829 78170 77253 81022v43471l-287 27V87593c-44424-2850-69965-30183-75333-76015l-47060-1v192819c6791 86790-60835 89368-86703 56462 30342 18977 79608 6642 73766-68039V0h58365zM78515 319644c-26591-5471-50770-21358-64969-44588-34496-56437-3401-148418 96651-157884v54345l-164 27v-40773C17274 145544 7961 245185 33650 286633c9906 15984 26169 27227 44864 33011z"}),/*#__PURE__*/e.jsx("path",{fill:"#fb2c53",d:"M218434 11587c3505 29920 15609 55386 35948 70259-27522-10602-43651-34934-47791-70262l11843 3zm63489 82463c3786 804 7734 1348 11844 1611v51530c-25770 2537-48321-5946-74600-21749l4034 88251c0 28460 106 41467-15166 67648-34260 58734-95927 63376-137628 35401 54529 22502 137077-4810 136916-103049v-96320c26279 15803 48830 24286 74600 21748V94050zm-171890 37247c5390-1122 11048-1985 16998-2548v54345c-21666 3569-35427 10222-41862 22528-20267 38754 5827 69491 35017 74111-33931 5638-73721-28750-49999-74111 6434-12304 18180-18959 39846-22528v-51797zm64479-119719h1808-1808z"}),/*#__PURE__*/e.jsx("path",{d:"M206590 11578c5369 45832 30910 73164 75333 76015v51528c-25770 2539-48321-5945-74600-21748v96320c206 125717-135035 135283-173673 72939-25688-41449-16376-141089 76383-155862v52323c-21666 3569-33412 10224-39846 22528-39762 76035 98926 121273 89342-1225V11577l47060 1z",fill:"#000000"})]})}const Ht=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"24px",width:"24px",...t},...r,children:/*#__PURE__*/e.jsx("path",{d:"M 14.285156 10.171875 L 23.222656 0 L 21.105469 0 L 13.34375 8.832031 L 7.148438 0 L 0 0 L 9.371094 13.355469 L 0 24.019531 L 2.117188 24.019531 L 10.308594 14.691406 L 16.851562 24.019531 L 24 24.019531 M 2.878906 1.5625 L 6.132812 1.5625 L 21.101562 22.535156 L 17.851562 22.535156",fill:"currentColor"})});let zt={google:{name:"Google",component:Lt},discord:{name:"Discord",component:Rt},github:{name:"Github",component:Ot},linkedin:{name:"LinkedIn",component:Ft},twitter:{name:"Twitter",component:Ht},spotify:{name:"Spotify",component:Dt},instagram:{name:"Instagram",component:Ut},tiktok:{name:"Tiktok",component:Bt},apple:{name:"Apple",component:Mt}};const qt=e=>e in zt?zt[e]:{name:"Unknown",component:Wt};function Vt(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),n=e.get("privy_oauth_provider");if(!t||!r||!n)return{inProgress:!1};let a=!1;try{a=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:n,withPrivyUi:!d.s.get(c.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&a,disableSignup:!!d.s.get(c.OAUTH_DISABLE_SIGNUP_KEY)}}function Gt(){let e=new URL(window.location.href);e.searchParams.delete("privy_oauth_code"),e.searchParams.delete("privy_oauth_provider"),e.searchParams.delete("privy_oauth_state"),d.s.del(c.STATE_CODE_KEY),window.history.replaceState({},"",e)}class $t{async initRegisterFlow(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!0,this.meta.initRegisterResponse=await this.initRegisterOnce.execute(e)}async initAuthenticationFlow(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async register(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new i.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,r=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(o.passkeyRegisterPath,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new i.PrivyClientError("Passkey request timed out or rejected by user.",void 0,i.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw i.formatApiError(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new i.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());let t=this.meta.allowedCredentialsIds?.map((e=>({type:"public-key",id:e})))??this.meta.initAuthenticateResponse.options.allow_credentials;try{let r=await e.startAuthentication(this._transformInitAuthenticateOptionsToCamelCase({...this.meta.initAuthenticateResponse.options,allow_credentials:t}));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(o.passkeyAuthenticatePath,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new i.PrivyClientError("Passkey request timed out or rejected by user.",void 0,i.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw i.formatApiError(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new i.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,r=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(o.passkeyLinkPath,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new i.PrivyClientError("Passkey request timed out or rejected by user.",void 0,i.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw i.formatApiError(e)}}async _initRegisterOnce(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");let t=Et(e);return await this.api.post(o.passkeyInitRegisterPath,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");let t=Et(e);return await this.api.post(o.passkeyInitAuthenticatePath,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");return await this.api.post(o.passkeyInitLinkPath,{})}_transformInitLinkOptionsToCamelCase(e){return{rp:e.rp,user:{id:e.user.id,name:e.user.name,displayName:e.user.display_name},challenge:e.challenge,pubKeyCredParams:e.pub_key_cred_params.map((e=>({type:e.type,alg:e.alg}))),timeout:e.timeout,excludeCredentials:e.exclude_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports}))),authenticatorSelection:{authenticatorAttachment:e.authenticator_selection?.authenticator_attachment,requireResidentKey:e.authenticator_selection?.require_resident_key,residentKey:e.authenticator_selection?.resident_key,userVerification:e.authenticator_selection?.user_verification},attestation:e.attestation,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props?.rk,hmacCreateSecret:e.extensions?.hmac_create_secret}}}_transformRegistrationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}_transformInitAuthenticateOptionsToCamelCase(e){return{rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}}_transformAuthenticationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}constructor({captchaToken:e,setPasskeyAuthState:t}){this.authenticateForRegistration=!1,this.initRegisterOnce=new s.RunEffectOnce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new s.RunEffectOnce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new s.RunEffectOnce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t}}}class Kt{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new i.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsAuthenticatePath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new i.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsLinkPath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw i.formatApiError(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new i.PrivyClientError("phone nNumber must be set when initialzing authentication.");let n=Et(r);try{return await this.api.post(o.passwordlessSmsInitPath,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw i.formatApiError(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class Yt extends Kt{async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new i.PrivyClientError("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(o.updatePhonePath,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw i.formatApiError(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class Zt{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.telegramAccountAuthenticatePath,{captcha_token:this.meta.captchaToken,telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.telegramAccountLinkPath,{telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData})}catch(e){throw i.formatApiError(e)}}constructor(e,t=!1){this.meta={disableSignup:!1},this.meta={captchaToken:e,disableSignup:!1},this.meta.disableSignup=t}}function Xt(e){let t={detail:"",retryable:!1};return e?.privyErrorCode===i.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(t.detail="This account has already been linked to another user."),e?.privyErrorCode===i.PrivyErrorCode.DISALLOWED_LOGIN_METHOD&&(t.detail="Login with Telegram not allowed."),e?.privyErrorCode===i.PrivyErrorCode.INVALID_DATA&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===i.PrivyErrorCode.INVALID_CREDENTIALS&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&(t.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("rate limit")&&(t.detail="Request limit reached for Telegram. Please wait a moment and try again."),e instanceof s.CaptchaError&&(t.retryable=!0,t.detail="Something went wrong. Try again."),t}function Qt(e){return Object.fromEntries(decodeURIComponent(e).split("&").map((e=>e.split("=").map(decodeURIComponent))))}function Jt(){let e=new URL(window.location.href);e.searchParams.delete("id"),e.searchParams.delete("hash"),e.searchParams.delete("auth_date"),e.searchParams.delete("first_name"),e.searchParams.delete("last_name"),e.searchParams.delete("username"),e.searchParams.delete("photo_url"),e.hash="",window.history.replaceState({},"",e)}class er{static parse(e){try{return new er(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return Ae.decodeJwt(e),e}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=1e3*(this.expiration-e)}constructor(e){this.value=e,this._decoded=Ae.decodeJwt(e)}}class tr extends er{static parse(e){try{return new tr(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}const rr=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{viewBox:"0 0 1024 1024",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("rect",{width:"1024",height:"1024",fill:"#0052FF",rx:100,ry:100}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z",fill:"white"})]});let nr,ar=[1,11155111,137,10,8453,84532,42161,7777777,43114,56],ir=(e,t)=>e.makeWeb3Provider({options:t});class or extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:"data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyBmaWxsPSdub25lJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHN0eWxlPSdoZWlnaHQ6MjhweDt3aWR0aDoyOHB4Jz48cmVjdCB3aWR0aD0nMTAyNCcgaGVpZ2h0PScxMDI0JyBmaWxsPScjMDA1MkZGJyByeD0nMTAwJyByeT0nMTAwJz48L3JlY3Q+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBjbGlwLXJ1bGU9J2V2ZW5vZGQnIGQ9J00xNTIgNTEyQzE1MiA3MTAuODIzIDMxMy4xNzcgODcyIDUxMiA4NzJDNzEwLjgyMyA4NzIgODcyIDcxMC44MjMgODcyIDUxMkM4NzIgMzEzLjE3NyA3MTAuODIzIDE1MiA1MTIgMTUyQzMxMy4xNzcgMTUyIDE1MiAzMTMuMTc3IDE1MiA1MTJaTTQyMCAzOTZDNDA2Ljc0NSAzOTYgMzk2IDQwNi43NDUgMzk2IDQyMFY2MDRDMzk2IDYxNy4yNTUgNDA2Ljc0NSA2MjggNDIwIDYyOEg2MDRDNjE3LjI1NSA2MjggNjI4IDYxNy4yNTUgNjI4IDYwNFY0MjBDNjI4IDQwNi43NDUgNjE3LjI1NSAzOTYgNjA0IDM5Nkg0MjBaJyBmaWxsPSd3aGl0ZSc+PC9wYXRoPjwvc3ZnPg==",id:"com.coinbase.wallet"}}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}updateConnectionPreference(e){this.connectionOptions=e,this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",this.proxyProvider.setWalletProvider(ir(nr,this.connectionOptions))}constructor(e,t,r,n,a,i){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.connectionOptions=n.coinbaseWallet.connectionOptions??"all",this.walletClientType="smartWalletOnly"===this.connectionOptions?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!nr){let r=[t.id].concat(e.map((e=>e.id))),n="eoaOnly"!==this.connectionOptions?r.filter((e=>!ar.includes(e))):[];n.length>0&&!n.every((e=>c.DEFAULT_SUPPORTED_CHAIN_IDS.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${n.join(", ")}`),nr=new p.CoinbaseWalletSDK({appName:a,appLogoUrl:i,appChainIds:r})}this.proxyProvider.setWalletProvider(ir(nr,this.connectionOptions))}}const sr=({...t})=>/*#__PURE__*/e.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t,children:/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M2.37126 11.0323C2.37126 12.696 3.90598 13.4421 5.40654 13.4468C8.91753 13.4468 12.8021 11.2897 12.7819 7.67984C12.7673 5.07728 10.3748 2.86167 7.54357 2.88296C4.8495 2.88296 2.21821 4.6411 2.21803 7.03628C2.21803 7.67951 2.58722 8.30178 3.55231 8.37184C2.74763 9.16826 2.37126 10.1225 2.37126 11.0323ZM7.55283 8.68012C8.11562 8.68012 8.57186 8.13217 8.57186 7.45624C8.57186 6.78032 8.11562 6.23237 7.55283 6.23237C6.99003 6.23237 6.53379 6.78032 6.53379 7.45624C6.53379 8.13217 6.99003 8.68012 7.55283 8.68012ZM10.4747 8.68012C11.0375 8.68012 11.4937 8.13217 11.4937 7.45625C11.4937 6.78032 11.0375 6.23237 10.4747 6.23237C9.91186 6.23237 9.45562 6.78032 9.45562 7.45625C9.45562 8.13217 9.91186 8.68012 10.4747 8.68012Z",fill:t.color||"var(--privy-color-foreground-3)"})});class lr extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[s.toHex(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:sr,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:r,rpcConfig:n,imported:a,walletIndex:i}){super("privy",t,r,n),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=i,a&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}const cr=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];let dr={0:"legacy",1:"eip2930",2:"eip1559",3:"eip4844"};const ur={legacy:0,eip2930:1,eip1559:2,eip4844:3};let hr=e=>void 0!==e?BigInt(e):void 0;function pr(e){let t,{type:r=2,...n}=e;n.accessList&&Array.isArray(n.accessList)?t=n.accessList.map((e=>Array.isArray(e)?{address:e[0],storageKeys:e[1]}:e)):n.accessList&&(t=Object.entries(n.accessList).map((e=>({address:e[0],storageKeys:e[1]}))));let a=Number(n.chainId??1),o=y.isHex(n.data)?n.data:n.data?y.toHex(Uint8Array.from(n.data)):void 0,s=n.nonce?Number(n.nonce):void 0,l={chainId:a,data:o,nonce:s,value:hr(n.value),gas:hr(n.gas??n.gasLimit)},c=Number(r);if(0===c)return{...n,type:dr[c],...l,gasPrice:hr(n.gasPrice),accessList:void 0,maxFeePerGas:void 0,maxPriorityFeePerGas:void 0};if(1===c)return{...n,type:dr[c],...l,gasPrice:hr(n.gasPrice),accessList:t,maxFeePerGas:void 0,maxPriorityFeePerGas:void 0};if(2===c)return{...n,type:dr[c],...l,nonce:s,accessList:t,maxFeePerGas:hr(n.maxFeePerGas),maxPriorityFeePerGas:hr(n.maxPriorityFeePerGas),gasPrice:void 0,maxFeePerBlobGas:void 0};throw new i.PrivyClientError(`Unsupported transaction type: ${r}`)}class yr extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class mr extends be.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new yr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Qh()||!this.address)throw new yr("Disconnected",4900);let{hash:r}=await rp(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new yr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Qh()||!this.address)throw new yr("Disconnected",4900);let{signature:r}=await tp(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new yr(`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 yr(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=m.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:n}=await Jh({message:t},{address:r});return n}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:n}=await ep(s.generateTypedDataWithDomainType(r),{address:t});return n}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:s.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...pr(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 s.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(!(e=>cr.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await Qh();if(await np(),!t||!this.address)throw new yr("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 yr("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:a,chains:i,appId:o,chainId:l=1,walletIndex:c}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=l,this.rpcConfig=a,this.chains=i,this.publicClient=m.getPublicClient(l,this.chains,a,{appId:o}),this.rpcTimeoutDuration=s.getRpcTimeout(a,"privy"),this.appId=o,this.walletIndex=c}}class gr extends s.EthereumWalletConnector{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the EthereumNullConnector")}disconnect(){throw Error("disconnect called for an uninstalled wallet via the EthereumNullConnector")}promptConnection(e){throw Error(`promptConnection called for an uninstalled wallet via the EthereumNullConnector for ${e}`)}constructor({id:e,name:t,icon:r,walletClientType:n,defaultChain:a}){super(n,[],a,{}),this.connectorType="null",this.proxyProvider=new s.PrivyProxyProvider(void 0,c.DEFAULT_RPC_TIMEOUT),this.id=e,this.name=t,this.icon=r,this.connectorType=n}}const fr=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlSpace:"preserve",x:0,y:0,viewBox:"0 0 318.6 318.6",width:"28",height:"28",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("style",{children:".s1{stroke-linecap:round;stroke-linejoin:round}.s2{fill:#e4761b;stroke:#e4761b}.s3{fill:#f6851b;stroke:#f6851b}"}),/*#__PURE__*/e.jsx("path",{fill:"#e2761b",stroke:"#e2761b",className:"s1",d:"m274.1 35.5-99.5 73.9L193 65.8z"}),/*#__PURE__*/e.jsx("path",{d:"m44.4 35.5 98.7 74.6-17.5-44.3zm193.9 171.3-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z",className:"s1 s2"}),/*#__PURE__*/e.jsx("path",{d:"m103.6 138.2-15.8 23.9 56.3 2.5-2-60.5zm111.3 0-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5 33.9 16.5-4.7-39.3z",className:"s1 s2"}),/*#__PURE__*/e.jsx("path",{fill:"#d7c1b3",stroke:"#d7c1b3",className:"s1",d:"m211.8 247.4-33.9-16.5 2.7 22.1-.3 9.3zm-105 0 31.5 14.9-.2-9.3 2.5-22.1z"}),/*#__PURE__*/e.jsx("path",{fill:"#233447",stroke:"#233447",className:"s1",d:"m138.8 193.5-28.2-8.3 19.9-9.1zm40.9 0 8.3-17.4 20 9.1z"}),/*#__PURE__*/e.jsx("path",{fill:"#cd6116",stroke:"#cd6116",className:"s1",d:"m106.8 247.4 4.8-40.6-31.3.9zM207 206.8l4.8 40.6 26.5-39.7zm23.8-44.7-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1 20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"}),/*#__PURE__*/e.jsx("path",{fill:"#e4751f",stroke:"#e4751f",className:"s1",d:"m87.8 162.1 23.6 46-.8-22.9zm120.3 23.1-1 22.9 23.7-46zm-64-20.6-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0-2.7 18 1.2 45 6.7-34.1z"}),/*#__PURE__*/e.jsx("path",{d:"m179.8 193.5-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z",className:"s3"}),/*#__PURE__*/e.jsx("path",{fill:"#c0ad9e",stroke:"#c0ad9e",className:"s1",d:"m180.3 262.3.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"}),/*#__PURE__*/e.jsx("path",{fill:"#161616",stroke:"#161616",className:"s1",d:"m177.9 230.9-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"}),/*#__PURE__*/e.jsx("path",{fill:"#763d16",stroke:"#763d16",className:"s1",d:"m278.3 114.2 8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"}),/*#__PURE__*/e.jsx("path",{d:"m267.2 153.5-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4 3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z",className:"s3"})]}),wr=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M46.5267 69.9229C42.0054 76.8509 34.4292 85.6182 24.348 85.6182C19.5824 85.6182 15 83.6563 15 75.1342C15 53.4305 44.6326 19.8327 72.1268 19.8327C87.768 19.8327 94 30.6846 94 43.0079C94 58.8258 83.7355 76.9122 73.5321 76.9122C70.2939 76.9122 68.7053 75.1342 68.7053 72.314C68.7053 71.5783 68.8275 70.7812 69.0719 69.9229C65.5893 75.8699 58.8685 81.3878 52.5754 81.3878C47.993 81.3878 45.6713 78.5063 45.6713 74.4598C45.6713 72.9884 45.9768 71.4556 46.5267 69.9229ZM83.6761 42.5794C83.6761 46.1704 81.5575 47.9658 79.1875 47.9658C76.7816 47.9658 74.6989 46.1704 74.6989 42.5794C74.6989 38.9885 76.7816 37.1931 79.1875 37.1931C81.5575 37.1931 83.6761 38.9885 83.6761 42.5794ZM70.2103 42.5795C70.2103 46.1704 68.0916 47.9658 65.7216 47.9658C63.3157 47.9658 61.233 46.1704 61.233 42.5795C61.233 38.9885 63.3157 37.1931 65.7216 37.1931C68.0916 37.1931 70.2103 38.9885 70.2103 42.5795Z",fill:"#FFFDF8"})]});function vr(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var Cr=0;class xr extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return{name:this.providerDetail.info.name,icon:this.providerDetail.info.icon,id:this.providerDetail.info.rdns}}disconnect(){console.warn(`Programmatic disconnect with ${this.providerDetail.info.name} is not yet supported.`)}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}constructor(e,t,r,n,a){super(a||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let i=n.provider;this.proxyProvider.setWalletProvider(i)}}var Er="__private_"+Cr+++"__walletBranding";class Sr extends s.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return vr(this,Er)[Er]??{name:"Browser Extension",icon:s.BrowserExtensionWallet,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}constructor(e,t,r,n,a){super(a??"unknown",e,t,r),Object.defineProperty(this,Er,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===a?vr(this,Er)[Er]={name:"MetaMask",icon:fr,id:"io.metamask"}:"phantom"===a&&(vr(this,Er)[Er]={name:"Phantom",icon:wr,id:"phantom"})}}class Tr extends xr{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{n.isMobile||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new i.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}}const Ar=["metamask","phantom","brave_wallet","rainbow","uniswap_wallet_extension","uniswap_extension","rabby_wallet","bybit_wallet","ronin_wallet","crypto.com_wallet_extension","crypto.com_onchain","coinbase_wallet","coinbase_smart_wallet","metamask","trust","safe","rainbow","uniswap","zerion","argent","spot","omni","cryptocom","blockchain","safepal","bitkeep","zengo","1inch","binance","exodus","mew_wallet","alphawallet","keyring_pro","mathwallet","unstoppable","obvious","ambire","internet_money_wallet","coin98","abc_wallet","arculus_wallet","haha","cling_wallet","broearn","copiosa","burrito_wallet","enjin_wallet","plasma_wallet","avacus","bee","pitaka","pltwallet","minerva","kryptogo","prema","slingshot","kriptonio","timeless","secux","bitizen","blocto","okx_wallet","safemoon","rabby_wallet","bybit_wallet","ronin_wallet","privy","unknown","phantom","solflare","glow","backpack"],br=Object.freeze({phantom:{client:"phantom",name:"Phantom",installLink:Te.isFirefox?"https://addons.mozilla.org/en-US/firefox/addon/phantom-app/":"https://chrome.google.com/webstore/detail/phantom/bfnaelmomeimhlpmgjnjophhpkkoljpa?hl=en",chainTypes:["ethereum","solana"],get isInstalled(){if("phantom"in window){let e=window;if(e?.phantom?.ethereum?.isPhantom&&e?.phantom?.ethereum?.chainId||e?.phantom?.solana?.isPhantom)return!0}return!1},getMobileRedirect({useUniversalLink:e,isSolana:t,connectOnly:r}){let n=Ir({client:this.client,isSolana:t,connectOnly:r});return`${e?"phantom://":"https://phantom.app/ul/"}browse/${n}?ref=${n}`}},solflare:{client:"solflare",name:"Solflare",installLink:Te.isFirefox?"https://addons.mozilla.org/es/firefox/addon/solflare-wallet/":"https://chromewebstore.google.com/detail/solflare-wallet/bhhhlbepdkbapadjdnnojkbgioiodbic",chainTypes:["solana"],get isInstalled(){return"solflare"in window&&!!window?.solflare?.isSolflare},getMobileRedirect({useUniversalLink:e,isSolana:t,connectOnly:r}){let n=Ir({client:this.client,isSolana:t,connectOnly:r});return`${e?"solflare://ul/v1/":"https://solflare.com/ul/v1/"}browse/${n}?ref=${n}`}},backpack:{client:"backpack",name:"Backpack",installLink:"https://chromewebstore.google.com/detail/backpack/aflkmfhebedbjioipglgcbcmnbpgliof",chainTypes:["ethereum","solana"],get isInstalled(){return!(!("backpack"in window)||!window?.backpack?.ethereum?.isBackpack&&!window?.backpack?.solana?.isBackpack)},getMobileRedirect({useUniversalLink:e,isSolana:t,connectOnly:r}){let n=Ir({client:this.client,isSolana:t,connectOnly:r});return`${e?"backpack://ul/v1/":"https://backpack.com/ul/v1/"}browse/${n}?ref=${n}`}},okx_wallet:{client:"okx_wallet",name:"OKX Wallet",installLink:"https://chromewebstore.google.com/detail/okx-wallet/mcohilncbfahbmgdjkbpemcciiolgcge",chainTypes:["solana"],get isInstalled(){return"okxwallet"in window&&!!window?.okxwallet?.isOkxWallet},getMobileRedirect({isSolana:e,connectOnly:t}){return"https://www.okx.com/download?deeplink="+encodeURIComponent("okx://wallet/dapp/url?dappUrl="+Ir({client:this.client,isSolana:e,connectOnly:t}))}}});function _r({connectorType:e,walletClientType:t}){for(let r of Ar)if(e===r||t===r)return br[r]}function Ir({client:e,isSolana:t,connectOnly:r}){let n=new URL(window.location.href);return n.searchParams.set("privy_connector",t?"solana_adapter":"injected"),n.searchParams.set("privy_wallet_client",e),n.searchParams.set("privy_connect_only",String(r)),encodeURIComponent(n.href.replace(/\/$/g,""))}class Pr extends d.SolanaWalletConnector{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the SolanaNullConnector")}constructor({id:e,name:t,icon:r}){super({name:t},!1),this.connectorType="null",this.proxyProvider=new s.PrivyProxyProvider(void 0,c.DEFAULT_RPC_TIMEOUT),this.disconnect=async()=>{throw Error("disconnect called for an uninstalled wallet via the SolanaNullConnector")},this.promptConnection=async()=>{throw Error("promptConnection called for an uninstalled wallet via the SolanaNullConnector")},this.id=e,this.name=t,this.icon=r}}class jr extends be.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(e){if(this.initialized&&!e)return;e&&this.removeAllConnectors(),d.s.get(c.CONNECTORS_STATE_KEY)&&(d.s.getKeys().forEach((e=>{e.startsWith("walletconnect")&&d.s.del(e)})),d.s.del(c.CONNECTORS_STATE_KEY));let t=s.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(br)))!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.addSolanaWalletConnector(new Pr({id:e.client,name:e.name})));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 t,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(s.isEthereumWalletConnector).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(s.isEthereumWalletConnector).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(d.isSolanaWalletConnector).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??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:n,appId:a}){for(let i of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(r&&s.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let{entropyId:r,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(t),s=new lr({provider:new mr({walletProxy:e,address:i.address,entropyId:r,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:n.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,r,n){let a=this.findWalletConnector("embedded_imported","privy");if(a&&s.isEthereumWalletConnector(a))a.proxyProvider.walletProxy=e;else{let a=new lr({provider:new mr({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(a)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=d.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=d.loadConnectionHistory(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let a=this.findWalletConnector(e,t);if(a&&s.isEthereumWalletConnector(a))return a instanceof s.WalletConnectV2WalletConnector&&a.resetConnection(t),a;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new or(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new s.WalletConnectV2WalletConnector(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):n?new gr({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Tr(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Sr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Sr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Sr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new xr(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})));d.s.put(c.CONNECTIONS_HISTORY_KEY,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&s.isBaseConnectedEthereumWallet(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=a.getAddress(e),this.emit("walletsUpdated")}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,r,n,a,i,o,l,c,u,h,p){super(),this.addSolanaWalletConnector=async e=>{let t=this.findSolanaWalletConnector(e.walletClientType);if(!t||"null"===t.connectorType){if("null"===t?.connectorType){let e=this.walletConnectors.indexOf(t);this.walletConnectors.splice(e,1)}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 s.PrivyProxyProvider},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=a,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=l,this.externalWalletConfig=c,this.privyAppName=u,this.privyAppLogo=h,this.walletChainType=p||"ethereum-only",this.storedConnections=d.loadConnectionHistory()}}let kr=[o.sessionsRefreshPath,o.sessionsLogoutPath,o.analyticsEventsPath];class Nr{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw i.formatApiError(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw i.formatApiError(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw i.formatApiError(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=c.VERSION,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=g.ofetch.create({baseURL:this.defaults.baseURL,timeout:this.defaults.timeout,retry:3,retryDelay:500,retryStatusCodes:[408,409,425,500,502,503,504],credentials:"include",onRequest:async({request:e,options:t})=>{let r=new Headers(t.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-ca-id",this.clientAnalyticsId||""),r.set("privy-client",`react-auth:${this.sdkVersion}`);let n=kr.includes(e.toString());if(!r.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:n});null!==e&&r.set("authorization",`Bearer ${e}`)}t.headers=r,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new i.PrivyTimeoutError}})}}let Mr=/paymaster\.biconomy\.io\/api/i,Rr={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const Or=(e,t)=>e&&Mr.test(e)?Rr:t&&t.policy_id?{policyId:t.policy_id}:void 0;function Wr(){return!(n.isSafari&&window.location.origin.startsWith("http://localhost"))}const Lr=w.create((()=>({identityToken:null})));var Ur,Fr=((Ur={}).PRIVY="privy_access_token",Ur.CUSTOMER="customer_access_token",Ur);class Dr{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)}get privyAccessToken(){return this._getToken(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}_getToken(e){try{let t=d.s.get(e);return"string"==typeof t?er.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=d.s.get(c.REFRESH_TOKEN_STORAGE_KEY);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=d.s.get(c.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new er(t);return r.isExpired()?(d.s.del(c.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=_e.default.get(c.SESSION_COOKIE_KEY);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e="privy_access_token"){let t="string"==typeof this.getToken(e),r="string"==typeof this.refreshToken&&this.refreshToken!==c.DEPRECATED_REFRESH_TOKEN;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=er.parse(this.getToken(e));return null!==t&&!t.isExpired(30)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(e,t){"string"==typeof t?d.s.put(c.getProviderAccessTokenStorageKey(e),t):d.s.del(c.getProviderAccessTokenStorageKey(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:r,is_new_user:n,oauth_tokens:a}=t;this.handleTokenResponse(t);let i=a?{provider:a.provider,accessToken:a.access_token,accessTokenExpiresInSeconds:a.access_token_expires_in_seconds,refreshToken:a.refresh_token,refreshTokenExpiresInSeconds:a.refresh_token_expires_in_seconds,scopes:a.scopes}:void 0;return this._trackAuthenticateEvents(e,n),{user:c.convertUserResponseToUser(r),isNewUser:n,oAuthTokens:i}}catch(e){throw console.warn("Error authenticating session"),i.formatPrivyError(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof St?"email":e instanceof Kt?"sms":e instanceof s.SiweFlow?"siwe":e instanceof _t?"guest":e instanceof xt?"custom_auth":e instanceof kt?e.meta.provider:null}(e);r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:r,isNewUser:t}}),"siwe"===r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:e.meta.connectorType,walletClientType:e.meta.walletClientType}})}async _link(e){try{let t=await e.link(),r=t.oauth_tokens,n=r?{provider:r.provider,accessToken:r.access_token,accessTokenExpiresInSeconds:r.access_token_expires_in_seconds,refreshToken:r.refresh_token,refreshTokenExpiresInSeconds:r.refresh_token_expires_in_seconds,scopes:r.scopes}:void 0;return{user:c.convertUserResponseToUser(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),i.formatPrivyError(e)}}async _refresh(){if(!this.api)throw new i.PrivyClientError("Session has no API instance");if(!this.client)throw new i.PrivyClientError("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,t=this.refreshToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let r;if(!(e&&t||this.mightHaveServerCookies))return null;{let n={};e&&(n.authorization=`Bearer ${e}`),r=await this.api.post(o.sessionsRefreshPath,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),c.convertUserResponseToUser(r.user)}catch(e){if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw i.formatPrivyError(e)}}handleTokenResponse(e){e.session_update_action&&"set"!==e.session_update_action?"clear"===e.session_update_action?this.destroyLocalState():"ignore"===e.session_update_action&&(e.token&&(this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token)),e.identity_token&&this.storeIdentityToken(e.identity_token)):this._storeAllTokens(e)}_storeAllTokens(e){this.storeRefreshToken(e.refresh_token),this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token),e.identity_token&&this.storeIdentityToken(e.identity_token)}async _destroy(){try{await(this.api?.post(o.sessionsLogoutPath,{refresh_token:this.refreshToken}))}catch(e){console.warn("Error destroying session")}this.destroyLocalState()}destroyLocalState(){this.storeRefreshToken(null),this.storeCustomerAccessToken(null),this.storePrivyAccessToken(null),this.clearIdentityToken()}storeCustomerAccessToken(e){if("string"==typeof e){let t=d.s.get(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(d.s.put(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=er.parse(e)?.expiration;_e.default.set(c.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:Wr(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else d.s.del(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),_e.default.remove(c.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(d.s.put(c.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||_e.default.set(c.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:Wr(),expires:30})):(d.s.del(c.REFRESH_TOKEN_STORAGE_KEY),_e.default.remove(c.REFRESH_TOKEN_COOKIE_KEY),_e.default.remove(c.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?d.s.put(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):d.s.del(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(Lr.setState({identityToken:e}),this.client?.useServerCookies)return;d.s.put(c.IDENTITY_TOKEN_STORAGE_KEY,e);let t=er.parse(e)?.expiration;_e.default.set(c.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:Wr(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){d.s.del(c.IDENTITY_TOKEN_STORAGE_KEY),Lr.setState({identityToken:null}),_e.default.remove(c.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new s.RunEffectOnce((async e=>this._authenticate(e))),this.linkOnce=new s.RunEffectOnce((async e=>this._link(e))),this.refreshOnce=new s.RunEffectOnce(this._refresh.bind(this)),this.destroyOnce=new s.RunEffectOnce(this._destroy.bind(this))}}let Br;var Hr=0,zr="__private_"+Hr+++"__getOrGenerateClientAnalyticsId";class qr{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:a,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new jr(this.appId,e,t,r,n,a,i,o,s,l,void 0,c))}generateApi(){let e=new Nr({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 i.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new i.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(o.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw i.formatApiError(e)}}async initMfaPasskeyVerification(){try{return(e=>({rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}))((await this.api.post(o.mfaPasskeyInitPath,{})).options)}catch(e){throw i.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(o.acceptTermsPath,{});return c.convertUserResponseToUser(e)}catch(e){throw i.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(o.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(o.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(o.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(o.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(o.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(r)}catch(e){throw i.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(o.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(o.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??c.convertUserResponseToUser(t)}catch(e){throw i.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(o.delegatedActionsRevokePath,{})}catch(e){throw i.formatPrivyError(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:n}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(o.analyticsEventsPath,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(o.moonpayPluginOnRampPath,e)}catch(e){throw i.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(o.coinbaseOnRampInitPath,e)}catch(e){throw i.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${o.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw i.formatPrivyError(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(Fr.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Fr.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?tr.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:Or(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw i.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}),n=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,a=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:{ethereum:{createOnLogin:r.embedded_wallet_config.ethereum?.create_on_login??r.embedded_wallet_config.create_on_login},solana:{createOnLogin:r.embedded_wallet_config.solana?.create_on_login??"off"},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:n,fundingConfig:a}}catch(e){throw i.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 generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(o.siweInitPath,{address:e,token:t})).nonce}catch(e){throw i.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i}){return await this.api.post(o.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){return await this.api.post(o.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})}async linkSmartWallet({message:e,signature:t,smartWalletType:r}){try{let n=await this.api.post(o.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r});return c.convertUserResponseToUser(n)}catch(e){throw i.formatPrivyError(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a});return c.convertUserResponseToUser(i)}catch(e){throw i.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(o.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw i.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:a}){return await this.api.post(o.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:n,mode:a})}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:s,farcasterEmbeddedAddress:l,oAuthUserInfo:d}){try{let i,u;switch(r){case"email":i=o.transferEmailPath,u={nonce:e,email:t};break;case"sms":i=o.transferPhonePath,u={nonce:e,phoneNumber:t};break;case"siwe":if(i=o.transferWalletPath,!n)throw Error("Wallet parameters must be defined");u={nonce:e,address:t,...n};break;case"farcaster":i=o.transferFarcasterPath,u={nonce:e,farcaster_id:t,farcaster_embedded_address:l};break;case"telegram":i=o.telegramAccountTransferPath,u={nonce:e,telegram_auth_result:a,telegram_web_app_data:s};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:i=o.transferOAuthPath,u={nonce:e,userInfo:d}}let h=await this.api.post(i,u);return await this.getAuthenticatedUser()??c.convertUserResponseToUser(h)}catch(e){throw i.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n}){return await this.api.post(o.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:n})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n}){try{let a=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n});return c.convertUserResponseToUser(a)}catch(e){throw i.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(o.usersMePath);return this.session.updateIdentityToken(e.identity_token),c.convertUserResponseToUser(e.user)}catch(e){throw i.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(o.transactionScanningPath,e)}catch(e){throw i.formatPrivyError(e)}}constructor({apiUrl:e=c.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:n=c.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,zr,{value:Vr}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==c.DEFAULT_PRIVY_API_URL&&e.startsWith("https://privy."),this.timeout=n,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,zr)[zr](),Br||(Br=new Dr),this.session=Br,this.api=this.generateApi(),this.session.client=this}}function Vr(){if("undefined"==typeof window)return null;try{let e=d.s.get(c.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=u.v4();try{return d.s.put(c.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}const Gr=t=>{let{enabled:n,siteKey:a,appId:i,setError:o,setToken:l,setExecuting:c,ref:d}=s.useCaptcha(),[,u]=r.useMemo((()=>a?.split("t:")||[]),[a]);if(r.useEffect((()=>d.current?.remove),[]),!n)return null;if(!u)throw Error("Unsupported captcha site key");/*#__PURE__*/return e.jsx("div",{className:"hidden h-0 w-0",children:/*#__PURE__*/e.jsx(v.Turnstile,{...t,ref:d,siteKey:u,options:{action:i,size:"invisible",...t.delayedExecution?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{t.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{t.onError?.(),o("Captcha failed"),c(!1)},onSuccess:e=>{t.onSuccess?.(e),l(e),c(!1)},onExpire:()=>{t.onExpire?.();try{d.current?.reset(),o(void 0),l(void 0)}catch(e){o("expired_and_failed_reset")}}})})};function $r(e){d.usePrivyEventSubscription("configureMfa",e)}const Kr=/*#__PURE__*/C.styled.span.withConfig({displayName:"CircleBackground",componentId:"sc-c9f33cd-0"})(["&&{width:82px;height:82px;border-width:4px;border-style:solid;border-color:",";background-color:",";border-radius:50%;display:inline-block;box-sizing:border-box;}"],(e=>e.color??"var(--privy-color-accent)"),(e=>e.color??"var(--privy-color-accent)"));let Yr=/*#__PURE__*/C.styled.div.withConfig({displayName:"StackedContainer",componentId:"sc-f7e7d474-0"})(["display:flex;flex-direction:column;justify-content:center;align-items:center;width:100%;height:82px;> div{position:relative;}> div > span{position:absolute;left:-41px;top:-41px;}> div > :last-child{position:absolute;left:-19px;top:-19px;}"]);const Zr=/*#__PURE__*/C.styled.div.withConfig({displayName:"Grow",componentId:"sc-ddbf22b4-0"})(["text-align:left;flex-grow:1;"]),Xr=/*#__PURE__*/C.styled.div.withConfig({displayName:"AlignBottom",componentId:"sc-ddbf22b4-1"})(["display:flex;flex-direction:column;justify-content:flex-end;flex-grow:1;"]),Qr=/*#__PURE__*/C.styled.div.withConfig({displayName:"LoginMethodContainer",componentId:"sc-ddbf22b4-2"})(["display:flex;flex-direction:column;gap:12px;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}"]),Jr=/*#__PURE__*/C.styled(Qr).withConfig({displayName:"LoginMethodContainerWithScrollShadows",componentId:"sc-ddbf22b4-3"})([""," background-repeat:no-repeat;background-size:100% 32px,100% 16px;background-attachment:local,scroll;max-height:400px;overflow-y:auto;scrollbar-width:none;padding:2px;"],(e=>"light"===e.$colorScheme?"background: linear-gradient(var(--privy-color-background), var(--privy-color-background) 70%) bottom, linear-gradient(rgba(0, 0, 0, 0) 20%, rgba(0, 0, 0, 0.06)) bottom;":"dark"===e.$colorScheme?"background: linear-gradient(var(--privy-color-background), var(--privy-color-background) 70%) bottom, linear-gradient(rgba(255, 255, 255, 0) 20%, rgba(255, 255, 255, 0.06)) bottom;":void 0));let en=/*#__PURE__*/C.css(["&&{width:100%;font-size:16px;line-height:24px;@media (min-width:440px){font-size:14px;}display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--privy-color-foreground-4) !important;border-radius:var(--privy-border-radius-mdlg);transition:background-color 200ms ease;cursor:pointer;&:hover{background-color:var(--privy-color-background-2);}&:disabled{cursor:pointer;background-color:var(--privy-color-background-2);}svg{height:24px;max-height:24px;max-width:24px;}}"]);const tn=/*#__PURE__*/C.styled.div.withConfig({displayName:"Subtitle",componentId:"sc-ddbf22b4-4"})(["text-align:center;font-size:14px;margin-bottom:24px;"]),rn=/*#__PURE__*/C.styled.button.attrs({className:"login-method-button"}).withConfig({displayName:"LoginMethodButton",componentId:"sc-ddbf22b4-5"})(["",""],en),nn=/*#__PURE__*/C.styled.a.withConfig({displayName:"LoginMethodButtonLink",componentId:"sc-ddbf22b4-6"})(["",""],en),an=/*#__PURE__*/C.styled.div.withConfig({displayName:"Hide",componentId:"sc-ddbf22b4-7"})(["width:100%;height:100%;min-height:inherit;display:flex;flex-direction:column;",""],(e=>e.$if?"display: none;":"")),on=/*#__PURE__*/C.styled.div.withConfig({displayName:"EmptyWalletState",componentId:"sc-ddbf22b4-8"})(["width:100%;height:100%;padding:",";"],(e=>e.$withPadding?"64px 0px":"0px")),sn=/*#__PURE__*/C.styled.div.withConfig({displayName:"Header",componentId:"sc-ddbf22b4-9"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-bottom:32px;gap:12px;& h3{font-size:18px;font-style:normal;font-weight:600;line-height:24px;}& p{max-width:300px;font-size:14px;font-style:normal;font-weight:400;line-height:20px;}"]);let ln=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-a3e74b9e-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;padding-bottom:16px;margin-top:24px;"]),cn=/*#__PURE__*/C.styled.div.withConfig({displayName:"GappedContainer",componentId:"sc-a3e74b9e-1"})(["display:flex;flex-direction:column;gap:8px;"]);const dn=/*#__PURE__*/C.styled.span.withConfig({displayName:"CircleBorder",componentId:"sc-9056b8b8-0"})(["&&{width:82px;height:82px;border-width:4px;border-style:solid;border-color:",";border-bottom-color:transparent;border-radius:50%;display:inline-block;box-sizing:border-box;animation:rotation 1.2s linear infinite;transition:border-color 800ms;border-bottom-color:",";}"],(e=>e.color??"var(--privy-color-accent)"),(e=>e.color??"var(--privy-color-accent)"));function un(t){/*#__PURE__*/return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:[/*#__PURE__*/e.jsx("circle",{cx:"12",cy:"12",r:"10"}),/*#__PURE__*/e.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),/*#__PURE__*/e.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}const hn=({onTransfer:t,isTransferring:r,transferSuccess:n})=>/*#__PURE__*/e.jsx(s.PrimaryButton,{...n?{success:!0,children:"Success!"}:{warn:!0,loading:r,onClick:t,children:"Transfer and delete account"}}),pn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-aa2e65ff-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;width:100%;padding-bottom:16px;"]),yn=/*#__PURE__*/C.styled.div.withConfig({displayName:"GappedContainer",componentId:"sc-aa2e65ff-1"})(["display:flex;flex-direction:column;&& p{font-size:14px;}width:100%;gap:16px;"]),mn=/*#__PURE__*/C.styled.div.withConfig({displayName:"DisclosedAccountContainer",componentId:"sc-aa2e65ff-2"})(["display:flex;cursor:pointer;align-items:center;width:100%;border:1px solid var(--privy-color-foreground-4) !important;border-radius:var(--privy-border-radius-md);padding:8px 10px;font-size:14px;font-weight:500;gap:8px;"]),gn=/*#__PURE__*/C.styled(ke.default).withConfig({displayName:"StyledExclamationCircleIcon",componentId:"sc-aa2e65ff-3"})(["position:relative;width:",";height:",";color:var(--privy-color-foreground-3);margin-left:auto;"],(e=>`${e.iconSize}px`),(e=>`${e.iconSize}px`)),fn=/*#__PURE__*/C.styled(Ne.default).withConfig({displayName:"StyledCopyIcon",componentId:"sc-aa2e65ff-4"})(["position:relative;width:15px;height:15px;color:var(--privy-color-foreground-3);margin-left:auto;"]),wn=/*#__PURE__*/C.styled.ol.withConfig({displayName:"ListContainer",componentId:"sc-aa2e65ff-5"})(["display:flex;flex-direction:column;font-size:14px;width:100%;text-align:left;"]),vn=/*#__PURE__*/C.styled.li.withConfig({displayName:"ListItem",componentId:"sc-aa2e65ff-6"})(["font-size:14px;list-style-type:auto;list-style-position:outside;margin-left:1rem;margin-bottom:0.5rem;&:last-child{margin-bottom:0;}"]),Cn=/*#__PURE__*/C.styled.div.withConfig({displayName:"CircleContainer",componentId:"sc-aa2e65ff-7"})(["position:relative;width:60px;height:60px;margin:10px;display:flex;justify-content:center;align-items:center;"]);let xn=()=>/*#__PURE__*/e.jsx(Cn,{children:/*#__PURE__*/e.jsx(gn,{iconSize:60})});const En=({address:t,onClose:r,onRetry:n,onTransfer:a,isTransferring:i,transferSuccess:o})=>{let{defaultChain:l}=c.useAppConfig(),d=l.blockExplorers?.default.url??"https://etherscan.io";/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:r,backFn:n}),/*#__PURE__*/e.jsxs(pn,{children:[/*#__PURE__*/e.jsx(xn,{}),/*#__PURE__*/e.jsxs(yn,{children:[/*#__PURE__*/e.jsx("h3",{children:"Check account assets before transferring"}),/*#__PURE__*/e.jsx("p",{children:"Before transferring, ensure there are no assets in the other account. Assets in that account will not transfer automatically and may be lost."}),/*#__PURE__*/e.jsxs(wn,{children:[/*#__PURE__*/e.jsx("p",{children:" To check your balance, you can:"}),/*#__PURE__*/e.jsx(vn,{children:"Log out and log back into the other account, or "}),/*#__PURE__*/e.jsxs(vn,{children:["Copy your wallet address and use a"," ",/*#__PURE__*/e.jsx("u",{children:/*#__PURE__*/e.jsx("a",{target:"_blank",href:d,children:"block explorer"})})," ","to see if the account holds any assets."]})]}),/*#__PURE__*/e.jsxs(mn,{onClick:()=>navigator.clipboard.writeText(t).catch(console.error),children:[/*#__PURE__*/e.jsx(je.default,{color:"var(--privy-color-foreground-1)",strokeWidth:2,height:"28px",width:"28px"}),/*#__PURE__*/e.jsx(s.Address,{address:t,showCopyIcon:!1}),/*#__PURE__*/e.jsx(fn,{})]}),/*#__PURE__*/e.jsx(hn,{onTransfer:a,isTransferring:i,transferSuccess:o})]})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},Sn=({onClose:t,onContinue:r,onInfo:n,onTransfer:a,transferSuccess:i,isTransferring:o,data:l})=>{if(!l?.accountTransfer?.linkMethod||!l?.accountTransfer?.displayName)return;let c={method:l?.accountTransfer?.linkMethod,handle:l?.accountTransfer?.displayName,disclosedAccount:l?.accountTransfer?.embeddedWalletAddress?{type:"wallet",handle:l?.accountTransfer?.embeddedWalletAddress}:void 0};/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{closeable:!0}),/*#__PURE__*/e.jsxs(pn,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(dn,{color:"var(--privy-color-error)"}),/*#__PURE__*/e.jsx(Pe.default,{height:38,width:38,stroke:"var(--privy-color-error)"})]})}),/*#__PURE__*/e.jsxs(yn,{children:[/*#__PURE__*/e.jsxs("h3",{children:[function(e){switch(e){case"sms":return"Phone number";case"email":return"Email address";case"siwe":return"Wallet address";case"linkedin":return"LinkedIn profile";case"google":case"apple":case"discord":case"github":case"instagram":case"spotify":case"tiktok":case"twitter":case"telegram":case"farcaster":return`${Nt(e.replace("_oauth",""))} profile`;default:return e}}(c.method)," is associated with another account"]}),/*#__PURE__*/e.jsxs("p",{children:["Do you want to transfer",/*#__PURE__*/e.jsx("b",{children:c.handle?` ${c.handle}`:""})," to this account instead? This will delete your other account."]}),/*#__PURE__*/e.jsx(Tn,{onClick:n,disclosedAccount:c.disclosedAccount})]}),/*#__PURE__*/e.jsxs(yn,{style:{gap:12,marginTop:12},children:[l?.accountTransfer?.embeddedWalletAddress?/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:r,children:"Continue"}):/*#__PURE__*/e.jsx(hn,{onTransfer:a,transferSuccess:i,isTransferring:o}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:t,children:"No thanks"})]})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})};function Tn({disclosedAccount:t,onClick:r}){return t?/*#__PURE__*/e.jsxs(mn,{onClick:r,children:[/*#__PURE__*/e.jsx(je.default,{color:"var(--privy-color-foreground-1)",strokeWidth:2,height:"28px",width:"28px"}),/*#__PURE__*/e.jsx(s.Address,{address:t.handle,showCopyIcon:!1}),/*#__PURE__*/e.jsx(un,{width:15,height:15,color:"var(--privy-color-foreground-3)",style:{marginLeft:"auto"}})]}):null}const An=/*#__PURE__*/C.styled.div.withConfig({displayName:"AppLogoContainer",componentId:"sc-a63b1990-0"})(["display:flex;flex-direction:column;align-items:center;padding:0px 0px 30px;@media (max-width:440px){padding:10px 10px 20px;}"]),bn=/*#__PURE__*/C.styled.div.withConfig({displayName:"Title",componentId:"sc-a63b1990-1"})(["font-size:18px;line-height:30px;text-align:center;font-weight:600;margin-bottom:10px;"]),_n=/*#__PURE__*/C.styled.div.withConfig({displayName:"SubTitle",componentId:"sc-a63b1990-2"})(["font-size:0.875rem;text-align:center;"]),In=/*#__PURE__*/C.styled.div.withConfig({displayName:"Container",componentId:"sc-a63b1990-3"})(["display:flex;flex-direction:column;align-items:center;gap:10px;flex-grow:1;padding:20px 0;@media (max-width:440px){padding:10px 10px 20px;}"]),Pn=/*#__PURE__*/C.styled.div.withConfig({displayName:"List",componentId:"sc-a63b1990-4"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.75rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),jn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ListItemIcon",componentId:"sc-a63b1990-5"})(["width:25px;display:flex;align-items:center;justify-content:flex-start;> svg{z-index:2;height:25px !important;width:25px !important;color:var(--privy-color-accent);}"]),kn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ListItem",componentId:"sc-a63b1990-6"})(["display:flex;align-items:center;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;"]),Nn=/*#__PURE__*/C.styled.div.withConfig({displayName:"BottomSection",componentId:"sc-a63b1990-7"})(["display:flex;flex-direction:column;gap:10px;padding-top:20px;"]),Mn=/*#__PURE__*/C.styled.div.withConfig({displayName:"MethodList",componentId:"sc-a63b1990-8"})(["display:flex;flex-direction:column;align-items:stretch;gap:1rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),Rn=/*#__PURE__*/C.styled.div.withConfig({displayName:"MethodListItem",componentId:"sc-a63b1990-9"})(["display:flex;gap:5px;width:100%;position:relative;"]),On=/*#__PURE__*/C.styled.button.withConfig({displayName:"RemoveMethodButton",componentId:"sc-a63b1990-10"})(["&&{background-color:transparent;color:var(--privy-color-foreground-3);padding:0 0.75rem;display:flex;align-items:center;height:100%;> svg{z-index:2;height:20px !important;width:20px !important;}}&&:hover{color:var(--privy-color-error);}"]),Wn=/*#__PURE__*/C.styled.div.withConfig({displayName:"MethodText",componentId:"sc-a63b1990-11"})(["display:flex;align-items:center;gap:0.5rem;> svg{z-index:2;height:20px !important;width:20px !important;}"]),Ln=/*#__PURE__*/C.styled.div.withConfig({displayName:"ExtraText",componentId:"sc-a63b1990-12"})(["display:flex;align-items:center;gap:6px;font-weight:400 !important;color:",";> svg{z-index:2;height:18px !important;width:18px !important;display:flex !important;align-items:flex-end;}"],(e=>e.isAccent?"var(--privy-color-accent)":"var(--privy-color-foreground-3)")),Un=/*#__PURE__*/C.styled.div.withConfig({displayName:"SmsInsecureText",componentId:"sc-a63b1990-13"})(["width:100%;display:flex;justify-content:space-between;"]),Fn=/*#__PURE__*/C.styled.p.withConfig({displayName:"TermsText",componentId:"sc-a63b1990-14"})(["text-align:left;width:100%;color:var(--privy-color-foreground-3) !important;"]),Dn=/*#__PURE__*/C.styled.button.withConfig({displayName:"PrimaryTextButton",componentId:"sc-a63b1990-15"})(["display:flex;flex-direction:row;align-items:center;justify-content:center;user-select:none;&{width:100%;cursor:pointer;border-radius:var(--privy-border-radius-md);font-size:0.875rem;line-height:1rem;font-style:normal;font-weight:500;line-height:22px;letter-spacing:-0.016px;}&&{color:",";background-color:transparent;padding:0.5rem 0px;}&:hover{text-decoration:underline;}"],(e=>"dark"===e.theme?"var(--privy-color-foreground-2)":"var(--privy-color-accent)")),Bn=/*#__PURE__*/C.styled.div.withConfig({displayName:"IconWrapper",componentId:"sc-a63b1990-16"})(["display:flex;align-items:center;justify-content:center;color:var(--privy-color-accent);width:100%;> svg{z-index:2;width:3rem;height:3rem;}"]),Hn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ErrorMessage",componentId:"sc-a63b1990-17"})(["color:var(--privy-color-error);"]),zn=({termsAndConditionsUrl:t,privacyPolicyUrl:r,onAccept:n,onDecline:a})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{closeable:!1}),/*#__PURE__*/e.jsx(Re.default,{width:56,height:56,fill:"var(--privy-color-accent)",style:{margin:"auto"}}),/*#__PURE__*/e.jsx(bn,{style:{marginTop:24},children:"One last step"}),/*#__PURE__*/e.jsx(_n,{children:"By signing up, you agree to our terms and privacy policy."}),/*#__PURE__*/e.jsxs(Qr,{style:{marginTop:24},children:[t&&/*#__PURE__*/e.jsxs(nn,{target:"_blank",href:t,children:["View Terms ",/*#__PURE__*/e.jsx(Me.default,{style:{marginLeft:"auto"}})]}),r&&/*#__PURE__*/e.jsxs(nn,{target:"_blank",href:r,children:["View Privacy Policy ",/*#__PURE__*/e.jsx(Me.default,{style:{marginLeft:"auto"}})]})]}),/*#__PURE__*/e.jsxs(qn,{style:{marginTop:24},children:[/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:a,children:"No thanks"}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:n,children:"Accept"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let qn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ButtonsContainer",componentId:"sc-d601b243-0"})(["display:flex;gap:10px;"]);const Vn=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...r,children:/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",d:"M12 1.5a5.25 5.25 0 00-5.25 5.25v3a3 3 0 00-3 3v6.75a3 3 0 003 3h10.5a3 3 0 003-3v-6.75a3 3 0 00-3-3v-3c0-2.9-2.35-5.25-5.25-5.25zm3.75 8.25v-3a3.75 3.75 0 10-7.5 0v3h7.5z",clipRule:"evenodd"})});let Gn=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-ed4ecf-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;padding-bottom:16px;"]),$n=/*#__PURE__*/C.styled.div.withConfig({displayName:"GappedContainer",componentId:"sc-ed4ecf-1"})(["display:flex;flex-direction:column;gap:8px;"]);const Kn=({title:t,description:r,children:n,...a})=>
2
2
  /*#__PURE__*/e.jsx(Xn,{...a,children:/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx("h3",{children:t}),"string"==typeof r?/*#__PURE__*/e.jsx("p",{children:r}):r,n]})}),Yn=/*#__PURE__*/C.styled(Kn).withConfig({displayName:"PaddedScreenHeader",componentId:"sc-523a75d6-0"})(["margin-bottom:24px;"]),Zn=({title:t,description:r,icon:n,children:a,...i})=>/*#__PURE__*/e.jsxs(Qn,{...i,children:[n||null,/*#__PURE__*/e.jsx("h3",{children:t}),r&&"string"==typeof r?/*#__PURE__*/e.jsx("p",{children:r}):r,a]});let Xn=/*#__PURE__*/C.styled.div.withConfig({displayName:"StyledSection",componentId:"sc-523a75d6-1"})(["display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start;text-align:left;gap:8px;width:100%;margin-bottom:24px;&& h3{font-size:17px;color:var(--privy-color-foreground);}&& p{color:var(--privy-color-foreground-2);font-size:14px;}"]),Qn=/*#__PURE__*/C.styled(Xn).withConfig({displayName:"CenteredStyledSection",componentId:"sc-523a75d6-2"})(["align-items:center;text-align:center;gap:16px;h3{margin-bottom:24px;}"]),Jn=Array(6).fill("");var ea,ta,ra=((ea=ra||{})[ea.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",ea[ea.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",ea),na=((ta=na||{})[ta.EMAIL=0]="EMAIL",ta[ta.SMS=1]="SMS",ta);let aa=/*#__PURE__*/C.styled.div.withConfig({displayName:"PasswordlessCodeContainer",componentId:"sc-bf1e04a-0"})(["display:flex;flex-direction:column;align-items:flex-start;justify-content:center;margin:auto;gap:16px;flex-grow:1;"]),ia=/*#__PURE__*/C.styled.div.withConfig({displayName:"CodeInput",componentId:"sc-bf1e04a-1"})(["display:flex;flex-direction:column;width:100%;gap:8px;> div:last-child{display:flex;justify-content:center;gap:0.5rem;width:100%;border-radius:var(--privy-border-radius-md);> input{border:1px solid var(--privy-color-foreground-4);background:var(--privy-color-background);border-radius:var(--privy-border-radius-md);padding:8px 10px;height:58px;width:46px;text-align:center;font-size:18px;}> input:focus{border:1px solid var(--privy-color-accent);}> input:invalid{border:1px solid var(--privy-color-error);}> input.success{border:1px solid var(--privy-color-success);}> input.fail{border:1px solid var(--privy-color-error);animation:shake 180ms;animation-iteration-count:2;}}@keyframes shake{0%{transform:translate(1px,0px);}33%{transform:translate(-1px,0px);}67%{transform:translate(-1px,0px);}100%{transform:translate(1px,0px);}}"]),oa=/*#__PURE__*/C.styled.div.withConfig({displayName:"InputHelp",componentId:"sc-bf1e04a-2"})(["line-height:20px;height:20px;font-size:13px;color:",";display:flex;justify-content:flex-end;width:100%;"],(e=>e.$success?"var(--privy-color-success)":e.$fail?"var(--privy-color-error)":"var(--privy-color-foreground-3)")),sa=/*#__PURE__*/C.styled.div.withConfig({displayName:"HelpText",componentId:"sc-bf1e04a-3"})(["font-size:13px;color:var(--privy-color-foreground);display:flex;gap:8px;align-items:center;width:100%;margin-top:16px;padding-bottom:32px;"]),la=/*#__PURE__*/C.styled.div.withConfig({displayName:"ResendButtonContainer",componentId:"sc-bf1e04a-4"})(["color:var(--privy-color-accent);padding:2px 0;> button{text-decoration:underline;}"]),ca=/*#__PURE__*/C.styled.div.withConfig({displayName:"Badge",componentId:"sc-bf1e04a-5"})(["display:flex;align-items:center;justify-content:center;border-radius:var(--privy-border-radius-sm);padding:2px 8px;gap:4px;background:var(--privy-color-background-2);color:var(--privy-color-foreground-2);"]),da=/*#__PURE__*/C.styled.span.withConfig({displayName:"BoldWrappingSpan",componentId:"sc-bf1e04a-6"})(["font-weight:500;word-break:break-all;"]);const ua=({icon:t})=>/*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsx(ha,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{}),"string"==typeof t?
3
3
  /*#__PURE__*/e.jsx("span",{style:{background:`url('${t}')`,height:"38px",width:"38px",borderRadius:"6px",margin:"auto",backgroundSize:"cover"}}):t?/*#__PURE__*/e.jsx(t,{style:{width:"38px",height:"38px"}}):
4
4
  /*#__PURE__*/e.jsx("span",{})]})})});let ha=/*#__PURE__*/C.styled.div.withConfig({displayName:"StackedContainer",componentId:"sc-26c1d9b9-0"})(["display:flex;flex-direction:column;justify-content:center;align-items:center;width:100%;height:82px;> div{position:relative;}> div > span{position:absolute;left:-41px;top:-41px;}> div > :last-child{position:absolute;left:-19px;top:-19px;}"]);let pa=/*#__PURE__*/C.styled.div.withConfig({displayName:"CaptchaContainer",componentId:"sc-9afcf974-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;"]);const ya=({chainType:t,withPadding:r})=>{let n="";return n="ethereum-only"===t||"ethereum-and-solana"===t?"Rainbow, Phantom, or Coinbase Wallet":"Phantom or Solflare",/*#__PURE__*/e.jsx(on,{$withPadding:r,children:/*#__PURE__*/e.jsxs(sn,{children:[/*#__PURE__*/e.jsx(Ie.default,{style:{color:"var(--privy-color-warn)",height:48,width:48}}),/*#__PURE__*/e.jsx("h3",{children:"No wallets available"}),/*#__PURE__*/e.jsxs("p",{children:["Please download an external wallet provider, like ",n,"."]})]})},"empty-wallet-state")},ma=({icon:t,name:r})=>"string"==typeof t?/*#__PURE__*/e.jsx("img",{alt:`${r||"wallet"} logo`,src:t,style:{height:24,width:24,borderRadius:4}}):void 0===t?/*#__PURE__*/e.jsx(je.default,{}):t?/*#__PURE__*/e.jsx(t,{}):null;function ga(e){let t=e.toLowerCase();return!!window?.webkit?.messageHandlers?.ReactNativeWebView||!!window?.ReactNativeWebView||["fbav","fban","instagram","snapchat","linkedinapp"].some((e=>t.includes(e)))}const fa=({provider:t,displayName:r,logo:a,connectOnly:o,connector:l})=>{let d,{navigate:u,setModalData:h}=c.usePrivyModal(),{connectWallet:p}=i.usePrivyInternal(),y=s.useRecentlyUsedLogin(),m=s.useExternalWalletListing(t),g="wallet_connect_v2"===l.connectorType?t:l.walletClientType,f=window.matchMedia("(display-mode: standalone)").matches,w=_r({connectorType:l.connectorType,walletClientType:g});d=w&&w.chainTypes.includes(l.chainType)?()=>{w.isInstalled||"solana"===l.chainType&&"isInstalled"in l&&l.isInstalled?(p(l,g),u(o?c.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION:c.ModalScreen.AWAITING_CONNECTION)):n.isMobile?(h({installWalletModalData:{walletConfig:w,chainType:l.chainType,connectOnly:o}}),u(c.ModalScreen.WALLET_INTERSTITIAL_SCREEN)):(h({installWalletModalData:{walletConfig:w,chainType:l.chainType,connectOnly:o}}),u(c.ModalScreen.INSTALL_WALLET_SCREEN))}:"coinbase_wallet"!==l.connectorType||"eoaOnly"!==l.connectionOptions||!n.isMobile||f||s.isCoinbaseWalletInstalled()?()=>{(!ga(window.navigator.userAgent)||event?.isTrusted)&&(p(l,g),u(o?c.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION:c.ModalScreen.AWAITING_CONNECTION))}:()=>{window.location.href=`https://go.cb-w.com/dapp?cb_url=${encodeURI(window.location.href)}`};let v=r||m?.metadata?.shortName||m?.name||l.walletClientType;/*#__PURE__*/return e.jsxs(wa,{onClick:d,children:[/*#__PURE__*/e.jsx(ma,{icon:a||m?.image_url?.md,name:v}),/*#__PURE__*/e.jsx("span",{children:v}),/*#__PURE__*/e.jsxs(Ca,{id:"chip-container",children:[y?.walletClientType===g&&y?.chainType===l.chainType?/*#__PURE__*/e.jsx(va,{color:"gray",children:"Recent"}):/*#__PURE__*/e.jsx("span",{id:"connect-text",children:"Connect"}),"solana"===l.chainType&&/*#__PURE__*/e.jsx(va,{color:"gray",children:"Solana"})]})]})};let wa=/*#__PURE__*/C.styled(rn).withConfig({displayName:"ConnectWalletButton",componentId:"sc-c6a554d4-0"})(["> #chip-container > #connect-text{font-weight:500;color:var(--privy-color-accent);opacity:0;transition:opacity 0.1s ease-out;}:hover > #chip-container > #connect-text{opacity:1;}@media (max-width:440px){> #chip-container > #connect-text{display:none;}}"]),va=/*#__PURE__*/C.styled(s.Chip).withConfig({displayName:"StyledChip",componentId:"sc-c6a554d4-1"})(["margin-left:auto;"]),Ca=/*#__PURE__*/C.styled.div.withConfig({displayName:"ChipContainer",componentId:"sc-c6a554d4-2"})(["display:flex;flex-wrap:wrap;gap:8px;margin-left:auto;"]);const xa=["coinbase_wallet"];let Ea=["metamask","okx_wallet","rainbow","uniswap","bybit_wallet","ronin_wallet","uniswap_extension","zerion","rabby_wallet","cryptocom"];const Sa=["safe"],Ta=["phantom","backpack","solflare","universal_profile"],Aa=({wallets:t})=>{let{app:r}=c.usePrivyModal();return 0===t.length?/*#__PURE__*/e.jsx(ya,{chainType:r.appearance.walletChainType,withPadding:!0}):/*#__PURE__*/e.jsx(e.Fragment,{children:t})},ba=({walletList:t,walletChainType:r,connectors:n,connectOnly:a,ignore:i,walletConnectEnabled:o,forceWallet:s})=>{let l=[],c=[],d=[],u=n.filter((e=>"ethereum-only"===r?"ethereum"===e.chainType:"solana-only"!==r||"solana"===e.chainType)),h=u.find((e=>"wallet_connect_v2"===e.connectorType));for(let[n,p]of(s?[s.wallet]:t).entries()){if("detected_ethereum_wallets"===p||"detected_wallets"===p)for(let[t,r]of u.filter((({chainType:e,connectorType:t,walletClientType:r})=>"solana"!==e&&("uniswap_wallet_extension"===r||"uniswap_extension"===r?!i.includes("uniswap"):"crypto.com_wallet_extension"===r||"crypto.com_onchain"===r?!i.includes("cryptocom"):"injected"===t&&!i.includes(r)))).entries()){let{walletClientType:i,walletBranding:o,chainType:s}=r;("unknown"===i?c:l).push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:i,logo:o.icon,displayName:o.name,connector:r},`${n}-${p}-${i}-${s}-${t}`))}if("detected_solana_wallets"===p||"detected_wallets"===p)for(let[t,o]of u.filter((({chainType:e,walletClientType:t})=>{if("solana"===e)return"ethereum-only"!==r&&!i.includes(t)})).entries()){let{walletClientType:r,walletBranding:i,chainType:s}=o;("unknown"===r?c:l).push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:r,logo:i.icon,displayName:i.name,connector:o},`${n}-${p}-${r}-${s}-${t}`))}if(Ta.includes(p)){let t=u.find((e=>"injected"===e.connectorType&&e.walletClientType===p||e.connectorType===p));if(t&&l.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,connector:t},`${n}-${p}`)),"solana-only"===r||"ethereum-and-solana"===r){let t=u.find((({chainType:e,walletClientType:t})=>"solana"===e&&t===p));t&&l.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,connector:t},`${p}-solana`))}}else if(Ea.includes(p)){let t=u.find((e=>"uniswap"===p?"uniswap_wallet_extension"===e.walletClientType||"uniswap_extension"===e.walletClientType:"cryptocom"===p?"crypto.com_wallet_extension"===e.walletClientType||"crypto.com_onchain"===e.walletClientType:"injected"===e.connectorType&&e.walletClientType===p));if(o&&!t&&(t=h),t&&l.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,connector:t,logo:"injected"===t.connectorType?t.walletBranding.icon:void 0,displayName:"injected"===t.connectorType?t.walletBranding.name:void 0},`${n}-${p}`)),"solana-only"===r||"ethereum-and-solana"===r){let t=u.find((({chainType:e,walletClientType:t})=>"solana"===e&&t===p));t&&l.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,connector:t},`${p}-solana`))}}else if(xa.includes(p)){let t=u.find((({connectorType:e})=>e===p));t&&l.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,connector:t},`${n}-${p}`))}else if(Sa.includes(p))h&&d.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,connector:h},`${n}-${p}`));else if("wallet_connect"===p)h&&d.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,connector:h,logo:h.walletBranding.icon,displayName:"Wallet Connect"},`${n}-${p}`));else if(p===s?.wallet){let r="ethereum"===s.chainType&&t.includes("detected_ethereum_wallets"),i="solana"===s.chainType&&t.includes("detected_solana_wallets");if(t.includes("detected_wallets")||r||i){let t=u.find((({walletClientType:e})=>e===p));t&&l.push(/*#__PURE__*/e.jsx(fa,{connectOnly:a,provider:p,displayName:t.walletBranding?.name,logo:t.walletBranding?.icon,connector:t},`${n}-${p}`))}}}return[...c,...l,...d]};let _a=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-4475d7d5-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;"]);const Ia=({name:t,logoUrl:r,size:n="38px"})=>{let a=`${t??"Provider app"} logo`;return"string"==typeof r?/*#__PURE__*/e.jsx("img",{src:r,alt:a,style:{width:n,height:n,maxHeight:"90px",maxWidth:"180px",borderRadius:"8px"}}):
@@ -11,12 +11,12 @@ return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsxs(Zc,{onClick:a,"data-open
11
11
  return e.jsx(qc,{...c.useAppConfig().render.standalone?{defaultValue:"details"}:{},children:/*#__PURE__*/e.jsxs(Vc,{value:"details",children:[/*#__PURE__*/e.jsx(Gc,{children:/*#__PURE__*/e.jsxs(od,{children:[/*#__PURE__*/e.jsx("div",{children:a?.title||"Details"}),/*#__PURE__*/e.jsx(sd,{children:/*#__PURE__*/e.jsx(jc,{weiQuantities:[l],tokenPrice:i,tokenSymbol:s})})]})}),/*#__PURE__*/e.jsxs($c,{children:[/*#__PURE__*/e.jsx(_c,{label:"From",children:/*#__PURE__*/e.jsx(nd,{walletAddress:t,chainId:n.chainId||c.CHAIN_ID_MAINNET,network:"ethereum"})}),/*#__PURE__*/e.jsx(_c,{label:"To",children:/*#__PURE__*/e.jsx(nd,{walletAddress:r,chainId:n.chainId||c.CHAIN_ID_MAINNET,network:"ethereum"})}),a&&a.action&&/*#__PURE__*/e.jsx(_c,{label:"Action",children:a.action}),o&&/*#__PURE__*/e.jsx(Lc,{value:n.value,gas:o,tokenPrice:i,tokenSymbol:s})]}),/*#__PURE__*/e.jsx(Kc,{children:({isActive:t})=>/*#__PURE__*/e.jsx(Uc,{value:n.value,displayFee:t,gas:o||"0x0",tokenPrice:i,tokenSymbol:s})})]})})};let od=/*#__PURE__*/C.styled.div.withConfig({displayName:"AccordionTriggerContent",componentId:"sc-29499c17-0"})(["display:flex;flex-direction:row;justify-content:space-between;"]),sd=/*#__PURE__*/C.styled.div.withConfig({displayName:"TotalText",componentId:"sc-29499c17-1"})(["flex-shrink:0;padding-left:8px;"]);async function ld(e,t,r){let n=pr(e),a=await t.prepareTransactionRequest({...n,account:{address:r,type:"json-rpc"}});return{...a,type:ur[a.type]}}const cd=({pendingTransaction:t})=>{let{getAccessToken:n}=c.usePrivyContext(),{wallets:a}=c.useWallets(),{walletProxy:o,rpcConfig:s,chains:l,appId:d,nativeTokenSymbolForChainId:u}=i.usePrivyInternal(),[h,p]=r.useState(null),[g,f]=r.useState(t),{tokenPrice:w}=Po(g.chainId),v=u(t.chainId)||"ETH",C=r.useMemo((()=>a.find((e=>"privy"===e.walletClientType))),[a]);return r.useEffect((()=>{(async function(){if(!await n()||!o||!C)return g;let e=m.getPublicClient(g.chainId,l,s,{appId:d}),t=await ld(g,e,C.address);return p(y.toHex(BigInt(t.gas??0))),t})().then(f).catch(console.error)}),[o]),C?/*#__PURE__*/e.jsx(dd,{children:/*#__PURE__*/e.jsx(id,{from:C.address,to:g.to,txn:g,gas:h??void 0,tokenPrice:w,tokenSymbol:v})}):null};let dd=/*#__PURE__*/C.styled.div.withConfig({displayName:"TransactionInfoWrapper",componentId:"sc-731f1950-0"})(["width:100%;padding:1rem 0;"]);const ud=({hasBlockingError:t,error:r,onClose:n,onBack:a,handleSubmit:o,account:l,submitSuccess:c})=>{let{pendingTransaction:d}=i.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:n},"header"),/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:c,fail:!!r}),r?/*#__PURE__*/e.jsx(Pe.default,{style:{width:"38px",height:"38px"}}):/*#__PURE__*/e.jsx(rs,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsx(bn,{style:{marginTop:"1rem"},children:"Verifying with passkey"}),/*#__PURE__*/e.jsxs(Pn,{children:[/*#__PURE__*/e.jsxs(kn,{children:[/*#__PURE__*/e.jsx(jn,{children:/*#__PURE__*/e.jsx(dt.default,{})}),"Approve this action using your touch, face, PIN, or hardware key."]}),/*#__PURE__*/e.jsxs(kn,{children:[/*#__PURE__*/e.jsx(jn,{children:/*#__PURE__*/e.jsx(gt.default,{})}),"You last added a passkey on"," ",l?.firstVerifiedAt?.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),"."]})]}),d&&/*#__PURE__*/e.jsx(In,{children:/*#__PURE__*/e.jsx(cd,{pendingTransaction:d})}),r&&/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Hn,{style:{marginTop:"1.25rem"},children:r.message}),/*#__PURE__*/e.jsx(s.PrimaryButton,{disabled:t,onClick:o,style:{marginTop:"1.25rem"},children:"Try again"})]}),a&&/*#__PURE__*/e.jsx(Dn,{style:{marginTop:"1rem"},onClick:a,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},hd=({open:t,onClose:n})=>{let{user:a}=c.usePrivyContext(),[i,o]=r.useState(a?.mfaMethods[0]??null),{init:l,cancel:d,submit:u}=tc(),[h,p]=r.useState(!1),[y,m]=r.useState(!1),[g,f]=r.useState(null),[w,v]=r.useState(null);r.useEffect((()=>{o(a?.mfaMethods[0]??null)}),[a?.mfaMethods]);let C=r.useRef(!1);r.useEffect((()=>{!C.current&&i&&t&&(C.current=!0,S(i).finally((()=>{C.current=!1})))}),[t]);let x=e=>qa(e)?(p(!0),Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.")):za(e)?(p(!1),Error("The code you entered is not valid")):Ha(e)?(p(!0),Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.")):(console.error(e),p(!1),Error("Something went wrong."));async function E(e){v(null);try{if(!e||!i)return;await u(i,e),m(!0),p(!1),n()}catch(e){throw x(e)}}async function S(e){if("passkey"!==e)try{o(e),await l(e)}catch(e){console.error(e)}else try{o(e);let t=await l(e);if(!t)throw Error("something went wrong");f(t),await u(e,t),m(!0),p(!1),n()}catch(e){v(x(e))}}let T=()=>{o(null),v(null),d(),n()};return t&&a?"passkey"===i?/*#__PURE__*/e.jsx(ud,{account:a.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],selectedMethod:i,submitSuccess:y,hasBlockingError:h,error:w,onClose:T,onBack:()=>{o(null),v(null)},handleSubmit:()=>E(g).catch(v)}):i?/*#__PURE__*/e.jsx(pd,{submitSuccess:y,hasBlockingError:h,handleSubmitCode:E,selectedMethod:i,onClose:T,onBack:a.mfaMethods.length>1?()=>o(null):void 0}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:T},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(dt.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Verify your identity"}),/*#__PURE__*/e.jsx(_n,{children:"Choose a verification method"}),/*#__PURE__*/e.jsxs(Mn,{children:[a.mfaMethods.includes("totp")&&/*#__PURE__*/e.jsxs(rn,{onClick:()=>S("totp"),children:[/*#__PURE__*/e.jsx(ht.default,{}),"Authenticator App"]},"totp"),a.mfaMethods.includes("sms")&&/*#__PURE__*/e.jsxs(rn,{onClick:()=>S("sms"),children:[/*#__PURE__*/e.jsx(Le.default,{}),"SMS"]},"sms"),a.mfaMethods.includes("passkey")&&/*#__PURE__*/e.jsxs(rn,{onClick:()=>S("passkey"),children:[/*#__PURE__*/e.jsx(ot.default,{}),"Passkey"]},"passkey")]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):null};let pd=({selectedMethod:t,submitSuccess:r,hasBlockingError:n,onClose:a,onBack:o,handleSubmitCode:l})=>{let{app:d}=c.usePrivyModal(),{pendingTransaction:u}=i.usePrivyInternal();switch(t){case"sms":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:a},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(Le.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(In,{children:[/*#__PURE__*/e.jsx(xc,{success:r,disabled:n,onChange:l}),/*#__PURE__*/e.jsxs(_n,{children:["To continue, please enter the 6-digit code sent to your ",/*#__PURE__*/e.jsx("strong",{children:"mobile device"})]}),u&&/*#__PURE__*/e.jsx(cd,{pendingTransaction:u})]}),o&&/*#__PURE__*/e.jsx(Dn,{theme:d?.appearance.palette.colorScheme,onClick:o,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:a,children:"Not now"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});case"totp":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:a},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ht.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(In,{children:[/*#__PURE__*/e.jsx(xc,{success:r,disabled:n,onChange:l}),/*#__PURE__*/e.jsxs(_n,{children:["To continue, please enter the 6-digit code generated from your"," ",/*#__PURE__*/e.jsx("strong",{children:"authenticator app"})]}),u&&/*#__PURE__*/e.jsx(cd,{pendingTransaction:u})]}),o&&/*#__PURE__*/e.jsx(Dn,{theme:d?.appearance.palette.colorScheme,onClick:o,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:a,children:"Not now"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});default:return null}};let yd=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-f0dc8bc7-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]);const md=/*#__PURE__*/C.styled.div.withConfig({displayName:"DoubleIconWrapper",componentId:"sc-fd7f30b7-0"})(["display:flex;align-items:center;justify-content:center;width:180px;height:90px;border-radius:50%;svg + svg{margin-left:12px;}> svg{z-index:2;color:var(--privy-color-accent);stroke:var(--privy-color-accent);fill:var(--privy-color-accent);}"]);let gd=/*#__PURE__*/C.styled.div.withConfig({displayName:"Container",componentId:"sc-d3724da1-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;"]);const fd=/*#__PURE__*/C.styled.div.withConfig({displayName:"Header",componentId:"sc-858d1103-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin:20px 0;gap:4px;& h3{font-size:18px;font-style:normal;font-weight:600;line-height:24px;}& p{max-width:300px;font-size:14px;font-style:normal;font-weight:400;line-height:20px;}"]);let wd=/*#__PURE__*/C.styled.div.withConfig({displayName:"Content",componentId:"sc-858d1103-1"})(["display:flex;flex-direction:column;justify-content:space-between;"]),vd=/*#__PURE__*/C.styled.div.withConfig({displayName:"ErrorMessage",componentId:"sc-858d1103-2"})(["line-height:20px;height:20px;font-size:13px;color:var(--privy-color-error);text-align:left;margin-top:0.5rem;"]),Cd=/*#__PURE__*/C.styled(s.PrimaryButton).withConfig({displayName:"NoAnimationPrimaryButton",componentId:"sc-858d1103-3"})(["",""],(e=>e.hideAnimations&&/*#__PURE__*/C.css(["&&{transition:none;}"])));const xd=t=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 21 20",...t,children:[/*#__PURE__*/e.jsx("path",{fill:"url(#icloud-gradient)",d:"M12.34 7.315a4.26 4.26 0 0 0-3.707 2.18 2.336 2.336 0 0 0-1.02-.236 2.336 2.336 0 0 0-2.3 1.963 3.217 3.217 0 0 0 1.244 6.181c.135-.001.27-.01.404-.029h8.943c.047.004.094.006.141.007.045-.001.09-.004.135-.007h.214v-.016a2.99 2.99 0 0 0 1.887-.988c.487-.55.757-1.261.757-1.998v-.006a3.017 3.017 0 0 0-.69-1.915 2.992 2.992 0 0 0-1.748-1.034 4.26 4.26 0 0 0-4.26-4.102Z"}),/*#__PURE__*/e.jsx("defs",{children:/*#__PURE__*/e.jsxs("linearGradient",{id:"icloud-gradient",x1:19.086,x2:3.333,y1:14.38,y2:14.163,gradientUnits:"userSpaceOnUse",children:[/*#__PURE__*/e.jsx("stop",{stopColor:"#3E82F4"}),/*#__PURE__*/e.jsx("stop",{offset:1,stopColor:"#93DCF7"})]})})]}),Ed=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{width:"16",height:"14",style:t,viewBox:"0 0 16 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",...r,children:[/*#__PURE__*/e.jsxs("g",{clipPath:"url(#clip0_2115_829)",children:[/*#__PURE__*/e.jsx("path",{d:"M2.34709 12.9404L2.3471 12.9404L2.34565 12.938L1.64031 11.7448L1.64004 11.7444L0.651257 10.0677C0.640723 10.0496 0.630746 10.0314 0.621325 10.0129H4.16461L2.39424 13.0139C2.3775 12.9901 2.36178 12.9656 2.34709 12.9404Z",fill:"#0066DA",stroke:"#6366F1"}),/*#__PURE__*/e.jsx("path",{d:"M8 4.48713L5.47995 0.215332C5.23253 0.358922 5.02176 0.556358 4.87514 0.80764L0.219931 8.70508C0.076007 8.95094 0.000191627 9.22937 0 9.51277H5.04009L8 4.48713Z",fill:"#00AC47"}),/*#__PURE__*/e.jsx("path",{d:"M13.48 13.7847C13.7274 13.6411 13.9382 13.4437 14.0848 13.1924L14.3781 12.6988L15.7801 10.3206C15.9267 10.0693 16.0001 9.79114 16.0001 9.51294H10.9596L12.0321 11.577L13.48 13.7847Z",fill:"#EA4335"}),/*#__PURE__*/e.jsx("path",{d:"M8.00003 4.48718L10.5201 0.215385C10.2726 0.0717949 9.98857 0 9.69533 0H6.30472C6.01148 0 5.7274 0.0807692 5.47998 0.215385L8.00003 4.48718Z",fill:"#00832D"}),/*#__PURE__*/e.jsx("path",{d:"M10.9599 9.51294H5.04007L2.52002 13.7847C2.76744 13.9283 3.05152 14.0001 3.34476 14.0001H12.6552C12.9484 14.0001 13.2325 13.9194 13.4799 13.7847L10.9599 9.51294Z",fill:"#2684FC"}),/*#__PURE__*/e.jsx("path",{d:"M13.4525 4.75636L11.1249 0.80764C10.9782 0.556358 10.7675 0.358922 10.52 0.215332L8 4.48713L10.9599 9.51277H15.9908C15.9908 9.23456 15.9175 8.95636 15.7709 8.70508L13.4525 4.75636Z",fill:"#FFBA00"})]}),/*#__PURE__*/e.jsx("defs",{children:/*#__PURE__*/e.jsx("clipPath",{id:"clip0_2115_829",children:/*#__PURE__*/e.jsx("rect",{width:"16",height:"14",fill:"white"})})})]}),Sd=/*#__PURE__*/C.styled.div.withConfig({displayName:"RecoveryContainer",componentId:"sc-12b46968-0"})(["display:flex;flex-direction:column;gap:12px;padding-top:24px;padding-bottom:24px;"]),Td=/*#__PURE__*/C.styled.div.withConfig({displayName:"RecoveryExplainerContainer",componentId:"sc-12b46968-1"})(["padding-bottom:24px;"]);let Ad={"google-drive":{name:"Google Drive",component:Ed},icloud:{name:"iCloud",component:xd}};let bd=/*#__PURE__*/C.styled.div.withConfig({displayName:"IconContainer",componentId:"sc-6716a2fa-0"})(["width:24px;height:24px;display:flex;justify-content:center;align-items:center;"]),_d={"google-drive":"Google Drive",icloud:"iCloud","user-passcode":"password",privy:"Privy"},Id=({onClose:t})=>/*#__PURE__*/e.jsxs(Td,{children:[/*#__PURE__*/e.jsx(Zn,{title:"Why do I need to secure my account?",icon:/*#__PURE__*/e.jsx(Ie.default,{width:48}),description:/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx("p",{children:"Your app uses cryptography to secure your account. App secrets are split and encrypted so only you can access them."}),/*#__PURE__*/e.jsx("p",{children:"To use this app on new devices, secure account secrets using a password, your Google or your Apple account. It’s important you don’t lose access to the method you choose."})]})}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:t,children:"Select backup method"})]});const Pd=/*#__PURE__*/C.styled.div.withConfig({displayName:"WithCircleBorder",componentId:"sc-e4fc5563-0"})(["&&{border-width:4px;}display:flex;justify-content:center;align-items:center;padding:1rem;aspect-ratio:1;border-style:solid;border-color:",";border-radius:50%;"],(e=>e.$color??"var(--privy-color-accent)"));async function jd({tx:e,accessToken:t,walletProxy:r,entropyId:n,entropyIdVerifier:a,transactingWalletAddress:i,transactingWalletIndex:o}){let s=function(e,t){let r=(Oo(e)?e.message:e.compileMessage()).staticAccountKeys.find((e=>e.toBase58()===t));if(!r)throw Error(`Transaction does not contain public key ${t}`);return r}(e,i),l=Oo(e)?Buffer.from(e.message.serialize()):e.serializeMessage(),{response:c}=await r.rpc({accessToken:t,entropyId:n,entropyIdVerifier:a,chainType:"solana",hdWalletIndex:o,request:{method:"signMessage",params:{message:l.toString("base64")}}}),d=c.data.signature,u=Buffer.from(d,"base64");e.addSignature(s,u)}async function kd({tx:e,connection:t,accessToken:r,walletProxy:n,entropyId:a,entropyIdVerifier:i,transactingWalletAddress:o,transactingWalletIndex:s,transactionOptions:l}){let c;try{await jd({tx:e,accessToken:r,walletProxy:n,entropyId:a,entropyIdVerifier:i,transactingWalletAddress:o,transactingWalletIndex:s});let d=e.serialize();c=await t.sendRawTransaction(d,l);let u=await t.confirmTransaction(c);if(u.value.err||u.value.err){let e=u.value.err||u.value.err;if("string"==typeof e)throw Error(e);throw e}return{signature:c,signedTransaction:e,receipt:await t.getParsedTransaction(c,{maxSupportedTransactionVersion:0})}}catch(e){throw e.txSignature=c,e}}const Nd=/*#__PURE__*/C.styled(Ho).withConfig({displayName:"InteractiveLabel",componentId:"sc-b57d0824-0"})(["cursor:pointer;display:inline-flex;gap:8px;align-items:center;color:var(--privy-color-accent);svg{fill:var(--privy-color-accent);}"]);var Md=({iconUrl:t,value:r,symbol:n,usdValue:a,nftName:i,$isLoading:o})=>o?/*#__PURE__*/e.jsx(Rd,{$isLoading:o}):/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsxs(Rd,{$isLoading:o,children:[t&&/*#__PURE__*/e.jsx(Wd,{src:t,alt:"Token icon"}),i,r," ",n]}),a&&/*#__PURE__*/e.jsxs(Od,{$isLoading:o,children:["$",a]})]});let Rd=/*#__PURE__*/C.styled.span.withConfig({displayName:"Value",componentId:"sc-d8e62921-0"})(["color:var(--privy-color-foreground);font-size:0.875rem;font-weight:500;line-height:1.375rem;word-break:break-all;text-align:right;display:flex;justify-content:flex-end;",""],s.LoadingSkeleton);const Od=/*#__PURE__*/C.styled.span.withConfig({displayName:"Subvalue",componentId:"sc-d8e62921-1"})(["color:var(--privy-color-foreground-2);font-size:12px;font-weight:400;line-height:18px;word-break:break-all;text-align:right;display:flex;justify-content:flex-end;",""],s.LoadingSkeleton);let Wd=/*#__PURE__*/C.styled.img.withConfig({displayName:"TokenIcon",componentId:"sc-d8e62921-2"})(["height:14px;width:14px;margin-right:4px;object-fit:contain;"]);const Ld=t=>{let{chain:r,transactionDetails:n,isTokenContractInfoLoading:a,symbol:i}=t,{action:o,functionName:l}=n;/*#__PURE__*/return e.jsx(s.Box,{children:/*#__PURE__*/e.jsxs(s.Rows,{children:["transaction"!==o&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Action"}),/*#__PURE__*/e.jsx(qo,{children:l})]}),"mint"===l&&"args"in n&&n.args.filter((e=>e)).map(((t,n)=>/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:`Param ${n}`}),/*#__PURE__*/e.jsx(qo,{children:"string"==typeof t&&y.isAddress(t)?/*#__PURE__*/e.jsx(s.Address,{address:t,url:r?.blockExplorers?.default?.url,showCopyIcon:!1}):t?.toString()})]},n))),"setApprovalForAll"===l&&n.operator&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Operator"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:n.operator,url:r?.blockExplorers?.default?.url,showCopyIcon:!1})})]}),"setApprovalForAll"===l&&void 0!==n.approved&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Set approval to"}),/*#__PURE__*/e.jsx(qo,{children:n.approved?"true":"false"})]}),"transfer"===l||"transferFrom"===l||"safeTransferFrom"===l||"approve"===l?/*#__PURE__*/e.jsxs(e.Fragment,{children:["formattedAmount"in n&&n.formattedAmount&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Amount"}),/*#__PURE__*/e.jsxs(qo,{$isLoading:a,children:[n.formattedAmount," ",i]})]}),"tokenId"in n&&n.tokenId&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token ID"}),/*#__PURE__*/e.jsx(qo,{children:n.tokenId.toString()})]})]}):null,"safeBatchTransferFrom"===l&&/*#__PURE__*/e.jsxs(e.Fragment,{children:["amounts"in n&&n.amounts&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Amounts"}),/*#__PURE__*/e.jsx(qo,{children:n.amounts.join(", ")})]}),"tokenIds"in n&&n.tokenIds&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token IDs"}),/*#__PURE__*/e.jsx(qo,{children:n.tokenIds.join(", ")})]})]}),"approve"===l&&n.spender&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Spender"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:n.spender,url:r?.blockExplorers?.default?.url,showCopyIcon:!1})})]}),("transferFrom"===l||"safeTransferFrom"===l||"safeBatchTransferFrom"===l)&&n.transferFrom&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Transferring from"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:n.transferFrom,url:r?.blockExplorers?.default?.url,showCopyIcon:!1})})]}),("transferFrom"===l||"safeTransferFrom"===l||"safeBatchTransferFrom"===l)&&n.transferTo&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Transferring to"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:n.transferTo,url:r?.blockExplorers?.default?.url,showCopyIcon:!1})})]})]})})};let Ud={success:"background: var(--privy-color-success-lightest, #dcfce7);",warn:"background: var(--privy-color-warn-lightest, #fff7e6);",error:"background: var(--privy-color-error-lightest, #fde8e8);"};const Fd=/*#__PURE__*/C.styled.div.withConfig({displayName:"Pill",componentId:"sc-8c138024-0"})(["border-radius:var(--privy-border-radius-md,8px);padding:12px;text-align:left;margin-top:23px;",""],(e=>Ud[e.variant])),Dd=({variant:t,setPreventMaliciousTransaction:r,preventMaliciousTransaction:n})=>"warn"===t?/*#__PURE__*/e.jsx(Fd,{variant:t,children:/*#__PURE__*/e.jsxs("div",{className:"flex flex-row",children:[/*#__PURE__*/e.jsx(Bd,{variant:t}),/*#__PURE__*/e.jsxs("p",{children:[/*#__PURE__*/e.jsx("b",{children:"Warning: Suspicious transaction"}),/*#__PURE__*/e.jsx("br",{}),"This has been flagged as a potentially deceptive request. Approving could put your assets or funds at risk."]})]})}):"error"===t?/*#__PURE__*/e.jsx(Fd,{variant:t,children:/*#__PURE__*/e.jsxs("div",{className:"flex flex-col",children:[/*#__PURE__*/e.jsxs("div",{className:"flex flex-row",children:[/*#__PURE__*/e.jsx(Bd,{variant:t}),/*#__PURE__*/e.jsxs("p",{children:[/*#__PURE__*/e.jsx("b",{children:"This is a malicious transaction"}),/*#__PURE__*/e.jsx("br",{}),"This transaction transfers tokens to a known malicious address. Proceeding may result in the loss of valuable assets."]})]}),/*#__PURE__*/e.jsxs("div",{className:"mt-3 flex flex-row gap-2",children:[/*#__PURE__*/e.jsx(Ai,{color:"var(--privy-color-error)",checked:!n,readOnly:!0,onClick:()=>r(!n)}),/*#__PURE__*/e.jsx("p",{children:"I understand and want to proceed anyways."})]})]})}):void 0;let Bd=/*#__PURE__*/C.styled(Pe.default).withConfig({displayName:"StyledExclamationTriangleIcon",componentId:"sc-e6305f32-0"})(["width:20px;height:20px;stroke-width:2px;flex-shrink:0;display:inline-block;margin-right:8px;",";"],(e=>"error"===e.variant?"color: var(--privy-color-error)":"color: var(--privy-color-warn)"));const Hd=({transactionIndex:e,maxIndex:t})=>"number"!=typeof e||0===t?"":` (${e+1} / ${t+1})`,zd=({img:t,submitError:n,prepareError:a,onClose:i,action:o,title:l,subtitle:c,txValue:d,to:u,tokenAddress:h,network:p,missingFunds:y,fee:m,from:g,cta:f,disabled:w,chain:v,isSubmitting:C,isPreparing:x,isTokenPriceLoading:E,isTokenContractInfoLoading:S,isSponsored:T,symbol:A,balance:b,onClick:_,transactionDetails:I,transactionIndex:P,maxIndex:j,onBack:k,chainName:N,validation:M,hasScanDetails:R,setIsScanDetailsOpen:O,preventMaliciousTransaction:W,setPreventMaliciousTransaction:L,tokensSent:U,tokensReceived:F,isScanning:D,isCancellable:B})=>{let{showTransactionDetails:H,setShowTransactionDetails:z,hasMoreDetails:q,isErc20Ish:V}=(e=>{let[t,n]=r.useState(!1),a=!0,i=!1;return(!e||e.isErc20Ish||"transaction"===e.action)&&(a=!1),a&&(i=Object.entries(e||{}).some((([e,t])=>t&&!["action","isErc20Ish","isNFTIsh"].includes(e)))),{showTransactionDetails:t,setShowTransactionDetails:n,hasMoreDetails:a&&i,isErc20Ish:e?.isErc20Ish}})(I),G=V&&S||x||E||D;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:i,backFn:k}),t&&/*#__PURE__*/e.jsx($d,{children:t}),/*#__PURE__*/e.jsxs(s.Title,{style:{marginTop:t?"1.5rem":0},children:[l,/*#__PURE__*/e.jsx(Hd,{maxIndex:j,transactionIndex:P})]}),/*#__PURE__*/e.jsx(s.Subtitle,{children:c}),/*#__PURE__*/e.jsxs(s.Rows,{style:{marginTop:"2rem"},children:[(!!U[0]||G)&&/*#__PURE__*/e.jsxs(s.Row,{children:[F.length>0?/*#__PURE__*/e.jsx(Ho,{children:"Send"}):/*#__PURE__*/e.jsx(Ho,{children:"Amount"}),/*#__PURE__*/e.jsx(Md,{iconUrl:U[0]?.iconUrl,value:U[0]?.value,usdValue:U[0]?.usdValue,symbol:U[0]?.symbol,nftName:U[0]?.nftName,$isLoading:G})]}),F.length>0&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Receive"}),/*#__PURE__*/e.jsx("div",{className:"flex flex-col",children:F.map(((t,r)=>/*#__PURE__*/e.jsx(Md,{iconUrl:t.iconUrl,value:t.value,usdValue:t.usdValue,symbol:t.symbol,nftName:t.nftName},r)))})]}),I&&"spender"in I&&I?.spender?/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Spender"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:I.spender,url:v?.blockExplorers?.default?.url,showCopyIcon:!1})})]}):null,u&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"To"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:u,url:v?.blockExplorers?.default?.url,showCopyIcon:!1})})]}),h&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token address"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:h,url:v?.blockExplorers?.default?.url,showCopyIcon:!1})})]}),/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Network"}),/*#__PURE__*/e.jsx(qo,{children:p})]}),/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Estimated fee"}),/*#__PURE__*/e.jsx(qo,{$isLoading:x||E||void 0===T,children:T?"Sponsored":m})]}),q&&!R&&/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.Row,{className:"cursor-pointer",onClick:()=>z(!H),children:/*#__PURE__*/e.jsxs(zo,{className:"flex items-center gap-x-1",children:["Details"," ",/*#__PURE__*/e.jsx(ge.ChevronDownIcon,{style:{width:"0.75rem",marginLeft:"0.25rem",transform:H?"rotate(180deg)":void 0}})]})}),H&&I&&/*#__PURE__*/e.jsx(Ld,{action:o,chain:v,transactionDetails:I,isTokenContractInfoLoading:S,symbol:A})]}),R&&/*#__PURE__*/e.jsx(s.Row,{children:/*#__PURE__*/e.jsxs(Nd,{onClick:()=>O(!0),children:[/*#__PURE__*/e.jsx("span",{className:"text-color-primary",children:"Details"}),/*#__PURE__*/e.jsx(ge.ArrowRightIcon,{height:"14px",width:"14px",strokeWidth:"2"})]})})]}),/*#__PURE__*/e.jsx(Zr,{}),n?/*#__PURE__*/e.jsx(s.ErrorMessage,{style:{marginTop:"2rem"},children:n.message}):a?/*#__PURE__*/e.jsx(s.ErrorMessage,{style:{marginTop:"2rem"},children:a.shortMessage??Gd}):null,/*#__PURE__*/e.jsx(Dd,{variant:M,preventMaliciousTransaction:W,setPreventMaliciousTransaction:L}),/*#__PURE__*/e.jsx(Vd,{$useSmallMargins:!(!a&&!n&&"warn"!==M&&"error"!==M),title:Number(d)>0?void 0:!1!==T?"Your wallet":void 0,address:g,balance:b,isLoading:x||E,errMsg:x||a||n||!y?void 0:`Add funds on ${v?.name??N} to complete transaction.`}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"1rem"},loading:C,disabled:w||x,onClick:_,children:f}),B&&/*#__PURE__*/e.jsx(s.EmbeddedButton,{style:{marginTop:"1rem"},onClick:i,isSubmitting:!1,children:"Not now"}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},qd=({img:t,title:r,subtitle:n,cta:a,network:i,blockExplorerUrl:o,transactionIndex:l,maxIndex:c,isMissingFunds:d,submitError:u,parseError:h,total:p,amount:y,fee:m,balance:g,from:f,to:w,tokenAddress:v,tokenAccount:C,tokenAccountOwner:x,programAddress:E,transactingWalletAddress:S,disabled:T,isSubmitting:A,isPreparing:b,isTokenPriceLoading:_,onClick:I,onClose:P,onBack:j})=>{let k=b||_;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:P,backFn:j}),t&&/*#__PURE__*/e.jsx($d,{children:t}),/*#__PURE__*/e.jsxs(s.Title,{style:{marginTop:t?"1.5rem":0},children:[r,/*#__PURE__*/e.jsx(Hd,{maxIndex:c,transactionIndex:l})]}),/*#__PURE__*/e.jsx(s.Subtitle,{children:n}),/*#__PURE__*/e.jsxs(s.Rows,{style:{marginTop:"2rem"},children:[(p||k)&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Total"}),/*#__PURE__*/e.jsx(qo,{$isLoading:k,children:p})]}),f&&f!==S&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"From"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:f,url:o,showCopyIcon:!1})})]}),w&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"To"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:w,url:o,showCopyIcon:!1})})]}),x&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token account owner"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:x,url:o,showCopyIcon:!1})})]}),C&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token account"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:C,url:o,showCopyIcon:!1})})]}),v&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token address"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:v,url:o,showCopyIcon:!1})})]}),E&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Program address"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(s.Address,{address:E,url:o,showCopyIcon:!1})})]}),i&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Network"}),/*#__PURE__*/e.jsx(qo,{children:i})]}),(y||k)&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Amount"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(qo,{$isLoading:k,children:y})})]}),(m||k)&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Estimated fee"}),/*#__PURE__*/e.jsx(qo,{$isLoading:k,children:m})]})]}),/*#__PURE__*/e.jsx(Zr,{}),u?/*#__PURE__*/e.jsx(s.ErrorMessage,{style:{marginTop:"2rem"},children:u.message}):h?/*#__PURE__*/e.jsx(s.ErrorMessage,{style:{marginTop:"2rem"},children:Gd}):null,/*#__PURE__*/e.jsx(Vd,{$useSmallMargins:!(!h&&!u),title:"Your wallet",address:S,balance:g,isLoading:b||_,errMsg:b||h||u||!d?void 0:"Add funds on Solana to complete transaction."}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"1rem"},loading:A,disabled:T||b,onClick:I,children:a}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})};let Vd=/*#__PURE__*/C.styled(s.WalletInfoCard).withConfig({displayName:"StyledWalletInfoCard",componentId:"sc-4bd3bb7d-0"})(["",""],(e=>e.$useSmallMargins?"margin-top: 0.5rem;":"margin-top: 2rem;")),Gd="There was an error preparing your transaction. Your transaction request will likely fail.",$d=/*#__PURE__*/C.styled.div.withConfig({displayName:"ImageContainer",componentId:"sc-4bd3bb7d-1"})(["display:flex;width:100%;justify-content:center;max-height:40px;> img{object-fit:contain;border-radius:var(--privy-border-radius-sm);}"]),Kd=()=>/*#__PURE__*/e.jsxs(Jd,{children:[/*#__PURE__*/e.jsx(tu,{}),/*#__PURE__*/e.jsx(eu,{})]});const Yd=({transactionError:t,chainId:n,onClose:a,onRetry:o,network:l,connection:d,transactionHash:u})=>{let{chains:h}=i.usePrivyInternal(),[p,y]=r.useState(!1),{errorCode:m,errorMessage:g}=((e,t)=>{if("ethereum"===t)return{errorCode:e.details??e.message,errorMessage:e.shortMessage};let r=e.txSignature,n=e?.transactionMessage||"Something went wrong.";if(Array.isArray(e.logs)){let t=e.logs.find((e=>/insufficient (lamports|funds)/gi.test(e)));t&&(n=t)}return{transactionHash:r,errorMessage:n}})(t,l),f=(({chains:e,chainId:t,network:r,connection:n,transactionHash:a})=>"ethereum"===r?e.find((e=>e.id===t))?.blockExplorers?.default.url??"https://etherscan.io":c.getSolanaTransactionExplorerUrl(a||"",c.getSolanaNetworkFromRpcEndpoint(n?.rpcEndpoint||"")))({chains:h,chainId:n,network:l,connection:d,transactionHash:u});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:a}),/*#__PURE__*/e.jsxs(Zd,{children:[/*#__PURE__*/e.jsx(Kd,{}),/*#__PURE__*/e.jsx(Xd,{children:m}),/*#__PURE__*/e.jsx(Qd,{children:"Please try again."}),/*#__PURE__*/e.jsxs(au,{children:[/*#__PURE__*/e.jsx(nu,{children:"Error message"}),/*#__PURE__*/e.jsx(ou,{$clickable:!1,children:g})]}),u&&/*#__PURE__*/e.jsxs(au,{children:[/*#__PURE__*/e.jsx(nu,{children:"Transaction hash"}),/*#__PURE__*/e.jsxs(iu,{children:["Copy this hash to view details about the transaction on a"," ",/*#__PURE__*/e.jsx("u",{children:/*#__PURE__*/e.jsx("a",{href:f,children:"block explorer"})}),"."]}),/*#__PURE__*/e.jsxs(ou,{$clickable:!0,onClick:async()=>{await navigator.clipboard.writeText(u),y(!0)},children:[u,/*#__PURE__*/e.jsx(cu,{clicked:p})]})]}),/*#__PURE__*/e.jsx(ru,{onClick:()=>o({resetNonce:!!u}),children:"Retry transaction"})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})};let Zd=/*#__PURE__*/C.styled.div.withConfig({displayName:"TransactionErrorScreenContainer",componentId:"sc-6e9001c5-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;"]),Xd=/*#__PURE__*/C.styled.span.withConfig({displayName:"ErrorCode",componentId:"sc-6e9001c5-1"})(["color:var(--privy-color-foreground);text-align:center;font-size:1.125rem;font-weight:500;line-height:1.25rem;text-align:center;margin:10px;"]),Qd=/*#__PURE__*/C.styled.span.withConfig({displayName:"Subtitle",componentId:"sc-6e9001c5-2"})(["margin-top:4px;margin-bottom:10px;color:var(--privy-color-foreground-3);text-align:center;font-size:0.875rem;font-style:normal;font-weight:400;line-height:20px;letter-spacing:-0.008px;"]),Jd=/*#__PURE__*/C.styled.div.withConfig({displayName:"CircleContainer",componentId:"sc-6e9001c5-3"})(["position:relative;width:60px;height:60px;margin:10px;display:flex;justify-content:center;align-items:center;"]),eu=/*#__PURE__*/C.styled(ke.default).withConfig({displayName:"StyledExclamationCircleIcon",componentId:"sc-6e9001c5-4"})(["position:absolute;width:35px;height:35px;color:var(--privy-color-error);"]),tu=/*#__PURE__*/C.styled.div.withConfig({displayName:"StyledRedCircle",componentId:"sc-6e9001c5-5"})(["position:absolute;width:60px;height:60px;border-radius:50%;background-color:var(--privy-color-error);opacity:0.1;"]),ru=/*#__PURE__*/C.styled(s.PrimaryButton).withConfig({displayName:"RetryButton",componentId:"sc-6e9001c5-6"})(["&&{margin-top:24px;}transition:color 350ms ease,background-color 350ms ease;"]),nu=/*#__PURE__*/C.styled.span.withConfig({displayName:"TextBoxTitle",componentId:"sc-6e9001c5-7"})(["width:100%;text-align:left;font-size:0.825rem;color:var(--privy-color-foreground);padding:4px;"]),au=/*#__PURE__*/C.styled.div.withConfig({displayName:"TextBoxContainer",componentId:"sc-6e9001c5-8"})(["width:100%;margin:5px;display:flex;flex-direction:column;justify-content:center;align-items:center;"]),iu=/*#__PURE__*/C.styled.text.withConfig({displayName:"HelperText",componentId:"sc-6e9001c5-9"})(["position:relative;width:100%;padding:5px;font-size:0.8rem;color:var(--privy-color-foreground-3);text-align:left;word-wrap:break-word;"]),ou=/*#__PURE__*/C.styled.span.withConfig({displayName:"TextBox",componentId:"sc-6e9001c5-10"})(["position:relative;width:100%;background-color:var(--privy-color-background-2);padding:8px 12px;border-radius:10px;margin-top:5px;font-size:14px;color:var(--privy-color-foreground-3);text-align:left;word-wrap:break-word;",""],(e=>e.$clickable&&"cursor: pointer;\n transition: background-color 0.3s;\n padding-right: 45px;\n\n &:hover {\n background-color: var(--privy-color-foreground-4);\n }")),su=/*#__PURE__*/C.styled(Ct.default).withConfig({displayName:"StyledClipboardIcon",componentId:"sc-6e9001c5-11"})(["position:absolute;top:13px;right:13px;width:24px;height:24px;"]),lu=/*#__PURE__*/C.styled(Ze.default).withConfig({displayName:"StyledClipboardCheckIcon",componentId:"sc-6e9001c5-12"})(["position:absolute;top:13px;right:13px;width:24px;height:24px;"]),cu=({clicked:t})=>t?/*#__PURE__*/e.jsx(lu,{}):/*#__PURE__*/e.jsx(su,{});const du=({instructions:t,fees:n,transactionInfo:a,solPrice:i,rpcEndpoint:o})=>{let l=t.reduce(((e,{amount:t,token:r})=>t&&"SOL"===r?.symbol?e+t:e),0n),[c,d]=r.useState(0),[u,h]=r.useState(!1),p=t[c];/*#__PURE__*/return e.jsxs(s.Rows,{children:[/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Total"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(Nc,{quantities:[l,n],tokenPrice:i})})]}),a&&a.action&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Action"}),/*#__PURE__*/e.jsx(qo,{children:a.action})]}),/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Fees"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(Nc,{quantities:[n||0n],tokenPrice:i})})]}),t.length>1?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.Row,{children:/*#__PURE__*/e.jsxs(Nd,{onClick:()=>h((e=>!e)),children:[/*#__PURE__*/e.jsx("span",{children:"Details"}),/*#__PURE__*/e.jsx(et.default,{height:"16px",width:"16px",strokeWidth:"2",style:{transition:"all 300ms",transform:u?"rotate(180deg)":void 0}})]})}),u&&/*#__PURE__*/e.jsx(s.Row,{children:/*#__PURE__*/e.jsxs(hu,{children:[/*#__PURE__*/e.jsxs(pu,{children:[/*#__PURE__*/e.jsxs(yu,{children:[c+1," of ",t.length," instructions"]}),/*#__PURE__*/e.jsxs(gu,{children:[c>0&&/*#__PURE__*/e.jsx(s.BackButton,{backFn:()=>d((e=>e-1))}),c<t.length-1&&/*#__PURE__*/e.jsx(s.NextButton,{nextFn:()=>d((e=>e+1))})]})]}),/*#__PURE__*/e.jsx(mu,{children:/*#__PURE__*/e.jsx(uu,{instruction:p,rpcEndpoint:o,solPrice:i})})]})})]}):/*#__PURE__*/e.jsx(uu,{instruction:p,rpcEndpoint:o,solPrice:i,hideAmount:!0})]})};function uu({instruction:t,rpcEndpoint:r,solPrice:n,hideAmount:a}){return t?/*#__PURE__*/e.jsxs(s.Rows,{children:[!a&&!!t.amount&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Amount"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(Nc,{quantities:[t.amount],tokenPrice:n,tokenSymbol:t.token?.symbol??"SOL",tokenDecimals:t.token?.decimals??9})})]}),t.to&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"To"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(nd,{walletAddress:t.to,rpcEndpoint:r,network:"solana"})})]}),t.tokenAccount&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token account"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(nd,{walletAddress:t.tokenAccount,rpcEndpoint:r,network:"solana"})})]}),t.tokenAccountOwner&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"Token account owner"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(nd,{walletAddress:t.tokenAccountOwner,rpcEndpoint:r,network:"solana"})})]}),t.from&&/*#__PURE__*/e.jsxs(s.Row,{children:[/*#__PURE__*/e.jsx(Ho,{children:"From"}),/*#__PURE__*/e.jsx(qo,{children:/*#__PURE__*/e.jsx(nd,{walletAddress:t.from,rpcEndpoint:r,network:"solana"})})]})]}):null}let hu=/*#__PURE__*/C.styled.div.withConfig({displayName:"InstructionsBox",componentId:"sc-5a140027-0"})(["display:flex;flex-direction:column;width:100%;overflow:hidden;&&{border:1px solid;border-color:var(--privy-color-foreground-4);border-radius:var(--privy-border-radius-md);}"]),pu=/*#__PURE__*/C.styled.header.withConfig({displayName:"InstructionsBoxHeader",componentId:"sc-5a140027-1"})(["display:flex;justify-content:space-between;align-items:center;padding:12px;background-color:var(--privy-color-background-2);"]),yu=/*#__PURE__*/C.styled.h4.withConfig({displayName:"HeaderTitle",componentId:"sc-5a140027-2"})(["font-size:14px;font-weight:500;line-height:19.6px;"]),mu=/*#__PURE__*/C.styled.div.withConfig({displayName:"InstructionsBoxContent",componentId:"sc-5a140027-3"})(["padding:12px;"]),gu=/*#__PURE__*/C.styled.div.withConfig({displayName:"NavigationButtonsConatiner",componentId:"sc-5a140027-4"})(["display:flex;gap:8px;align-items:center;"]);const fu=({instructions:t,fees:r,onClose:n,receiptHeader:a,receiptDescription:i,transactionInfo:o,solPrice:l,rpcEndpoint:c,signOnly:d})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:n}),/*#__PURE__*/e.jsx(Yr,{style:{marginBottom:"16px"},children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(Kr,{color:"var(--privy-color-success-light)"}),/*#__PURE__*/e.jsx(De.default,{height:38,width:38,strokeWidth:2,stroke:"var(--privy-color-success)"})]})}),/*#__PURE__*/e.jsx(Zn,{title:a??`Transaction ${d?"signed":"complete"}!`,description:i??"You're all set."}),/*#__PURE__*/e.jsx(du,{solPrice:l,instructions:t,fees:r,transactionInfo:o,rpcEndpoint:c}),/*#__PURE__*/e.jsx(Zr,{}),/*#__PURE__*/e.jsx(wu,{loading:!1,onClick:n,children:"Close"}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let wu=/*#__PURE__*/C.styled(s.PrimaryButton).withConfig({displayName:"SubmitButton",componentId:"sc-6f95cdcf-0"})(["&&{margin-top:24px;}transition:color 350ms ease,background-color 350ms ease;"]);async function vu({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWallet:n,walletProxy:a,transactionRequest:i,publicClient:o,requesterAppId:s}){let l=await Cu({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWallet:n,walletProxy:a,transactionRequest:i,requesterAppId:s});return await o.sendRawTransaction({serializedTransaction:l})}async function Cu({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWallet:n,walletProxy:a,transactionRequest:i,requesterAppId:o}){return(await a.rpc({entropyId:t,entropyIdVerifier:r,hdWalletIndex:n.walletIndex??0,chainType:"ethereum",accessToken:e,requesterAppId:o,request:{method:"eth_signTransaction",params:[i]}})).response.data}let xu=({data:t})=>{let r=t=>"object"==typeof t&&null!==t?/*#__PURE__*/e.jsx(Su,{children:Object.entries(t).map((([t,n])=>/*#__PURE__*/e.jsxs("li",{children:[/*#__PURE__*/e.jsxs("strong",{children:[t,":"]})," ",r(n)]},t)))}):/*#__PURE__*/e.jsx("span",{children:String(t)});/*#__PURE__*/return e.jsx("div",{children:r(t)})};const Eu=/*#__PURE__*/C.styled.div.withConfig({displayName:"Message",componentId:"sc-ccf49562-0"})(["margin-top:1.5rem;background-color:var(--privy-color-background-2);border-radius:var(--privy-border-radius-md);padding:12px;text-align:left;max-height:310px;overflow:scroll;white-space:pre-wrap;width:100%;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}"]);let Su=/*#__PURE__*/C.styled.ul.withConfig({displayName:"MessageList",componentId:"sc-ccf49562-1"})(["margin-left:12px !important;white-space:nowrap;&:first-child{margin-left:0 !important;}strong{font-weight:500 !important;}"]);const Tu=({data:t})=>/*#__PURE__*/e.jsx(Eu,{children:/*#__PURE__*/e.jsx(xu,{data:t})});let Au=/*#__PURE__*/C.styled.div.withConfig({displayName:"Container",componentId:"sc-b3a607dd-0"})(["display:flex;flex-direction:column;min-height:72px;"]);var bu=({onBack:t,details:r})=>/*#__PURE__*/e.jsxs(Au,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t}),/*#__PURE__*/e.jsx(Tu,{data:r}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let _u=({gasUsed:e,effectiveGasPrice:t})=>{if(e&&t)try{return y.toHex(e*t)}catch(e){return}};const Iu=({txn:t,receipt:r,transactionInfo:n,onClose:a,tokenPrice:i,tokenSymbol:o,receiptHeader:l,receiptDescription:c})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:a}),/*#__PURE__*/e.jsx(Kn,{title:l??"Transaction complete!",description:c??"You're all set."}),/*#__PURE__*/e.jsx(id,{tokenPrice:i,from:r.from,to:r.to,gas:_u(r),txn:t,transactionInfo:n,tokenSymbol:o}),/*#__PURE__*/e.jsx(Zr,{}),/*#__PURE__*/e.jsx(Pu,{loading:!1,onClick:a,children:"All Done"}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let Pu=/*#__PURE__*/C.styled(s.PrimaryButton).withConfig({displayName:"SubmitButton",componentId:"sc-f857236b-0"})(["&&{margin-top:24px;}transition:color 350ms ease,background-color 350ms ease;"]);const ju=[{constant:!1,inputs:[{name:"_salt",type:"bytes32"},{name:"_initializer",type:"bytes"}],name:"deployAccount",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"}],ku=[{name:"from",type:"address"},{name:"param2",type:"address"},{name:"param3",type:"bytes"},{name:"param4",type:"tuple",components:[]},{type:"tuple",components:[{name:"param5",type:"address"},{name:"param6",type:"uint256"},{name:"param7",type:"uint256"},{name:"encodedInitData",type:"bytes"}]}],Nu=[{constant:!1,inputs:[{name:"spender",type:"address"},{name:"value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"}],Mu=[{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"mint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"mint",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"}],name:"mint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"}],name:"mint",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"quantity",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"mint",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"quantity",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"mint",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"tokenIds",type:"uint256[]"},{internalType:"uint256[]",name:"quantities",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"mintBatch",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"tokenIds",type:"uint256[]"},{internalType:"uint256[]",name:"quantities",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"mintBatch",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"payable",type:"function"},{inputs:[{internalType:"uint256",name:"quantity",type:"uint256"}],name:"mint",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"quantity",type:"uint256"}],name:"mint",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"}],name:"safeMint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"}],name:"safeMint",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"string",name:"uri",type:"string"}],name:"safeMint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"string",name:"uri",type:"string"}],name:"safeMint",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeMint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeMint",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"string",name:"uri",type:"string"}],name:"safeMint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"string",name:"uri",type:"string"}],name:"safeMint",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"batchMint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"batchMint",outputs:[],stateMutability:"payable",type:"function"}],Ru=[{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"}],Ou=[{constant:!1,inputs:[{name:"_operator",type:"address"},{name:"_approved",type:"bool"}],name:"setApprovalForAll",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"}],Wu=[{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_tokenId",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"}],Lu=[{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_tokenIds",type:"uint256[]"},{name:"_amounts",type:"uint256[]"},{name:"_data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"}],Uu=[{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_tokenId",type:"uint256"},{name:"_amount",type:"uint256"},{name:"_data",type:"bytes"}],name:"safeTransferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"}],Fu=(e,t)=>{let r=Du(Nu,e);if(r)return{action:"approve",functionName:"approve",isErc20Ish:!0,isNFTIsh:!1,spender:r.args[0],amount:r.args[1]};let n=Du(Os,e);if(n)return{action:"transfer",functionName:"transfer",isErc20Ish:!0,isNFTIsh:!1,transferTo:n.args[0],amount:n.args[1]};if(!t)return{action:"transaction",functionName:"",isErc20Ish:!1,isNFTIsh:!1};let a=Du(ju,e);if(a&&"string"==typeof a.args[1]){let e=Bu(a.args[1]);if(e&&e[4].encodedInitData)return Fu(e[4].encodedInitData,t)}let i=Du(Ou,e);if(i)return{action:"approve",functionName:"setApprovalForAll",isNFTIsh:!0,isErc20Ish:!1,operator:i.args[0],approved:i.args[1]};let o=Du(Wu,e);if(o)return{action:"transfer",functionName:"transferFrom",isNFTIsh:!0,isErc20Ish:!1,transferFrom:o.args[0],transferTo:o.args[1],tokenId:o.args[2]};let s=Du(Ru,e);if(s)return{action:"transfer",functionName:"safeTransferFrom",isNFTIsh:!0,isErc20Ish:!1,transferFrom:s.args[0],transferTo:s.args[1],tokenId:s.args[2]};let l=Du(Uu,e);if(l)return{action:"transfer",functionName:"safeTransferFrom",isNFTIsh:!0,isErc20Ish:!1,transferFrom:l.args[0],transferTo:l.args[1],tokenId:l.args[2],amount:l.args[3]};let c=Du(Lu,e);if(c)return{action:"batch transfer",functionName:"safeBatchTransferFrom",isNFTIsh:!0,isErc20Ish:!1,transferFrom:c.args[0],transferTo:c.args[1],tokenIds:c.args[2],amounts:c.args[3]};let d=Du(Mu,e);return d?{action:"mint",functionName:d.functionName,isNFTIsh:!0,isErc20Ish:!1,args:d.args}:{action:"transaction",isErc20Ish:!1,isNFTIsh:!1}};let Du=(e,t)=>{try{let r=y.decodeFunctionData({abi:e,data:t});return{functionName:r.functionName,args:r.args||[]}}catch(e){return null}},Bu=e=>{try{if("string"==typeof e)return y.decodeAbiParameters(ku,`0x${e.slice(10)}`)}catch(e){return null}};const Hu=(e,t,n)=>{let[a,o]=r.useState(null),{getAccessToken:s}=c.usePrivyContext(),{walletProxy:l}=i.usePrivyInternal();return r.useEffect((()=>{a&&o(null),(async()=>{if(!await s()||!l||!t)return null;let r=[],a=!0,i=await ld(e,n,t.address).catch((t=>(t.details.includes("insufficient funds")?a=!1:r.push(t),e)));return{tx:i,totalGasEstimate:i.gas,hasFunds:a,errors:r}})().then(o)}),[e]),a};let zu=new d.PrivyProviderRpcError(new d.ProviderRpcError("There was an issue preparing your transaction",K.ProviderErrors.E32603_DEFAULT_INTERNAL_ERROR.eipCode)),qu=(e,t)=>e?.sendTransaction?"transactionRequest"in e.sendTransaction?e.sendTransaction.transactionRequest:e.sendTransaction.transactionRequests[t]:void 0;const Vu=/*#__PURE__*/C.styled.img.withConfig({displayName:"StyledLogo",componentId:"sc-68c1b1ea-0"})(["&&{height:",";width:",";border-radius:16px;margin-bottom:12px;}"],(e=>"sm"===e.size?"65px":"140px"),(e=>"sm"===e.size?"65px":"140px"));let Gu=e=>{if(!y.isHex(e))return e;try{return y.hexToString(e)}catch{return e}},$u=e=>JSON.stringify(e,null,2),Ku=t=>{let{types:r,primaryType:n,...a}=t.typedData;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Tu,{data:a}),/*#__PURE__*/e.jsx(uo,{text:$u(t.typedData),itemName:"full payload to clipboard"})," "]})};let Yu=/*#__PURE__*/C.styled.div.withConfig({displayName:"InputHelp",componentId:"sc-84af275e-0"})(["line-height:20px;height:20px;font-size:13px;color:",";display:flex;justify-content:flex-start;width:100%;margin-top:16px;margin-bottom:4px;"],(e=>e.$fail?"var(--privy-color-error)":"var(--privy-color-foreground-3)")),Zu=/*#__PURE__*/C.styled.span.withConfig({displayName:"ContentWithIcon",componentId:"sc-84af275e-1"})(["display:flex;align-items:center;gap:8px;"]),Xu=/*#__PURE__*/C.styled.div.withConfig({displayName:"IconContainer",componentId:"sc-84af275e-2"})(["display:flex;flex-direction:column;justify-content:center;align-items:center;width:100%;height:82px;"]),Qu=/*#__PURE__*/C.styled.div.withConfig({displayName:"Grow",componentId:"sc-84af275e-3"})(["flex-grow:1;"]);let Ju=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-a512957a-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]);const eh=/*#__PURE__*/r.forwardRef(((t,n)=>{let[a,o]=r.useState(""),[l,d]=r.useState(""),[u,h]=r.useState(!1),{authenticated:p,user:y}=c.usePrivyContext(),{initUpdateEmail:m}=i.usePrivyInternal(),{navigate:g,setModalData:f,currentScreen:w}=c.usePrivyModal(),{enabled:v,token:C}=s.useCaptcha(),x=c.useAppConfig(),E=s.validateEmail(a)&&(x.disablePlusEmails&&a.includes("+")?(l||d("Please enter a valid email address without a '+'."),!1):(l&&d(""),!0)),S=u||!E,T=()=>{!v||C||p?(async e=>{if(!y?.email)throw Error("User is required to have an email address to update it.");h(!0);try{await m(y.email.address,a,e),g(c.ModalScreen.AWAITING_PASSWORDLESS_CODE)}catch(e){f({errorModalData:{error:e,previousScreen:w||c.ModalScreen.LANDING}})}h(!1)})(C):(f({captchaModalData:{callback:e=>{if(!y?.email)throw Error("User is required to have an email address to update it.");return m(y.email.address,a,e)},userIntentRequired:!1,onSuccessNavigateTo:c.ModalScreen.AWAITING_PASSWORDLESS_CODE,onErrorNavigateTo:c.ModalScreen.ERROR_SCREEN}}),g(c.ModalScreen.CAPTCHA_SCREEN))};/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsxs(th,{children:[l&&/*#__PURE__*/e.jsx(s.ErrorMessage,{style:{marginTop:"0.25rem",textAlign:"left"},children:l}),/*#__PURE__*/e.jsxs(rh,{$error:!!l,children:[/*#__PURE__*/e.jsx(We.default,{}),/*#__PURE__*/e.jsx("input",{ref:n,id:"email-input",type:"email",placeholder:"your@email.com",onChange:e=>o(e.target.value),onKeyUp:e=>{"Enter"===e.key&&T()},value:a,autoComplete:"email"}),t.stacked?null:/*#__PURE__*/e.jsx(s.EmbeddedButton,{isSubmitting:u,onClick:T,disabled:S,children:"Submit"})]})]}),t.stacked?/*#__PURE__*/e.jsx(s.PrimaryButton,{loadingText:null,loading:u,disabled:S,onClick:T,children:"Submit"}):null]})}));let th=s.InputContainerForm,rh=s.EmailUpdateForm;const nh=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"38px",width:"38px",...t},...r,children:/*#__PURE__*/e.jsx("path",{d:"M20 13.6V20M20 26.4H20.016M36 20C36 28.8365 28.8366 36 20 36C11.1635 36 4.00001 28.8365 4.00001 20C4.00001 11.1634 11.1635 3.99999 20 3.99999C28.8366 3.99999 36 11.1634 36 20Z",stroke:"currentColor",strokeWidth:"3.2",strokeLinecap:"round",strokeLinejoin:"round"})});let ah=/*#__PURE__*/C.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-fc448c87-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;padding-top:8px;padding-bottom:32px;"]),ih=/*#__PURE__*/C.styled.div.withConfig({displayName:"IconContainer",componentId:"sc-fc448c87-1"})(["display:flex;align-items:center;justify-content:center;height:72px;aspect-ratio:1;color:var(--privy-color-error);background-color:var(--privy-color-error-light);border-radius:50%;"]),oh=/*#__PURE__*/C.styled.div.withConfig({displayName:"GappedContainer",componentId:"sc-fc448c87-2"})(["display:flex;flex-direction:column;gap:8px;"]);const sh=/*#__PURE__*/C.createGlobalStyle([":root{--privy-border-radius-sm:6px;--privy-border-radius-md:12px;--privy-border-radius-mdlg:16px;--privy-border-radius-lg:24px;--privy-border-radius-full:9999px;--privy-color-background:",";--privy-color-background-2:",";--privy-color-background-3:",";--privy-color-foreground:",";--privy-color-foreground-2:",";--privy-color-foreground-3:",";--privy-color-foreground-4:",";--privy-color-foreground-accent:",";--privy-color-accent:",";--privy-color-accent-light:",";--privy-color-accent-lightest:",";--privy-color-accent-dark:",";--privy-color-accent-darkest:",";--privy-color-success:",";--privy-color-success-dark:",";--privy-color-success-light:",";--privy-color-error:",";--privy-color-error-light:",";--privy-color-warn:",";--privy-color-warn-light:",";--privy-height-modal-full:620px;--privy-height-modal-compact:480px;};"],(e=>e.theme.background),(e=>e.theme.background2),(e=>e.theme.background3),(e=>e.theme.foreground),(e=>e.theme.foreground2),(e=>e.theme.foreground3),(e=>e.theme.foreground4),(e=>e.theme.foregroundAccent),(e=>e.theme.accent),(e=>e.theme.accentLight),(e=>e.theme.accentLightest),(e=>e.theme.accentDark),(e=>e.theme.accentDarkest),(e=>e.theme.success),(e=>e.theme.successDark),(e=>e.theme.successLight),(e=>e.theme.error),(e=>e.theme.errorLight),(e=>e.theme.warn),(e=>e.theme.warnLight)),lh=/*#__PURE__*/C.styled.div.withConfig({displayName:"StylesWrapper",componentId:"sc-bc1e45b4-0"})([""," color:var(--privy-color-foreground-2);h3{font-size:16px;line-height:24px;font-weight:500;color:var(--privy-color-foreground-2);}h4{font-size:14px;line-height:20px;font-weight:500;color:var(--privy-color-foreground);}p{font-size:13px;line-height:20px;color:var(--privy-color-foreground-2);}button:focus,input:focus,optgroup:focus,select:focus,textarea:focus{outline:none;border-color:var(--privy-color-accent-light);box-shadow:0 0 0 1px var(--privy-color-accent-light);}.mobile-only{@media (min-width:441px){display:none;}}@keyframes fadein{0%{opacity:0;}100%{opacity:1;}}"],"\n *,\n ::before,\n ::after {\n box-sizing: border-box;\n border-width: 0;\n border-style: solid;\n }\n\n line-height: 1.15;\n -webkit-text-size-adjust: 100%;\n -moz-tab-size: 4;\n tab-size: 4;\n font-feature-settings: normal;\n\n margin: 0;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n\n abbr:where([title]) {\n text-decoration: underline dotted;\n }\n\n h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: inherit;\n font-weight: inherit;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n display: inline;\n }\n\n a {\n color: inherit;\n text-decoration: inherit;\n }\n\n b,\n strong {\n font-weight: bolder;\n }\n\n code,\n kbd,\n samp,\n pre {\n font-family: ui-monospace, SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 1em;\n }\n\n small {\n font-size: 80%;\n }\n\n sub,\n sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n }\n\n sub {\n bottom: -0.25em;\n }\n\n sup {\n top: -0.5em;\n }\n\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n\n button,\n input,\n optgroup,\n select,\n textarea {\n font-family: inherit;\n font-size: 100%;\n font-weight: inherit;\n line-height: inherit;\n color: inherit;\n margin: 0;\n padding: 0;\n }\n\n button,\n select {\n text-transform: none;\n }\n\n button,\n [type='button'],\n [type='reset'],\n [type='submit'] {\n -webkit-appearance: button;\n background-color: transparent;\n background-image: none;\n }\n\n ::-moz-focus-inner {\n border-style: none;\n padding: 0;\n }\n\n :-moz-focusring {\n outline: 1px dotted ButtonText;\n }\n\n :-moz-ui-invalid {\n box-shadow: none;\n }\n\n legend {\n padding: 0;\n }\n\n progress {\n vertical-align: baseline;\n }\n\n ::-webkit-inner-spin-button,\n ::-webkit-outer-spin-button {\n height: auto;\n }\n\n [type='search'] {\n -webkit-appearance: textfield;\n outline-offset: -2px;\n }\n\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n\n ::-webkit-file-upload-button {\n -webkit-appearance: button;\n font: inherit;\n }\n\n summary {\n display: list-item;\n }\n\n blockquote,\n dl,\n dd,\n h1,\n h2,\n h3,\n h4,\n h5,\n h6,\n hr,\n figure,\n p,\n pre {\n margin: 0;\n }\n\n fieldset {\n margin: 0;\n padding: 0;\n }\n\n legend {\n padding: 0;\n }\n\n ol,\n ul,\n menu {\n list-style: none;\n margin: 0;\n padding: 0;\n }\n\n textarea {\n resize: vertical;\n }\n\n input::placeholder,\n textarea::placeholder {\n opacity: 1;\n color: #9ca3af;\n }\n\n button,\n [role='button'] {\n cursor: pointer;\n }\n\n :disabled {\n cursor: default;\n }\n\n img,\n svg,\n video,\n canvas,\n audio,\n iframe,\n embed,\n object {\n display: block;\n }\n\n img,\n video {\n max-width: 100%;\n height: auto;\n }\n\n [hidden] {\n display: none;\n }\n"),ch=({children:t,open:r,onClick:n,...a})=>/*#__PURE__*/e.jsx(Y.Transition,{show:r,as:Se.default.Fragment,children:/*#__PURE__*/e.jsxs(Y.Dialog,{onClose:n,...a,as:uh,children:[/*#__PURE__*/e.jsx(Y.TransitionChild,{as:Se.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(dh,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/e.jsx(hh,{children:/*#__PURE__*/e.jsx(Y.TransitionChild,{as:Se.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(Y.DialogPanel,{as:ph,children:t})})})]})});let dh=/*#__PURE__*/C.styled.div.withConfig({displayName:"Backdrop",componentId:"sc-3cfde0b5-0"})(["position:fixed;inset:0;transition:backdrop-filter 100ms ease;backdrop-filter:blur(3px);-webkit-backdrop-filter:blur(3px);&.entering,&.leaving{backdrop-filter:unset;-webkit-backdrop-filter:unset;}"]),uh=/*#__PURE__*/C.styled.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),hh=/*#__PURE__*/C.styled.div.withConfig({displayName:"DialogContainer",componentId:"sc-3cfde0b5-2"})(["position:fixed;inset:0;display:flex;align-items:center;justify-content:center;width:100vw;min-height:100vh;"]);const ph=/*#__PURE__*/C.styled.div.withConfig({displayName:"Panel",componentId:"sc-3cfde0b5-3"})(["padding:0;background:transparent;border:none;width:100%;pointer-events:auto;outline:none;display:block;@media (max-width:440px){opacity:1;transform:translate3d(0,0,0);transition:transform 200ms ease-in;position:fixed;bottom:0;&.entering,&.leaving{opacity:0;transform:translate3d(0,100%,0);transition:transform 150ms ease-in 0ms,opacity 0ms ease 150ms;}}@media (min-width:441px){opacity:1;transition:opacity 100ms ease-in;&.entering,&.leaving{opacity:0;transition-delay:5ms;}margin:auto;width:360px;box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]),yh=/*#__PURE__*/C.styled.div.withConfig({displayName:"CenterItem",componentId:"sc-3cfde0b5-4"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;"]);let mh={[c.ModalScreen.LANDING]:()=>{let{app:t}=c.usePrivyModal();return t.loginMethodsAndOrder&&t.loginMethodsAndOrder.primary.length>0?/*#__PURE__*/e.jsx(Xl,{connectOnly:!1}):/*#__PURE__*/e.jsx(Vl,{connectOnly:!1})},[c.ModalScreen.CONNECT_OR_CREATE]:()=>{let{app:t}=c.usePrivyModal();return t.loginMethodsAndOrder&&t.loginMethodsAndOrder.primary.length>0?/*#__PURE__*/e.jsx(Xl,{connectOnly:!0}):/*#__PURE__*/e.jsx(Vl,{connectOnly:!0})},[c.ModalScreen.AWAITING_PASSWORDLESS_CODE]:()=>{let{app:t,navigate:a,lastScreen:o,navigateBack:l,setModalData:d,onUserCloseViaDialogOrKeybindRef:u}=c.usePrivyModal(),{closePrivyModal:h,resendEmailCode:p,resendSmsCode:y,getAuthMeta:m,loginWithCode:g,updateWallets:f,createAnalyticsEvent:w}=i.usePrivyInternal(),{authenticated:v,logout:C,user:x}=c.usePrivyContext(),[E,S]=r.useState(Jn),[T,A]=r.useState(!1),[b,_]=r.useState(null),[I,P]=r.useState(null),[j,k]=r.useState(0);u.current=()=>null;let N=m()?.email?0:1,M=c.DEFAULT_SUCCESS_SCREEN_DURATION_MS-500;r.useEffect((()=>{if(j){let e=setTimeout((()=>{k(j-1)}),1e3);return()=>clearTimeout(e)}}),[j]),r.useEffect((()=>{if(v&&T&&x){if(t?.legal.requireUsersAcceptTerms&&!x.hasAcceptedTerms){let e=setTimeout((()=>{a(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),M);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(x,t.embeddedWallets)){let e=setTimeout((()=>{d({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),w({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"AwaitingPasswordlessCodeScreen"}}),C()},callAuthOnSuccessOnClose:!0}}),a(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),M);return()=>clearTimeout(e)}{f();let e=setTimeout((()=>h({shouldCallAuthOnSuccess:!0,isSuccess:!0})),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}}}),[v,T,x]),r.useEffect((()=>{if(b&&0===I){let e=setTimeout((()=>{S(Jn),_(null);let e=document.querySelector("input[name=code-0]");e?.focus()}),1400);return()=>clearTimeout(e)}}),[b]);let R=e=>{e.preventDefault();let t=e.currentTarget.value.replace(" ","");if(""===t)return;if(isNaN(Number(t)))return _("Code should be numeric"),void P(1);_(null),P(null);let r=Number(e.currentTarget.name?.charAt(5)),n=[...t||[""]].slice(0,6-r),s=[...E.slice(0,r),...n,...E.slice(r+n.length)];S(s);let l=Math.min(Math.max(r+n.length,0),5);if(!isNaN(Number(e.currentTarget.value))){let e=document.querySelector(`input[name=code-${l}]`);e?.focus()}if(s.every((e=>e&&!isNaN(+e)))){let e=document.querySelector(`input[name=code-${l}]`);e?.blur(),g(s.join("")).then((()=>A(!0))).catch((e=>{if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.INVALID_CREDENTIALS)_("Invalid or expired verification code");else if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE)_(e.message);else{if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new i.PrivyUserLimitReachedError(e).toString()),void a(c.ModalScreen.USER_LIMIT_REACHED_SCREEN);if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.USER_DOES_NOT_EXIST)return void a(c.ModalScreen.ACCOUNT_NOT_FOUND_SCREEN);if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.LINKED_TO_ANOTHER_USER)return d({errorModalData:{error:e,previousScreen:o??c.ModalScreen.AWAITING_PASSWORDLESS_CODE}}),void a(c.ModalScreen.ERROR_SCREEN,!1);if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.DISALLOWED_PLUS_EMAIL)return d({inlineError:{error:e}}),void a(c.ModalScreen.CONNECT_OR_CREATE,!1);if(e instanceof i.PrivyApiError&&e.privyErrorCode===i.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return d({accountTransfer:{nonce:e.data?.data?.nonce,account:0===N?m()?.email:m()?.phoneNumber,displayName:e.data?.data?.account?.displayName,linkMethod:0===N?"email":"sms",embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress}}),void a(c.ModalScreen.LINK_CONFLICT_SCREEN);_("Issue verifying code")}P(0)}))}},O=0==N?/*#__PURE__*/e.jsx(We.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"}):
12
12
  /*#__PURE__*/e.jsx(Le.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"40px",width:"40px"}),W=0==N?/*#__PURE__*/e.jsxs("p",{children:["Please check ",/*#__PURE__*/e.jsx(da,{children:m()?.email})," for an email from privy.io and enter your code below."]}):/*#__PURE__*/e.jsxs("p",{children:["Please check ",/*#__PURE__*/e.jsx(da,{children:m()?.phoneNumber})," for a message from ",t?.name||"Privy"," and enter your code below."]});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:()=>l()},"header"),/*#__PURE__*/e.jsxs(aa,{children:[/*#__PURE__*/e.jsx(Zn,{title:"Enter confirmation code",description:W,icon:O}),/*#__PURE__*/e.jsxs(s.HorizontallyCenteredItem,{children:[/*#__PURE__*/e.jsxs(ia,{children:[/*#__PURE__*/e.jsx(oa,{$fail:!!b,$success:T,children:/*#__PURE__*/e.jsx("span",{children:b||(T?"Success!":"")})}),/*#__PURE__*/e.jsx("div",{children:E.map(((t,r)=>/*#__PURE__*/e.jsx("input",{name:`code-${r}`,type:"text",value:E[r],onChange:R,onKeyUp:e=>{"Backspace"===e.key&&(e=>{if(1===I&&(_(null),P(null)),S([...E.slice(0,e),"",...E.slice(e+1)]),e>0){let t=document.querySelector(`input[name=code-${e-1}]`);t?.focus()}})(r)},inputMode:"numeric",autoFocus:0===r,pattern:"[0-9]",className:`${T?"success":""} ${b?"fail":""}`,autoComplete:n.isMobile?"one-time-code":"off"},r)))})]}),/*#__PURE__*/e.jsxs(sa,{children:[/*#__PURE__*/e.jsxs("span",{children:["Didn't get ",0==N?"an email":"a message","?"]}),j?/*#__PURE__*/e.jsxs(ca,{children:[/*#__PURE__*/e.jsx(Oe.default,{color:"var(--privy-color-foreground)",strokeWidth:1.33,height:"12px",width:"12px"}),/*#__PURE__*/e.jsx("span",{children:"Code sent"})]}):/*#__PURE__*/e.jsx(la,{children:/*#__PURE__*/e.jsx("button",{onClick:async()=>{k(30),0==N?await p():await y()},children:"Resend code"})})]})]})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.AWAITING_CONNECTION]:s.ConnectionStatusScreen,[c.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION]:()=>{let t,{navigateBack:a,navigate:o,lastScreen:l,currentScreen:u,data:h,setModalData:p}=c.usePrivyModal(),{walletConnectionStatus:y,closePrivyModal:m}=i.usePrivyInternal(),[g,f]=r.useState(void 0),[w,v]=r.useState(0),C=s.useExternalWalletListing(y?.connector?.walletClientType||"unknown"),x="connected"===y?.status,E="switching_to_supported_chain"===y?.status;r.useEffect((()=>{if(x){let e;if(h?.externalConnectWallet?.onCompleteNavigateTo){let t=h.externalConnectWallet.onCompleteNavigateTo,r=y.connectedWallet?.address;e=setTimeout((()=>{h.funding&&p({...h,funding:{...h.funding,connectedWalletAddress:r}}),o(t({walletChainType:y.connector?.chainType}))}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS)}else e=setTimeout(m,c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}}),[x]);r.useEffect((()=>{y?.connectError&&(e=>{f(s.getErrorDetails(e))})(y?.connectError)}),[y]);let S=y?.connector?.connectorType||"injected",T=y?.connector?.walletClientType||"unknown",A=C?.metadata?.shortName||C?.name||y?.connector?.walletBranding.name||"Browser Extension",b=C?.image_url?.md||y?.connector?.walletBranding.icon||(t=>/*#__PURE__*/e.jsx(s.BrowserExtensionWallet,{...t})),_="Browser Extension"===A?A.toLowerCase():A;t=x?`Successfully connected with ${_}`:g?g.message:E?"Switching networks":`Waiting for ${_}`;let I="Don’t see your wallet? Check your other browser windows.";return x?I="You’re good to go!":w>=2&&g?I="Unable to connect wallet":g?I=g.detail:E?I="Switch your wallet to the requested network.":"metamask"===T&&n.isMobile?I="Click to continue to open and connect MetaMask.":"metamask"===T?I="For the best experience, connect only one wallet at a time.":"wallet_connect_v2"===S?I="Open your mobile wallet app to continue":"coinbase_wallet"===S&&(I="Open the Coinbase app on your phone to continue."),/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:u===l?void 0:a}),/*#__PURE__*/e.jsxs(_a,{children:[/*#__PURE__*/e.jsx(s.WalletLoading,{walletLogo:b,success:x,fail:!!g}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:t}),/*#__PURE__*/e.jsx("p",{children:I})]}),g==d.ConnectorErrors.ERROR_USER_EXISTS?/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:a,children:"Use a different wallet"}):!x&&g?.retryable&&w<2?/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{v(w+1),f(void 0),y?.connectRetry()},disabled:!x&&(!g?.retryable||w>=2),children:"Retry"}):!x&&g&&w>=2?/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:a,children:"Use a different wallet"}):null]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.AWAITING_FARCASTER_CONNECTION]:()=>{let{authenticated:t,logout:a,ready:o,user:l}=c.usePrivyContext(),{lastScreen:d,navigate:u,navigateBack:h,setModalData:p,app:y}=c.usePrivyModal(),{getAuthFlow:m,loginWithFarcaster:g,closePrivyModal:f,createAnalyticsEvent:w}=i.usePrivyInternal(),[v,C]=r.useState(void 0),[x,E]=r.useState(!1),[S,T]=r.useState(!1),A=r.useRef([]),b=m(),_=b?.meta.connectUri;return r.useEffect((()=>{let e=Date.now(),t=setInterval((async()=>{let r=await b.pollForReady.execute(),n=Date.now()-e;if(r){clearInterval(t),E(!0);try{await g(),T(!0)}catch(e){let t={retryable:!1,message:"Authentication failed"};if(e?.privyErrorCode===i.PrivyErrorCode.ALLOWLIST_REJECTED)return void u(c.ModalScreen.ALLOWLIST_REJECTION_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new i.PrivyUserLimitReachedError(e).toString()),void u(c.ModalScreen.USER_LIMIT_REACHED_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_DOES_NOT_EXIST)return void u(c.ModalScreen.ACCOUNT_NOT_FOUND_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.LINKED_TO_ANOTHER_USER)t.detail=e.message??"This account has already been linked to another user.";else{if(e?.privyErrorCode===i.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return p({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:"farcaster",embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,farcasterEmbeddedAddress:e.data?.data?.otherUser?.farcasterEmbeddedAddress}}),void u(c.ModalScreen.LINK_CONFLICT_SCREEN);e?.privyErrorCode===i.PrivyErrorCode.INVALID_CREDENTIALS?(t.retryable=!0,t.detail="Something went wrong. Try again."):e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&(t.detail="Too many requests. Please wait before trying again.")}C(t)}}else n>12e4&&(clearInterval(t),C({retryable:!0,message:"Authentication failed",detail:"The request timed out. Try again."}))}),2e3);return()=>{clearInterval(t),A.current.forEach((e=>clearTimeout(e)))}}),[]),r.useEffect((()=>{if(o&&t&&S&&l){if(y?.legal.requireUsersAcceptTerms&&!l.hasAcceptedTerms){let e=setTimeout((()=>{u(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}S&&(s.shouldProceedtoEmbeddedWalletCreationFlow(l,y.embeddedWallets)?A.current.push(setTimeout((()=>{p({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),w({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"FarcasterConnectStatusScreen"}}),a()},callAuthOnSuccessOnClose:!0}}),u(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS)):A.current.push(setTimeout((()=>f({shouldCallAuthOnSuccess:!0,isSuccess:!0})),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS)))}}),[S,o,t,l]),n.isMobile||x?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:d?h:void 0,onClose:f},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),n.isIOS?
13
13
  /*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(wo,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:S,fail:!!v}),/*#__PURE__*/e.jsx(mo,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(bn,{children:v?v.message:"Sign in with Farcaster"}),/*#__PURE__*/e.jsx(_n,{children:v?v.detail:"To sign in with Farcaster, please open the Warpcast app."})]}),_&&/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:e=>{e.preventDefault(),window.location.href=_},children:"Open Warpcast app"})]})}):/*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(fo,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:S,fail:!!v}),/*#__PURE__*/e.jsx(mo,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(bn,{children:v?v.message:"Signing in with Farcaster"}),/*#__PURE__*/e.jsx(_n,{children:v?v.detail:"This should only take a moment"}),/*#__PURE__*/e.jsx(s.CenteredItem,{children:_&&n.isMobile&&/*#__PURE__*/e.jsx(po,{text:"Take me to Warpcast",url:_,color:go})})]})]})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:d?h:void 0,onClose:f},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(fo,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(bn,{children:"Sign in with Farcaster"}),/*#__PURE__*/e.jsx(_n,{children:"Scan with your phone's camera to continue."}),/*#__PURE__*/e.jsx(s.CenteredItemWithPadding,{children:_?/*#__PURE__*/e.jsx(s.QrCode,{url:_,size:275,squareLogoElement:mo}):/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsxs(s.CenteredItem,{children:[/*#__PURE__*/e.jsx(_n,{children:"Or copy this link and paste it into a phone browser to open the Warpcast app."}),_&&/*#__PURE__*/e.jsx(uo,{text:_,itemName:"link",color:go})]})]})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.AWAITING_FARCASTER_SIGNER]:()=>{let{lastScreen:t,navigateBack:a,data:o,app:l}=c.usePrivyModal(),{requestFarcasterSignerStatus:d,closePrivyModal:u}=i.usePrivyInternal(),[h,p]=r.useState(void 0),[y,m]=r.useState(!1),[g,f]=r.useState(!1),w=r.useRef([]),v=o?.farcasterSigner;r.useEffect((()=>{let e=Date.now(),t=setInterval((async()=>{if(!v?.public_key)return clearInterval(t),void p({retryable:!0,message:"Connect failed",detail:"Something went wrong. Please try again."});"approved"===v.status&&(clearInterval(t),m(!1),f(!0),w.current.push(setTimeout((()=>u({shouldCallAuthOnSuccess:!1,isSuccess:!0})),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS)));let r=await d(v?.public_key),n=Date.now()-e;"approved"===r.status?(clearInterval(t),m(!1),f(!0),w.current.push(setTimeout((()=>u({shouldCallAuthOnSuccess:!1,isSuccess:!0})),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS))):n>3e5?(clearInterval(t),p({retryable:!0,message:"Connect failed",detail:"The request timed out. Try again."})):"revoked"===r.status&&(clearInterval(t),p({retryable:!0,message:"Request rejected",detail:"The request was rejected. Please try again."}))}),2e3);return()=>{clearInterval(t),w.current.forEach((e=>clearTimeout(e)))}}),[]);let C="pending_approval"===v?.status?v.signer_approval_url:void 0;return n.isMobile||y?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t?a:void 0,onClose:u},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),n.isIOS?
14
- /*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(xo,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:g,fail:!!h}),/*#__PURE__*/e.jsx(mo,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(bn,{children:h?h.message:"Add a signer to Farcaster"}),/*#__PURE__*/e.jsx(_n,{children:h?h.detail:"This will allow "+l.name+" to add casts, likes, follows, and more on your behalf."})]}),C&&/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:e=>{e.preventDefault(),window.location.href=C},children:"Open Warpcast app"})]})}):/*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(Co,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:g,fail:!!h}),/*#__PURE__*/e.jsx(mo,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(bn,{children:h?h.message:"Requesting signer from Farcaster"}),/*#__PURE__*/e.jsx(_n,{children:h?h.detail:"This should only take a moment"}),/*#__PURE__*/e.jsx(s.CenteredItem,{children:C&&n.isMobile&&/*#__PURE__*/e.jsx(po,{text:"Take me to Warpcast",url:C,color:vo})})]})]})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t?a:void 0,onClose:u},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Co,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(bn,{children:"Add a signer to Farcaster"}),/*#__PURE__*/e.jsxs(_n,{children:["This will allow ",l.name," to add casts, likes, follows, and more on your behalf."]}),/*#__PURE__*/e.jsx(s.CenteredItemWithPadding,{children:"pending_approval"===v?.status?/*#__PURE__*/e.jsx(s.QrCode,{url:v.signer_approval_url,size:275,squareLogoElement:mo}):/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsxs(s.CenteredItem,{children:[/*#__PURE__*/e.jsx(_n,{children:"Or copy this link and paste it into a phone browser to open the Warpcast app."}),"pending_approval"===v?.status&&/*#__PURE__*/e.jsx(uo,{text:v.signer_approval_url,itemName:"link",color:vo})]})]})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.SELECT_PASSKEY_SIGNUP_OR_LOGIN]:()=>{let{enabled:t,token:r}=s.useCaptcha(),{lastScreen:n,currentScreen:a,navigateBack:o,navigate:l,setModalData:d}=c.usePrivyModal(),{initSignupWithPasskey:u,initLoginWithPasskey:h}=i.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:n&&a!==n?o:void 0}),/*#__PURE__*/e.jsx(An,{children:/*#__PURE__*/e.jsxs(md,{children:[/*#__PURE__*/e.jsx(rs,{}),/*#__PURE__*/e.jsx(ns,{})]})}),/*#__PURE__*/e.jsx(bn,{children:"Log in or create a new account?"}),/*#__PURE__*/e.jsx(_n,{children:"Create a new account with a passkey or use a passkey to log in to an existing account."}),/*#__PURE__*/e.jsxs(Nn,{children:[/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:async()=>{t&&!r?(d({passkeyAuthModalData:{passkeySignupFlow:!0},captchaModalData:{callback:e=>u({captchaToken:e,withPrivyUi:!0}),userIntentRequired:!1,onSuccessNavigateTo:c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE,onErrorNavigateTo:c.ModalScreen.ERROR_SCREEN}}),l(c.ModalScreen.CAPTCHA_SCREEN)):(await u({withPrivyUi:!0}),d({passkeyAuthModalData:{passkeySignupFlow:!0}}),l(c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE))},children:"Create new account"}),/*#__PURE__*/e.jsx(Dn,{onClick:async()=>{t&&!r?(d({passkeyAuthModalData:{passkeySignupFlow:!1},captchaModalData:{callback:e=>h({captchaToken:e,withPrivyUi:!0}),userIntentRequired:!1,onSuccessNavigateTo:c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE,onErrorNavigateTo:c.ModalScreen.ERROR_SCREEN}}),l(c.ModalScreen.CAPTCHA_SCREEN)):(await h({withPrivyUi:!0}),d({passkeyAuthModalData:{passkeySignupFlow:!1}}),l(c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE))},children:"Log in with a passkey"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE]:()=>{let{app:t,lastScreen:n,currentScreen:a,navigateBack:o,data:l,setModalData:d,navigate:u}=c.usePrivyModal(),{loginWithPasskey:h,signupWithPasskey:p,closePrivyModal:y,createAnalyticsEvent:m}=i.usePrivyInternal(),{user:g,logout:f}=c.usePrivyContext(),{passkeySignupFlow:w}=l?.passkeyAuthModalData??{},v=c.DEFAULT_SUCCESS_SCREEN_DURATION_MS-500,[C,x]=r.useState("loading"),[E,S]=r.useState(null),T=r.useRef([]),A=e=>{T.current=[e,...T.current]};r.useEffect((()=>()=>{T.current.forEach((e=>clearTimeout(e))),T.current=[]}),[]);let b=async()=>{x("loading");try{w?await p():await h(),x("success")}catch(e){S(e),x("error")}};return r.useEffect((()=>{if("success"===C&&g){if(t?.legal.requireUsersAcceptTerms&&!g.hasAcceptedTerms)return void A(setTimeout((()=>{u(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),v));if(!s.shouldProceedtoEmbeddedWalletCreationFlow(g,t?.embeddedWallets))return void A(setTimeout((()=>{y({shouldCallAuthOnSuccess:!0,isSuccess:!0})}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS));A(setTimeout((()=>{d({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),m({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"PasskeyStatusScreen"}}),f()},callAuthOnSuccessOnClose:!0}}),u(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),v))}}),[g,C]),r.useEffect((()=>{b()}),[]),/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:n&&a!==n?o:void 0}),/*#__PURE__*/e.jsxs(gd,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:"success"===C,fail:"error"===C}),/*#__PURE__*/e.jsx(ns,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:(()=>{switch(C){case"loading":return"Waiting for passkey";case"success":return"Success";case"error":return"Something went wrong"}})()}),/*#__PURE__*/e.jsx("p",{style:{whiteSpace:"pre-wrap"},children:(()=>{switch(C){case"loading":return w?"Please follow prompts to register your passkey.":"Please follow prompts to verify your passkey.\nYou will have to sign up with another method first to register a passkey for your account.";case"success":return"You've successfully logged in with your passkey.";case"error":if(E instanceof i.PrivyError){if(E.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE)return"Cannot link more passkeys to account.";if(E.privyErrorCode===i.PrivyErrorCode.PASSKEY_NOT_ALLOWED)return"Passkey request timed out or rejected by user.\nYou will have to sign up with another method first to register a passkey for your account."}return"An unknown error occurred.\nYou will have to sign up with another method first to register a passkey for your account."}})()})]}),(()=>{switch(C){case"loading":case"success":/*#__PURE__*/return e.jsx(s.PrimaryButton,{onClick:()=>{},disabled:!0,children:"Continue"});case"error":/*#__PURE__*/return e.jsx(s.PrimaryButton,{onClick:b,disabled:!1,children:"Retry"})}})()]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.WALLET_INTERSTITIAL_SCREEN]:()=>{let{ready:t}=c.usePrivyContext(),{data:n}=c.usePrivyModal(),[a,i]=r.useState(!1);if(!n?.installWalletModalData)throw Error("Wallet data is missing");let{walletConfig:o,connectOnly:l,chainType:d}=n.installWalletModalData,u=o.getMobileRedirect({useUniversalLink:!a,isSolana:"solana"===d,connectOnly:l}),h=o.name.replace(/ wallet/gi,""),p={title:`Redirecting to ${h} Mobile Wallet`,description:`We'll take you to the ${h} Mobile Wallet app to continue your login experience.`,footnote:""};return t&&(p.description=`For the best experience, we'll automatically log you into the ${h} Mobile Wallet in-app browser.`,p.footnote="Once you're done, you can always return here and refresh to view your updated account."),a&&(p.title="Still here?",p.description=`You may need to install the ${o.name} mobile app.`,p.footnote=`Once you're done, you can return here or connect via ${o.name}'s in-app browser.`),/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Yn,{title:p.title,description:p.description}),/*#__PURE__*/e.jsxs(s.BottomPusherContainer,{children:[/*#__PURE__*/e.jsx(s.PrimaryButtonLink,{href:u,onClick:()=>setTimeout((()=>i(!0)),1e3),loading:t&&!u,children:a?"Go to App Store":"Continue"}),p.footnote?/*#__PURE__*/e.jsx("p",{children:p.footnote}):null]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.LOGIN_FAILED_SCREEN]:()=>{let{closePrivyModal:t}=i.usePrivyInternal(),{navigate:r}=c.usePrivyModal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(ec,{style:{width:"160px",height:"160px",margin:"0 auto 20px"}}),/*#__PURE__*/e.jsx(Yn,{title:"Could not connect with wallet",description:"Please check that Phantom multichain is enabled and try again.",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center"}}),/*#__PURE__*/e.jsxs(s.BottomPusherContainer,{children:[/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>r(c.ModalScreen.LANDING),children:"Try again"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:()=>t(),children:"Cancel"})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.AWAITING_OAUTH_SCREEN]:()=>{let{authenticated:t,logout:n,ready:a,user:o}=c.usePrivyContext(),{app:l,setModalData:d,navigate:u,resetNavigation:h}=c.usePrivyModal(),{getAuthMeta:p,initLoginWithOAuth:y,loginWithOAuth:m,updateWallets:g,setReadyToTrue:f,closePrivyModal:w,createAnalyticsEvent:v}=i.usePrivyInternal(),[C,x]=r.useState(!1),[E,S]=r.useState(void 0),T=p()?.provider||"google",{name:A,component:b}=qt(T);r.useEffect((()=>{m(T).then((()=>{x(!0),f(!0)})).catch((e=>{if(f(!1),e?.privyErrorCode===i.PrivyErrorCode.ALLOWLIST_REJECTED)return S(void 0),h(),void u(c.ModalScreen.ALLOWLIST_REJECTION_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new i.PrivyUserLimitReachedError(e).toString()),S(void 0),h(),void u(c.ModalScreen.USER_LIMIT_REACHED_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_DOES_NOT_EXIST)return S(void 0),h(),void u(c.ModalScreen.ACCOUNT_NOT_FOUND_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return S(void 0),h(),d({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:p()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void u(c.ModalScreen.LINK_CONFLICT_SCREEN);let{retryable:t,detail:r}=function(e,t){let r={detail:"",retryable:!1},n=Nt(t);if(e?.privyErrorCode===i.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(r.detail="This account has already been linked to another user."),e?.privyErrorCode===i.PrivyErrorCode.INVALID_CREDENTIALS&&(r.retryable=!0,r.detail="Something went wrong. Try again."),e.privyErrorCode===i.PrivyErrorCode.OAUTH_USER_DENIED&&(r.detail=`Retry and check ${n} to finish connecting your account.`,r.retryable=!0),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&(r.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=qt(t).name;r.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===i.PrivyErrorCode.OAUTH_ACCOUNT_SUSPENDED){let e=qt(t).name;r.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(r.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===i.PrivyErrorCode.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(r.detail="Something went wrong. Please try again."),r}(e,T);S({retryable:t,detail:r,message:"Authentication failed"})})).finally((()=>{Gt()}))}),[A,T]),r.useEffect((()=>{if(a&&t&&C&&o){if(l?.legal.requireUsersAcceptTerms&&!o.hasAcceptedTerms){let e=setTimeout((()=>{u(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(o,l.embeddedWallets)){let e=setTimeout((()=>{d({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),v({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:T,screen:"OAuthStatusScreen"}}),n()},callAuthOnSuccessOnClose:!0}}),u(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}{let e=setTimeout((()=>w({shouldCallAuthOnSuccess:!0,isSuccess:!0})),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return g(),()=>clearTimeout(e)}}}),[a,t,C,o]);let _=C?`Successfully connected with ${A}`:E?E.message:`Verifying connection to ${A}`,I="";return I=C?"You’re good to go!":E?E.detail:"Just a few moments more",/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(yd,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:C,fail:!!E}),/*#__PURE__*/e.jsx(b,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:_}),/*#__PURE__*/e.jsx("p",{children:I})]}),E&&E?.retryable?/*#__PURE__*/e.jsx(s.SoftCtaButton,{onClick:()=>{Gt(),y(T),S(void 0)},disabled:!C&&!E?.retryable,children:"Retry"}):null]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.CROSS_APP_AUTH_SCREEN]:()=>{let t=c.useAppConfig(),{data:n,navigate:a,setModalData:o,onUserCloseViaDialogOrKeybindRef:l}=c.usePrivyModal(),{crossAppAuthFlow:d,updateWallets:u,closePrivyModal:h,createAnalyticsEvent:p}=i.usePrivyInternal(),{logout:y}=s.useLogout(),[m,g]=r.useState({}),f=n?.crossAppAuth,w={id:f.appId,name:f.name,logoUrl:f.logoUrl},v=new i.PrivyClientError(`There was an issue connecting your ${w.name} account. Please try again.`),C=new s.RunEffectOnce((async e=>{if(f.popup)try{let t=await d({appId:e,popup:f.popup,action:f.action});g({data:t})}catch(e){e instanceof i.PrivyClientError?g({error:e}):(e instanceof i.PrivyApiError&&f.popup&&f.popup.close(),g({error:v}))}else g({error:v})})),x=()=>{m.data&&(u(),f.onSuccess(m.data),h({shouldCallAuthOnSuccess:!0,isSuccess:!0})),f.onError(m.error??new i.PrivyClientError("User canceled flow")),h({shouldCallAuthOnSuccess:!1,isSuccess:!1})};l.current=x,r.useEffect((()=>{w.id.length&&C.execute(w.id)}),[w.id]),r.useEffect((()=>{if(!m.data)return;let e=m.data;if(t.legal.requireUsersAcceptTerms&&!e.hasAcceptedTerms){let e=setTimeout((()=>{a(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(e,t.embeddedWallets)){let e=setTimeout((()=>{o({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),p({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${w.id}`,screen:"CrossAppAuthScreen"}}),y()},callAuthOnSuccessOnClose:!0}}),a(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}let r=setTimeout(x,c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(r)}),[m.data]);let{title:E,subtitle:S}=r.useMemo((()=>m.data?{title:`Successfully connected with ${w.name}`,subtitle:"You're good to go!"}:m.error?{title:"Authentication failed",subtitle:m.error.message}:{title:`Connecting to ${w.name}`,subtitle:`Please check the pop-up from ${w.name} to continue`}),[m,w.name]);/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:x}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(Pa,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:!!m.data,fail:!!m.error}),/*#__PURE__*/e.jsx(Ia,{name:w.name,logoUrl:w.logoUrl})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:E}),/*#__PURE__*/e.jsx("p",{children:S})]})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.ALLOWLIST_REJECTION_SCREEN]:()=>{let{navigate:t,app:r}=c.usePrivyModal(),n=r?.allowlistConfig.errorTitle||"You don't have access to this app",a=r?.allowlistConfig.errorDetail||"Have you been invited?",i=r?.allowlistConfig.errorCtaText||"Try another account";/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsxs(Gn,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(dn,{}),/*#__PURE__*/e.jsx(Vn,{style:{width:"38px",height:"38px",strokeWidth:"1",stroke:"var(--privy-color-accent)",fill:"var(--privy-color-accent)"}})]})}),/*#__PURE__*/e.jsxs($n,{children:["string"==typeof n?/*#__PURE__*/e.jsx("h3",{children:n}):/*#__PURE__*/e.jsx(e.Fragment,{children:n}),"string"==typeof a?/*#__PURE__*/e.jsx("p",{children:a}):/*#__PURE__*/e.jsx(e.Fragment,{children:a})]}),r?.allowlistConfig.errorCtaLink?
14
+ /*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(xo,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:g,fail:!!h}),/*#__PURE__*/e.jsx(mo,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(bn,{children:h?h.message:"Add a signer to Farcaster"}),/*#__PURE__*/e.jsx(_n,{children:h?h.detail:"This will allow "+l.name+" to add casts, likes, follows, and more on your behalf."})]}),C&&/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:e=>{e.preventDefault(),window.location.href=C},children:"Open Warpcast app"})]})}):/*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(Co,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:g,fail:!!h}),/*#__PURE__*/e.jsx(mo,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(bn,{children:h?h.message:"Requesting signer from Farcaster"}),/*#__PURE__*/e.jsx(_n,{children:h?h.detail:"This should only take a moment"}),/*#__PURE__*/e.jsx(s.CenteredItem,{children:C&&n.isMobile&&/*#__PURE__*/e.jsx(po,{text:"Take me to Warpcast",url:C,color:vo})})]})]})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t?a:void 0,onClose:u},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Co,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(bn,{children:"Add a signer to Farcaster"}),/*#__PURE__*/e.jsxs(_n,{children:["This will allow ",l.name," to add casts, likes, follows, and more on your behalf."]}),/*#__PURE__*/e.jsx(s.CenteredItemWithPadding,{children:"pending_approval"===v?.status?/*#__PURE__*/e.jsx(s.QrCode,{url:v.signer_approval_url,size:275,squareLogoElement:mo}):/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsxs(s.CenteredItem,{children:[/*#__PURE__*/e.jsx(_n,{children:"Or copy this link and paste it into a phone browser to open the Warpcast app."}),"pending_approval"===v?.status&&/*#__PURE__*/e.jsx(uo,{text:v.signer_approval_url,itemName:"link",color:vo})]})]})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.SELECT_PASSKEY_SIGNUP_OR_LOGIN]:()=>{let{enabled:t,token:r}=s.useCaptcha(),{lastScreen:n,currentScreen:a,navigateBack:o,navigate:l,setModalData:d}=c.usePrivyModal(),{initSignupWithPasskey:u,initLoginWithPasskey:h}=i.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:n&&a!==n?o:void 0}),/*#__PURE__*/e.jsx(An,{children:/*#__PURE__*/e.jsxs(md,{children:[/*#__PURE__*/e.jsx(rs,{}),/*#__PURE__*/e.jsx(ns,{})]})}),/*#__PURE__*/e.jsx(bn,{children:"Log in or create a new account?"}),/*#__PURE__*/e.jsx(_n,{children:"Create a new account with a passkey or use a passkey to log in to an existing account."}),/*#__PURE__*/e.jsxs(Nn,{children:[/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:async()=>{t&&!r?(d({passkeyAuthModalData:{passkeySignupFlow:!0},captchaModalData:{callback:e=>u({captchaToken:e,withPrivyUi:!0}),userIntentRequired:!1,onSuccessNavigateTo:c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE,onErrorNavigateTo:c.ModalScreen.ERROR_SCREEN}}),l(c.ModalScreen.CAPTCHA_SCREEN)):(await u({withPrivyUi:!0}),d({passkeyAuthModalData:{passkeySignupFlow:!0}}),l(c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE))},children:"Create new account"}),/*#__PURE__*/e.jsx(Dn,{onClick:async()=>{t&&!r?(d({passkeyAuthModalData:{passkeySignupFlow:!1},captchaModalData:{callback:e=>h({captchaToken:e,withPrivyUi:!0}),userIntentRequired:!1,onSuccessNavigateTo:c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE,onErrorNavigateTo:c.ModalScreen.ERROR_SCREEN}}),l(c.ModalScreen.CAPTCHA_SCREEN)):(await h({withPrivyUi:!0}),d({passkeyAuthModalData:{passkeySignupFlow:!1}}),l(c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE))},children:"Log in with a passkey"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.AWAITING_PASSKEY_SYSTEM_DIALOGUE]:()=>{let{app:t,lastScreen:n,currentScreen:a,navigateBack:o,data:l,setModalData:d,navigate:u}=c.usePrivyModal(),{loginWithPasskey:h,signupWithPasskey:p,closePrivyModal:y,createAnalyticsEvent:m}=i.usePrivyInternal(),{user:g,logout:f}=c.usePrivyContext(),{passkeySignupFlow:w}=l?.passkeyAuthModalData??{},v=c.DEFAULT_SUCCESS_SCREEN_DURATION_MS-500,[C,x]=r.useState("loading"),[E,S]=r.useState(null),T=r.useRef([]),A=e=>{T.current=[e,...T.current]};r.useEffect((()=>()=>{T.current.forEach((e=>clearTimeout(e))),T.current=[]}),[]);let b=async()=>{x("loading");try{w?await p():await h(),x("success")}catch(e){S(e),x("error")}};return r.useEffect((()=>{if("success"===C&&g){if(t?.legal.requireUsersAcceptTerms&&!g.hasAcceptedTerms)return void A(setTimeout((()=>{u(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),v));if(!s.shouldProceedtoEmbeddedWalletCreationFlow(g,t?.embeddedWallets))return void A(setTimeout((()=>{y({shouldCallAuthOnSuccess:!0,isSuccess:!0})}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS));A(setTimeout((()=>{d({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),m({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"PasskeyStatusScreen"}}),f()},callAuthOnSuccessOnClose:!0}}),u(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),v))}}),[g,C]),r.useEffect((()=>{b()}),[]),/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:n&&a!==n?o:void 0}),/*#__PURE__*/e.jsxs(gd,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:"success"===C,fail:"error"===C}),/*#__PURE__*/e.jsx(ns,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:(()=>{switch(C){case"loading":return"Waiting for passkey";case"success":return"Success";case"error":return"Something went wrong"}})()}),/*#__PURE__*/e.jsx("p",{style:{whiteSpace:"pre-wrap"},children:(()=>{switch(C){case"loading":return w?"Please follow prompts to register your passkey.":"Please follow prompts to verify your passkey.\nYou will have to sign up with another method first to register a passkey for your account.";case"success":return"You've successfully logged in with your passkey.";case"error":if(E instanceof i.PrivyError){if(E.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE)return"Cannot link more passkeys to account.";if(E.privyErrorCode===i.PrivyErrorCode.PASSKEY_NOT_ALLOWED)return"Passkey request timed out or rejected by user.\nYou will have to sign up with another method first to register a passkey for your account."}return"An unknown error occurred.\nYou will have to sign up with another method first to register a passkey for your account."}})()})]}),(()=>{switch(C){case"loading":case"success":/*#__PURE__*/return e.jsx(s.PrimaryButton,{onClick:()=>{},disabled:!0,children:"Continue"});case"error":/*#__PURE__*/return e.jsx(s.PrimaryButton,{onClick:b,disabled:!1,children:"Retry"})}})()]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.WALLET_INTERSTITIAL_SCREEN]:()=>{let{ready:t}=c.usePrivyContext(),{data:n}=c.usePrivyModal(),[a,i]=r.useState(!1);if(!n?.installWalletModalData)throw Error("Wallet data is missing");let{walletConfig:o,connectOnly:l,chainType:d}=n.installWalletModalData,u=o.getMobileRedirect({useUniversalLink:!a,isSolana:"solana"===d,connectOnly:l}),h=o.name.replace(/ wallet/gi,""),p={title:`Redirecting to ${h} Mobile Wallet`,description:`We'll take you to the ${h} Mobile Wallet app to continue your login experience.`,footnote:""};return t&&(p.description=`For the best experience, we'll automatically log you into the ${h} Mobile Wallet in-app browser.`,p.footnote="You can always return here to login via other methods."),a&&(p.title="Still here?",p.description=`You may need to install the ${o.name} mobile app.`,p.footnote=`Once you're done, you can connect with ${o.name} wallet to complete the login.`),/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Yn,{title:p.title,description:p.description}),/*#__PURE__*/e.jsxs(s.BottomPusherContainer,{children:[/*#__PURE__*/e.jsx(s.PrimaryButtonLink,{href:u,onClick:()=>setTimeout((()=>i(!0)),1e3),loading:t&&!u,children:a?"Go to App Store":"Continue"}),p.footnote?/*#__PURE__*/e.jsx("p",{children:p.footnote}):null]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.LOGIN_FAILED_SCREEN]:()=>{let{closePrivyModal:t}=i.usePrivyInternal(),{navigate:r}=c.usePrivyModal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(ec,{style:{width:"160px",height:"160px",margin:"0 auto 20px"}}),/*#__PURE__*/e.jsx(Yn,{title:"Could not connect with wallet",description:"Please check that Phantom multichain is enabled and try again.",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center"}}),/*#__PURE__*/e.jsxs(s.BottomPusherContainer,{children:[/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>r(c.ModalScreen.LANDING),children:"Try again"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:()=>t(),children:"Cancel"})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.AWAITING_OAUTH_SCREEN]:()=>{let{authenticated:t,logout:n,ready:a,user:o}=c.usePrivyContext(),{app:l,setModalData:d,navigate:u,resetNavigation:h}=c.usePrivyModal(),{getAuthMeta:p,initLoginWithOAuth:y,loginWithOAuth:m,updateWallets:g,setReadyToTrue:f,closePrivyModal:w,createAnalyticsEvent:v}=i.usePrivyInternal(),[C,x]=r.useState(!1),[E,S]=r.useState(void 0),T=p()?.provider||"google",{name:A,component:b}=qt(T);r.useEffect((()=>{m(T).then((()=>{x(!0),f(!0)})).catch((e=>{if(f(!1),e?.privyErrorCode===i.PrivyErrorCode.ALLOWLIST_REJECTED)return S(void 0),h(),void u(c.ModalScreen.ALLOWLIST_REJECTION_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new i.PrivyUserLimitReachedError(e).toString()),S(void 0),h(),void u(c.ModalScreen.USER_LIMIT_REACHED_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_DOES_NOT_EXIST)return S(void 0),h(),void u(c.ModalScreen.ACCOUNT_NOT_FOUND_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return S(void 0),h(),d({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:p()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void u(c.ModalScreen.LINK_CONFLICT_SCREEN);let{retryable:t,detail:r}=function(e,t){let r={detail:"",retryable:!1},n=Nt(t);if(e?.privyErrorCode===i.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(r.detail="This account has already been linked to another user."),e?.privyErrorCode===i.PrivyErrorCode.INVALID_CREDENTIALS&&(r.retryable=!0,r.detail="Something went wrong. Try again."),e.privyErrorCode===i.PrivyErrorCode.OAUTH_USER_DENIED&&(r.detail=`Retry and check ${n} to finish connecting your account.`,r.retryable=!0),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&(r.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===i.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=qt(t).name;r.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===i.PrivyErrorCode.OAUTH_ACCOUNT_SUSPENDED){let e=qt(t).name;r.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(r.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===i.PrivyErrorCode.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(r.detail="Something went wrong. Please try again."),r}(e,T);S({retryable:t,detail:r,message:"Authentication failed"})})).finally((()=>{Gt()}))}),[A,T]),r.useEffect((()=>{if(a&&t&&C&&o){if(l?.legal.requireUsersAcceptTerms&&!o.hasAcceptedTerms){let e=setTimeout((()=>{u(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(o,l.embeddedWallets)){let e=setTimeout((()=>{d({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),v({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:T,screen:"OAuthStatusScreen"}}),n()},callAuthOnSuccessOnClose:!0}}),u(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}{let e=setTimeout((()=>w({shouldCallAuthOnSuccess:!0,isSuccess:!0})),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return g(),()=>clearTimeout(e)}}}),[a,t,C,o]);let _=C?`Successfully connected with ${A}`:E?E.message:`Verifying connection to ${A}`,I="";return I=C?"You’re good to go!":E?E.detail:"Just a few moments more",/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(yd,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:C,fail:!!E}),/*#__PURE__*/e.jsx(b,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:_}),/*#__PURE__*/e.jsx("p",{children:I})]}),E&&E?.retryable?/*#__PURE__*/e.jsx(s.SoftCtaButton,{onClick:()=>{Gt(),y(T),S(void 0)},disabled:!C&&!E?.retryable,children:"Retry"}):null]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.CROSS_APP_AUTH_SCREEN]:()=>{let t=c.useAppConfig(),{data:n,navigate:a,setModalData:o,onUserCloseViaDialogOrKeybindRef:l}=c.usePrivyModal(),{crossAppAuthFlow:d,updateWallets:u,closePrivyModal:h,createAnalyticsEvent:p}=i.usePrivyInternal(),{logout:y}=s.useLogout(),[m,g]=r.useState({}),f=n?.crossAppAuth,w={id:f.appId,name:f.name,logoUrl:f.logoUrl},v=new i.PrivyClientError(`There was an issue connecting your ${w.name} account. Please try again.`),C=new s.RunEffectOnce((async e=>{if(f.popup)try{let t=await d({appId:e,popup:f.popup,action:f.action});g({data:t})}catch(e){e instanceof i.PrivyClientError?g({error:e}):(e instanceof i.PrivyApiError&&f.popup&&f.popup.close(),g({error:v}))}else g({error:v})})),x=()=>{m.data&&(u(),f.onSuccess(m.data),h({shouldCallAuthOnSuccess:!0,isSuccess:!0})),f.onError(m.error??new i.PrivyClientError("User canceled flow")),h({shouldCallAuthOnSuccess:!1,isSuccess:!1})};l.current=x,r.useEffect((()=>{w.id.length&&C.execute(w.id)}),[w.id]),r.useEffect((()=>{if(!m.data)return;let e=m.data;if(t.legal.requireUsersAcceptTerms&&!e.hasAcceptedTerms){let e=setTimeout((()=>{a(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(e,t.embeddedWallets)){let e=setTimeout((()=>{o({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),p({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${w.id}`,screen:"CrossAppAuthScreen"}}),y()},callAuthOnSuccessOnClose:!0}}),a(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}let r=setTimeout(x,c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(r)}),[m.data]);let{title:E,subtitle:S}=r.useMemo((()=>m.data?{title:`Successfully connected with ${w.name}`,subtitle:"You're good to go!"}:m.error?{title:"Authentication failed",subtitle:m.error.message}:{title:`Connecting to ${w.name}`,subtitle:`Please check the pop-up from ${w.name} to continue`}),[m,w.name]);/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:x}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(Pa,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:!!m.data,fail:!!m.error}),/*#__PURE__*/e.jsx(Ia,{name:w.name,logoUrl:w.logoUrl})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:E}),/*#__PURE__*/e.jsx("p",{children:S})]})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.ALLOWLIST_REJECTION_SCREEN]:()=>{let{navigate:t,app:r}=c.usePrivyModal(),n=r?.allowlistConfig.errorTitle||"You don't have access to this app",a=r?.allowlistConfig.errorDetail||"Have you been invited?",i=r?.allowlistConfig.errorCtaText||"Try another account";/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsxs(Gn,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(dn,{}),/*#__PURE__*/e.jsx(Vn,{style:{width:"38px",height:"38px",strokeWidth:"1",stroke:"var(--privy-color-accent)",fill:"var(--privy-color-accent)"}})]})}),/*#__PURE__*/e.jsxs($n,{children:["string"==typeof n?/*#__PURE__*/e.jsx("h3",{children:n}):/*#__PURE__*/e.jsx(e.Fragment,{children:n}),"string"==typeof a?/*#__PURE__*/e.jsx("p",{children:a}):/*#__PURE__*/e.jsx(e.Fragment,{children:a})]}),r?.allowlistConfig.errorCtaLink?
15
15
  /*#__PURE__*/e.jsx(s.PrimaryButton,{as:"a",href:r.allowlistConfig.errorCtaLink,children:i}):/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{t(c.ModalScreen.LANDING)},children:i})]})]})},[c.ModalScreen.ACCOUNT_NOT_FOUND_SCREEN]:()=>{let{navigate:t,app:r,setModalData:n,data:a}=c.usePrivyModal(),{getAuthMeta:o,client:l}=i.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsxs(ln,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(Kr,{color:"var(--privy-color-warn-light)"}),/*#__PURE__*/e.jsx(Ie.default,{height:38,width:38,strokeWidth:2,stroke:"var(--privy-color-warn)"})]})}),/*#__PURE__*/e.jsxs(cn,{children:[/*#__PURE__*/e.jsx("h3",{children:"Account not found"}),/*#__PURE__*/e.jsxs("p",{children:["Please try logging in again or go to ",r.name," to create an account."]})]}),/*#__PURE__*/e.jsx(Zr,{}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{let e=o();n({...a,login:{...a?.login,...e?.disableSignup?{disableSignup:!0}:{}}}),l?.authFlow&&(l.authFlow=void 0),t(c.ModalScreen.LANDING)},children:"Try logging in again"})]})]})},[c.ModalScreen.USER_LIMIT_REACHED_SCREEN]:()=>{let{navigate:t}=c.usePrivyModal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsxs(ah,{children:[/*#__PURE__*/e.jsx(ih,{children:/*#__PURE__*/e.jsx(nh,{})}),/*#__PURE__*/e.jsxs(oh,{children:[/*#__PURE__*/e.jsx("h3",{children:"Unable to sign in"}),/*#__PURE__*/e.jsx("p",{children:"This application has reached its user limit and cannot sign in new users."})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{t(c.ModalScreen.LANDING)},children:"Go back"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.INSTALL_WALLET_SCREEN]:()=>{let{navigateBack:t,data:r}=c.usePrivyModal();if(!r?.installWalletModalData)throw Error("Wallet data is missing");let{walletConfig:n}=r.installWalletModalData;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(gl,{...n}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsxs(s.ModalFooter,{children:[/*#__PURE__*/e.jsx("span",{children:"Still not sure? "}),/*#__PURE__*/e.jsx("a",{target:"_blank",href:"https://solana.com/docs/intro/wallets",children:"Learn more"})]})]})},[c.ModalScreen.LINK_EMAIL_SCREEN]:()=>{let{app:t}=c.usePrivyModal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Zn,{title:"Connect your email",description:`Add your email to your ${t?.name} account`,icon:/*#__PURE__*/e.jsx(We.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(Sl,{stacked:!0})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.LINK_PHONE_SCREEN]:()=>{let{app:t,currentScreen:r,data:n,navigate:a,setModalData:o}=c.usePrivyModal(),{initLoginWithSms:l}=i.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Zn,{title:"Connect your phone",description:`Add your number to your ${t?.name} account`,icon:/*#__PURE__*/e.jsx(Le.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"40px",width:"40px"})}),/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(Rl,{stacked:!0,onSubmit:async function({qualifiedPhoneNumber:e}){try{await l({phoneNumber:e,withPrivyUi:!0}),a(c.ModalScreen.AWAITING_PASSWORDLESS_CODE)}catch(e){o({errorModalData:{error:e,previousScreen:n?.errorModalData?.previousScreen||r||c.ModalScreen.LINK_PHONE_SCREEN}}),a(c.ModalScreen.ERROR_SCREEN)}},hideRecent:!0})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.LINK_WALLET_SCREEN]:()=>{let{app:t,data:r}=c.usePrivyModal(),n=r?.externalConnectWallet?.suggestedAddress,a=n?/*#__PURE__*/e.jsxs("span",{children:["Link the wallet with address ",/*#__PURE__*/e.jsx(s.Address,{showCopyIcon:!1,address:n})," ",t?.name?`to ${t.name}.`:"."]}):`Link a wallet to your ${t?.name} account`,{connectors:o}=i.usePrivyInternal(),l=ba({walletList:r?.externalConnectWallet?.walletList??t.appearance.walletList,walletChainType:r?.externalConnectWallet?.walletChainType??t.appearance.walletChainType,connectors:o,connectOnly:!1,ignore:t.appearance.walletList,walletConnectEnabled:t.externalWallets.walletConnect.enabled});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),l.length>0&&/*#__PURE__*/e.jsx(Yn,{title:"Link your wallet",description:a}),/*#__PURE__*/e.jsx(Qr,{children:/*#__PURE__*/e.jsx(Aa,{wallets:l})}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.LINK_PASSKEY_SCREEN]:()=>{let{user:t,unlinkPasskey:n}=c.usePrivyContext(),{linkWithPasskey:a,closePrivyModal:o}=i.usePrivyInternal(),l=t?.linkedAccounts.filter((e=>"passkey"===e.type)),[d,u]=r.useState(!1),[h,p]=r.useState(""),[y,m]=r.useState(!1),[g,f]=r.useState(!1);r.useEffect((()=>{0===l.length&&f(!1)}),[l.length]);let w=async e=>(u(!0),await n(e).then((()=>m(!0))).catch((e=>{e instanceof i.PrivyError&&e.privyErrorCode===i.PrivyErrorCode.MISSING_MFA_CREDENTIALS?p("Cannot unlink a passkey enrolled in MFA"):p("Unknown error occurred.")})).finally((()=>{u(!1)})));return y?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:()=>o()},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(De.default,{})}),/*#__PURE__*/e.jsx(us,{style:{marginBottom:"1.5rem"},children:"Passkeys updated"}),/*#__PURE__*/e.jsx(hs,{children:" "}),/*#__PURE__*/e.jsx(Nn,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>o(),children:"Done"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):g?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:()=>f(!1),onClose:()=>o()},"header"),/*#__PURE__*/e.jsx(as,{passkeys:l,expanded:g,onUnlink:w,onExpand:()=>f(!0)}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:()=>o()},"header"),/*#__PURE__*/e.jsx(An,{children:/*#__PURE__*/e.jsxs(os,{children:[/*#__PURE__*/e.jsx(rs,{}),/*#__PURE__*/e.jsx(ns,{})]})}),/*#__PURE__*/e.jsx(us,{children:"Secure your account with a passkey"}),/*#__PURE__*/e.jsx(ps,{}),0===l.length?/*#__PURE__*/e.jsx(is,{}):/*#__PURE__*/e.jsx(as,{passkeys:l,expanded:g,onUnlink:w,onExpand:()=>f(!0)}),/*#__PURE__*/e.jsxs(Nn,{style:{marginTop:"12px"},children:[h&&/*#__PURE__*/e.jsx(ss,{$fail:!0,children:h}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{u(!0),a().then((()=>m(!0))).catch((e=>{if(e instanceof i.PrivyError){if(e.privyErrorCode===i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE)return void p("Cannot link more passkeys to account.");if(e.privyErrorCode===i.PrivyErrorCode.PASSKEY_NOT_ALLOWED)return void p("Passkey request timed out or rejected by user.")}p("Unknown error occurred.")})).finally((()=>{u(!1)}))},loading:d,children:"Add new passkey"})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.UPDATE_EMAIL_SCREEN]:()=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Zn,{title:"Update your email",description:"Add the email address you'd like to use going forward. We'll send you a confirmation code",icon:/*#__PURE__*/e.jsx(We.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(eh,{stacked:!0})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]}),[c.ModalScreen.UPDATE_PHONE_SCREEN]:()=>{let{currentScreen:t,data:r,navigate:n,setModalData:a}=c.usePrivyModal(),{user:o}=c.usePrivyContext(),{initUpdatePhone:l}=i.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Zn,{title:"Update your phone number",description:"Add the phone number you'd like to use going forward. We'll send you a confirmation code",icon:/*#__PURE__*/e.jsx(Le.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(Rl,{stacked:!0,onSubmit:async function({qualifiedPhoneNumber:e}){try{if(!o?.phone?.number)throw Error("User is required to have an phone number to update it.");await l(o?.phone?.number,e),n(c.ModalScreen.AWAITING_PASSWORDLESS_CODE)}catch(e){a({errorModalData:{error:e,previousScreen:r?.errorModalData?.previousScreen||t||c.ModalScreen.LINK_PHONE_SCREEN}}),n(c.ModalScreen.ERROR_SCREEN)}},hideRecent:!0})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.CONNECT_ONLY_LANDING_SCREEN]:()=>{let{app:t,data:r}=c.usePrivyModal(),n=c.useAppConfig(),a=r?.externalConnectWallet?.suggestedAddress,o=a?/*#__PURE__*/e.jsxs("span",{children:["Connect the wallet with address ",/*#__PURE__*/e.jsx(s.Address,{showCopyIcon:!1,address:a})," ",t?.name?`to ${t.name}.`:"."]}):`Connect a wallet to your ${t?.name} account`,{connectors:l}=i.usePrivyInternal(),d=ba({walletList:r?.externalConnectWallet?.walletList??t.appearance.walletList,walletChainType:r?.externalConnectWallet?.walletChainType??t.appearance.walletChainType,connectors:l,connectOnly:!0,ignore:t.appearance.walletList,walletConnectEnabled:t.externalWallets.walletConnect.enabled});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),d.length>0&&/*#__PURE__*/e.jsx(Kn,{title:"Connect your wallet",description:o}),/*#__PURE__*/e.jsx(Jr,{$colorScheme:n.appearance.palette.colorScheme,children:/*#__PURE__*/e.jsx(Aa,{wallets:d})}),t&&/*#__PURE__*/e.jsx(s.TermsAndConditions,{app:t,alwaysShowImplicitConsent:!0}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN]:()=>{let{app:t,data:r}=c.usePrivyModal(),n=c.useAppConfig(),a=r?.externalConnectWallet?.suggestedAddress,o=a?`Connect the wallet with address ${s.formatWalletAddress(a)} ${t?.name?`to ${t.name}.`:"."}`:`Connect a wallet to ${t?.name}`,{connectors:l}=i.usePrivyInternal(),d=ba({walletList:r?.externalConnectWallet?.walletList??t.appearance.walletList,walletChainType:r?.externalConnectWallet?.walletChainType??t.appearance.walletChainType,connectors:l,connectOnly:!0,ignore:t.appearance.walletList,walletConnectEnabled:t.externalWallets.walletConnect.enabled});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),d.length>0&&/*#__PURE__*/e.jsx(Yn,{title:"Connect your wallet",description:o}),/*#__PURE__*/e.jsx(Jr,{$colorScheme:n.appearance.palette.colorScheme,children:/*#__PURE__*/e.jsx(Aa,{wallets:d})}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN]:()=>{let{app:t,setModalData:n,navigate:a,data:o,onUserCloseViaDialogOrKeybindRef:l}=c.usePrivyModal(),[d,u]=r.useState(""),{embeddedWallets:h}=c.useAppConfig(),{authenticated:p,user:y,getAccessToken:m}=c.usePrivyContext(),{closePrivyModal:g,walletProxy:f,refreshSessionAndUser:w,recoverPrimaryWallet:v}=i.usePrivyInternal(),{onSuccess:C,onFailure:x,callAuthOnSuccessOnClose:E}=o.createWallet,S=!0===t?.embeddedWallets.requireUserOwnedRecoveryOnCreate,{createWallet:T}=ii(),[A,b]=r.useState(null),_=new s.RunEffectOnce((async()=>{let e=await m();if(y&&e&&f)try{let r=c.getPrivyPrimaryWallet(y);if(r&&"privy"===r.recoveryMethod)await v();else if(r){let{entropyId:t,entropyIdVerifier:n}=c.getEntropyDetailsFromAccount(r);try{if(!await f.connect({accessToken:e,entropyId:t,entropyIdVerifier:n}))throw new i.PrivyClientError("Primary wallet not connected.")}catch(e){return b(r),void a(c.ModalScreen.EMBEDDED_WALLET_CREATED_SCREEN)}}let n=s.shouldCreateEmbeddedEthWallet(y,t.embeddedWallets.ethereum.createOnLogin),o=s.shouldCreateEmbeddedSolWallet(y,t.embeddedWallets.solana.createOnLogin);if(n&&o){let t=await T({user:y});if(await f.createSolana({accessToken:e,ethereumAddress:t?.address}),!t)return;return b(t),void a(c.ModalScreen.EMBEDDED_WALLET_CREATED_SCREEN)}if(o){await f.createSolana({accessToken:e,ethereumAddress:c.getPrivyEthereumWallet(y)?.address});let t=await w();return b(c.getPrivySolanaWallet(t)),void a(c.ModalScreen.EMBEDDED_WALLET_CREATED_SCREEN)}if(n){let e=await T({user:y});if(!e)return;b(e),a(c.ModalScreen.EMBEDDED_WALLET_CREATED_SCREEN)}}catch(e){u(e.message)}}));return r.useEffect((()=>p&&y?S?(n({...o,recoverySelection:{...o?.recoverySelection,isInAccountCreateFlow:!0}}),a(Ka({walletAction:"create",showAutomaticRecovery:!1,availableRecoveryMethods:h.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:!1,isResettingPassword:!1}))):void _.execute():(a(c.ModalScreen.LANDING),void x(Error("User must be authenticated before creating a Privy wallet")))),[S,p]),l.current=()=>null,d?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{closeable:!1}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(Fe.default,{fill:"var(--privy-color-error)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(Zn,{title:"Something went wrong",description:d})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{A?(C(A),g({shouldCallAuthOnSuccess:E})):(x(new i.PrivyEmbeddedWalletError("User wallet creation failed")),g({shouldCallAuthOnSuccess:!1}))},children:"Close"}),/*#__PURE__*/e.jsx(oi,{})]}):/*#__PURE__*/e.jsx(Ma,{})},[c.ModalScreen.EMBEDDED_WALLET_CREATED_SCREEN]:()=>{let{user:t}=c.usePrivyContext(),{closePrivyModal:n,isNewUserThisSession:a,updateWallets:o}=i.usePrivyInternal(),{app:l,data:d,onUserCloseViaDialogOrKeybindRef:u}=c.usePrivyModal(),{onSuccess:h,onFailure:p,callAuthOnSuccessOnClose:y}=d.createWallet,m=()=>{let e=c.getPrivyEthereumWallet(t)??c.getPrivySolanaWallet(t);e?(o(),h(e)):p(Error("Failed to create wallet")),n({shouldCallAuthOnSuccess:y})};return r.useEffect((()=>{let e=setTimeout(m,c.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[]),u.current=m,/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:m}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(Ue.default,{fill:"var(--privy-color-accent)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(Zn,{title:a?"Welcome"+(l?.name?` to ${l?.name}`:""):"All set!",description:a?"You’ve successfully created an account.":"Your account is secured."})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN]:()=>{let{authenticated:t,user:n,getAccessToken:a}=c.usePrivyContext(),{closePrivyModal:o,createAnalyticsEvent:l,walletProxy:d}=i.usePrivyInternal(),{navigate:u,data:h,setModalData:p,onUserCloseViaDialogOrKeybindRef:y}=c.usePrivyModal(),m=r.useMemo((()=>Date.now()),[]),[g,f]=r.useState(!1),{onCompleteNavigateTo:w,onFailure:v,shouldForceMFA:C,entropyId:x,entropyIdVerifier:E}=h?.connectWallet,S=e=>{g||(f(!0),v("string"==typeof e?Error(e):e))};r.useEffect((()=>{let e,r=c.getPrivyWalletWithAddress(n,x);return t&&r?d?((async()=>{let t=await a();if(!t)return S("User must be authenticated and have a Privy wallet before it can be connected");try{await d.connect({accessToken:t,entropyId:x,entropyIdVerifier:E}),C&&await d.verifyMfa({accessToken:t});let r=(Date.now()-m)/1e3;w===c.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN&&r<1?e=setTimeout((()=>{u(w,!1)}),1e3*(1-r)):u(w,!1)}catch(e){if(Ba(e)&&"privy"===r.recoveryMethod){let e=await a();if(!e)return S("User must be authenticated and have a Privy wallet before it can be recovered");try{l({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:r.address}});let t=await(d?.recover({accessToken:e,entropyId:x,entropyIdVerifier:E}));t?.entropyId||S(Error("Unable to recover wallet")),w?u(w):o({shouldCallAuthOnSuccess:!1}),l({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:r.address}}),u(w)}catch(e){S("An error has occurred, please try again.")}}else Ba(e)&&"privy"!==r.recoveryMethod?(p({...h,recoverWallet:{entropyId:x,entropyIdVerifier:E,onCompleteNavigateTo:w,onFailure:v},recoveryOAuthStatus:{provider:r.recoveryMethod,action:"recover",isInAccountCreateFlow:!1}}),u(Ya(r.recoveryMethod))):S(e)}})(),()=>clearTimeout(e)):void 0:S("User must be authenticated and have a Privy wallet before it can be connected")}),[t,n,d]);let T=()=>{S("User exited before wallet could be connected"),o({shouldCallAuthOnSuccess:!1})};return y.current=T,/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:T}),g?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(Fe.default,{fill:"var(--privy-color-error)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(Zn,{title:"Something went wrong",description:"We’re on it. Please try again later."})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>o({shouldCallAuthOnSuccess:!1}),children:"Close"})]}):/*#__PURE__*/e.jsx(Ma,{}),/*#__PURE__*/e.jsx(Qa,{})]})},[c.ModalScreen.EMBEDDED_WALLET_PASSWORD_RECOVERY_SCREEN]:()=>{let[t,n]=r.useState(!0),{authenticated:a,getAccessToken:o,user:l}=c.usePrivyContext(),{walletProxy:d,closePrivyModal:u,createAnalyticsEvent:h}=i.usePrivyInternal(),{navigate:p,data:y,onUserCloseViaDialogOrKeybindRef:m}=c.usePrivyModal(),[g,f]=r.useState(void 0),[w,v]=r.useState(""),[C,x]=r.useState(!1),{entropyId:E,entropyIdVerifier:S,onCompleteNavigateTo:T,onSuccess:A,onFailure:b}=y.recoverWallet,_=(e="User exited before their wallet could be recovered")=>{u({shouldCallAuthOnSuccess:!1}),b("string"==typeof e?new i.PrivyEmbeddedWalletError(e):e)};m.current=_,r.useEffect((()=>{if(!a)return _("User must be authenticated and have a Privy wallet before it can be recovered")}),[a]);/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:_}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(wd,{children:[/*#__PURE__*/e.jsxs(fd,{children:[/*#__PURE__*/e.jsx(dt.default,{height:48,width:48,stroke:"var(--privy-color-accent)"}),/*#__PURE__*/e.jsx("h3",{style:{color:"var(--privy-color-foreground)"},children:"Enter your password"}),/*#__PURE__*/e.jsx("p",{style:{color:"var(--privy-color-foreground-2)"},children:"Please provision your account on this new device. To continue, enter your recovery password."})]}),/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsxs(yi,{children:[/*#__PURE__*/e.jsx(hi,{type:t?"password":"text",onChange:e=>(e=>{e&&f(e)})(e.target.value),disabled:C,style:{paddingRight:"2.3rem"}}),/*#__PURE__*/e.jsx(vi,{style:{right:"0.75rem"},children:t?/*#__PURE__*/e.jsx(xi,{onClick:()=>n(!1)}):/*#__PURE__*/e.jsx(Ei,{onClick:()=>n(!0)})})]}),!!w&&/*#__PURE__*/e.jsx(vd,{children:w})]}),/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsxs(s.StyledCalloutSection,{children:[/*#__PURE__*/e.jsx("h4",{children:"Why is this necessary?"}),/*#__PURE__*/e.jsx("p",{children:"You previously set a password for this wallet. This helps ensure only you can access it"})]}),/*#__PURE__*/e.jsx(Cd,{loading:C||!d,disabled:!g,onClick:async()=>{x(!0);let e=await o(),t=c.getPrivyWalletWithAddress(l,E);if(!e||!t||null===g)return _("User must be authenticated and have a Privy wallet before it can be recovered");try{h({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t.address}}),await(d?.recover({accessToken:e,entropyId:E,entropyIdVerifier:S,recoveryPassword:g})),v(""),T?p(T):u({shouldCallAuthOnSuccess:!1}),A?.(t),h({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t.address}})}catch(e){!function(e){return Da(e)&&("invalid_recovery_pin"===e.type||"invalid_request_arguments"===e.type)}(e)?v("An error has occurred, please try again."):v("Invalid recovery password, please try again.")}finally{x(!1)}},warn:!1,hideAnimations:!E&&C,children:"Recover your account"})]})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_RECOVERY_SELECTION_SCREEN]:()=>{let[t,n]=r.useState(!1),{navigate:a,lastScreen:o,navigateBack:l,setModalData:d,data:u,onUserCloseViaDialogOrKeybindRef:h}=c.usePrivyModal(),{user:p}=c.usePrivyContext(),{embeddedWallets:y}=c.useAppConfig(),{closePrivyModal:m}=i.usePrivyInternal(),g=c.getPrivyPrimaryWallet(p),f=null===g,{isInAccountCreateFlow:w,isResettingPassword:v}=u.recoverySelection,C=g&&"privy"!==g.recoveryMethod,x=C?/*#__PURE__*/e.jsxs("span",{children:["Your account is currently secured using"," ",/*#__PURE__*/e.jsx("strong",{children:_d[g?.recoveryMethod||"user-passcode"]}),"."]}):"Select a method for logging in on new devices and recovering your account.";function E(e){d({recoveryOAuthStatus:{provider:e,action:f?"create-wallet":"set-recovery",isInAccountCreateFlow:w}}),a(c.ModalScreen.EMBEDDED_WALLET_RECOVERY_OAUTH_SCREEN)}function S(){u?.setWalletPassword?.onFailure(Error("User exited set recovery flow")),m({shouldCallAuthOnSuccess:u?.setWalletPassword?.callAuthOnSuccessOnClose??!1})}return h.current=S,/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:S,backFn:t?()=>n(!1):o?l:void 0,infoFn:o||t?void 0:()=>n(!0)},"header"),t?/*#__PURE__*/e.jsx(Id,{onClose:()=>n(!1)}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Zn,{title:C?"Update backup method":"Secure your account",icon:/*#__PURE__*/e.jsx(wt.default,{width:48}),description:x}),/*#__PURE__*/e.jsx(Sd,{children:y.userOwnedRecoveryOptions.filter((e=>!["icloud","google-drive"].includes(g?.recoveryMethod||"")||e!==g?.recoveryMethod)).sort().map((t=>{switch(t){case"google-drive":/*#__PURE__*/return e.jsxs(rn,{onClick:()=>E("google-drive"),children:[/*#__PURE__*/e.jsx(bd,{children:/*#__PURE__*/e.jsx(Ed,{style:{width:18}})}),"Back up to Google Drive"]},t);case"icloud":/*#__PURE__*/return e.jsxs(rn,{onClick:()=>E("icloud"),children:[/*#__PURE__*/e.jsx(bd,{children:/*#__PURE__*/e.jsx(xd,{style:{width:24}})}),"Back up to Apple iCloud"]},t);case"user-passcode":/*#__PURE__*/return e.jsxs(rn,{onClick:()=>{a($a({isCreatingWallet:f,skipSplashScreen:!0}))},children:[/*#__PURE__*/e.jsx(bd,{children:/*#__PURE__*/e.jsx(vt.default,{style:{width:18}})}),v?"Reset your":"Set a"," password"]},t);default:return null}}))})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_SET_AUTOMATIC_RECOVERY_SCREEN]:()=>{let{user:t,getAccessToken:n}=c.usePrivyContext(),{walletProxy:a,refreshSessionAndUser:o,closePrivyModal:l}=i.usePrivyInternal(),d=c.usePrivyModal(),{entropyId:u,entropyIdVerifier:h}=d.data?.recoverWallet,[p,y]=r.useState(!1),[m,g]=r.useState(null),[f,w]=r.useState(null);function v(){if(!p){if(f)return d.data?.setWalletPassword?.onFailure(f),void l();if(!m)return d.data?.setWalletPassword?.onFailure(Error("User exited set recovery flow")),void l()}}d.onUserCloseViaDialogOrKeybindRef.current=v;let C=!(!p&&!m);return f?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:v},"header"),/*#__PURE__*/e.jsx(Pd,{$color:"var(--privy-color-error)",style:{alignSelf:"center"},children:/*#__PURE__*/e.jsx(Pe.default,{height:38,width:38,stroke:"var(--privy-color-error)"})}),/*#__PURE__*/e.jsx(s.Title,{style:{marginTop:"0.5rem"},children:"Something went wrong"}),/*#__PURE__*/e.jsx(Zr,{style:{minHeight:"2rem"}}),/*#__PURE__*/e.jsx(s.PrimaryButtonWithoutGray,{onClick:()=>w(null),children:"Try again"}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:v},"header"),/*#__PURE__*/e.jsx(wt.default,{style:{width:"3rem",height:"3rem",alignSelf:"center"}}),/*#__PURE__*/e.jsx(s.Title,{style:{marginTop:"0.5rem"},children:"Automatically secure your account"}),/*#__PURE__*/e.jsx(s.Subtitle,{style:{marginTop:"1rem"},children:"When you log into a new device, you’ll only need to authenticate to access your account. Never get logged out if you forget your password."}),/*#__PURE__*/e.jsx(Zr,{style:{minHeight:"2rem"}}),/*#__PURE__*/e.jsx(s.PrimaryButtonWithoutGray,{loading:p,disabled:C,onClick:()=>async function(){y(!0);try{let e=await n(),r=c.getPrivyWalletWithAddress(t,u);if(!e||!a||!r)return;if(!(await a.setRecovery({accessToken:e,entropyId:u,entropyIdVerifier:h,existingRecoveryMethod:r.recoveryMethod,recoveryMethod:"privy"})).entropyId)throw Error("Unable to set recovery on wallet");let i=await o();if(!i)throw Error("Unable to set recovery on wallet");let s=c.getPrivyWalletWithAddress(i,r.address);if(!s)throw Error("Unabled to set recovery on wallet");g(!!i),setTimeout((()=>{d.data?.setWalletPassword?.onSuccess(s),l()}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS)}catch(e){w(e)}finally{y(!1)}}(),children:m?"Success":"Confirm"}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_RECOVERY_OAUTH_SCREEN]:()=>{let{logout:t}=c.usePrivyContext(),{navigate:n,setModalData:a,data:o}=c.usePrivyModal(),{recoveryOAuthFlow:l,closePrivyModal:d,createAnalyticsEvent:u}=i.usePrivyInternal(),[h,p]=r.useState(!1),{provider:y,action:m,isInAccountCreateFlow:g}=o?.recoveryOAuthStatus,[f,w]=r.useState(void 0),[v,C]=r.useState("create-wallet"===m);if("user-passcode"===y)throw Error("RecoveryOAuthScreen should never be called with a wallet that specifies recoveryMethod: `user-passcode`");let x=Ad[y].name,E=Ad[y].component,S=o?.recoverWallet?.onCompleteNavigateTo,T=new s.RunEffectOnce((async(e="create-wallet")=>(C(!0),new Promise(((t,r)=>{setTimeout((async()=>{try{let r=window.open();await l(y,e,r),p(!0),t()}catch(t){w({message:`${"recover"===e?"Recovery":"Back up"} with ${x} unsuccessful`,detail:"recover"===m?`Please verify that you are selecting the ${x} account associated with your backup.`:"",retryable:!0}),r()}}),0)})))));r.useEffect((()=>{"recover"!==m&&T.execute(g?"create-wallet":"set-recovery")}),[]),r.useEffect((()=>{if(!h)return;let e=setTimeout((()=>{g?(a({createWallet:{onSuccess:()=>{},onFailure:e=>{u({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"RecoveryOAuthScreen"}}),t()},callAuthOnSuccessOnClose:!0}}),n(c.ModalScreen.EMBEDDED_WALLET_CREATED_SCREEN)):d({shouldCallAuthOnSuccess:!1})}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}),[h]);let A=r.useCallback((async()=>{await T.execute("recover"),S?n(S):p(!0)}),[]),b="google-drive"===y?"Google Drive":"Apple iCloud",_=h&&`Successfully ${"recover"===m?"recovered":"backed up"} with ${b}.`||f&&f.message||`${"recover"===m?"Recovering":"Backing up"} with ${b}...`,I=f?f.detail:"";/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),v?/*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(Sd,{children:[/*#__PURE__*/e.jsx(Zn,{title:_,icon:/*#__PURE__*/e.jsx(E,{style:{width:"38px",height:"38px"}}),description:I}),f&&f?.retryable?/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{Gt(),w(void 0),"create-wallet"===m?T.execute("create-wallet"):A()},disabled:!h&&!f?.retryable,children:"Try again"}):null]})}):/*#__PURE__*/e.jsxs(Sd,{children:[/*#__PURE__*/e.jsx(Zn,{title:"Confirm it's really you",icon:/*#__PURE__*/e.jsx(E,{style:{height:42,width:48}}),description:`To confirm your identity, please log in to ${b} where your account is backed up.`}),/*#__PURE__*/e.jsxs(s.PrimaryButton,{onClick:A,children:["Confirm with ",b]})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN]:()=>{let[t,n]=r.useState(null),{authenticated:a,user:o,getAccessToken:l}=c.usePrivyContext(),{closePrivyModal:d,createAnalyticsEvent:u,clientAnalyticsId:h}=i.usePrivyInternal(),p=c.useAppConfig(),{data:y,onUserCloseViaDialogOrKeybindRef:m}=c.usePrivyModal(),{onFailure:g,onSuccess:f,origin:w,appId:v,appClientId:C,walletToExport:x,primaryWallet:E}=y.keyExport,S=e=>{d({shouldCallAuthOnSuccess:!1}),g("string"==typeof e?Error(e):e)},T=()=>{d({shouldCallAuthOnSuccess:!1}),f(),u({eventName:"embedded_wallet_key_export_completed",payload:{walletAddress:x.address}})};return r.useEffect((()=>{if(!a||!x)return S("User must be authenticated before exporting their wallet");l().then(n,S)}),[a,o]),m.current=T,/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:T}),/*#__PURE__*/e.jsxs(ri,{children:[/*#__PURE__*/e.jsx(s.Title,{children:"Transfer wallet"}),/*#__PURE__*/e.jsxs(s.Subtitle,{children:["Either copy your private key or seed phrase to transfer your wallet."," ",/*#__PURE__*/e.jsx("a",{href:"https://privy-io.notion.site/Transferring-your-account-9dab9e16c6034a7ab1ff7fa479b02828",target:"blank",rel:"noopener noreferrer",children:"Learn more"})]}),/*#__PURE__*/e.jsx(Ja,{theme:p.appearance.palette.colorScheme,children:"Never share your private key or seed phrase with anyone."}),/*#__PURE__*/e.jsx(s.WalletInfoCard,{isLoading:!1,isPulsing:!1,title:"Your wallet",address:x.address,showIcon:!0}),/*#__PURE__*/e.jsx("div",{style:{width:"100%"},children:t&&/*#__PURE__*/e.jsx(ti,{origin:w,appId:v,appClientId:C,accessToken:t,clientAnalyticsId:h,walletToExport:x,primaryWallet:E,dimensions:{height:"44px"}})})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN]:()=>{let{authenticated:t}=c.usePrivyContext(),{initializeWalletProxy:n,closePrivyModal:a}=i.usePrivyInternal(),{navigate:o,data:l,onUserCloseViaDialogOrKeybindRef:u}=c.usePrivyModal(),[h,p]=r.useState(!0),[y,m]=r.useState(""),[g,f]=r.useState(),[w,v]=r.useState(null),[C,x]=r.useState(!1),E=null!==w;r.useEffect((()=>{t||o(c.ModalScreen.LANDING)}),[t]),r.useEffect((()=>{n(c.WALLET_PROXY_TIMEOUT).then((e=>{p(!1),e||(m("An error has occurred, please try again."),f(new d.PrivyProviderRpcError(new d.ProviderRpcError(y,K.ProviderErrors.E32603_DEFAULT_INTERNAL_ERROR.eipCode))))}))}),[]);let{method:S,data:T,confirmAndSign:A,onSuccess:b,onFailure:_,uiOptions:I}=l.signMessage,P={title:I?.title||"Sign message",description:I?.description||"Signing this message will not cost you any fees.",buttonText:I?.buttonText||"Sign and continue"},j=e=>{e?b(e):_(g||new d.PrivyProviderRpcError(new d.ProviderRpcError("The user rejected the request.",K.ProviderErrors.E4001_USER_REJECTED_REQUEST.eipCode))),a({shouldCallAuthOnSuccess:!1}),setTimeout((()=>{v(null),m(""),f(void 0)}),200)};return u.current=()=>{j(w)},/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:()=>j(w)}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),I?.iconUrl&&"string"==typeof I.iconUrl?/*#__PURE__*/e.jsx(Xu,{children:/*#__PURE__*/e.jsx(Vu,{size:"sm",src:I.iconUrl,alt:"app image"})}):null,/*#__PURE__*/e.jsx(s.Title,{children:P.title}),/*#__PURE__*/e.jsx(s.Subtitle,{children:P.description}),"personal_sign"===S&&/*#__PURE__*/e.jsx(Eu,{children:Gu(T)}),"eth_signTypedData_v4"===S&&/*#__PURE__*/e.jsx(Ku,{typedData:T}),"solana_signMessage"===S&&/*#__PURE__*/e.jsx(Eu,{children:T}),/*#__PURE__*/e.jsx(Qu,{}),/*#__PURE__*/e.jsx(Yu,{$fail:!0,children:y}),/*#__PURE__*/e.jsx(s.PrimaryButtonWithoutGray,{disabled:C||E||h,loading:C,onClick:async()=>{x(!0),m("");try{let e=await A();v(e),x(!1),setTimeout((()=>{j(e)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS)}catch(e){console.error(e),m("An error has occurred, please try again."),f(new d.PrivyProviderRpcError(new d.ProviderRpcError(y,K.ProviderErrors.E32603_DEFAULT_INTERNAL_ERROR.eipCode))),x(!1)}},children:C?"Signing...":E?/*#__PURE__*/e.jsxs(Zu,{children:[/*#__PURE__*/e.jsx(co,{style:{height:"0.9rem",width:"0.9rem"},strokeWidth:2})," ",/*#__PURE__*/e.jsx("span",{children:"Success"})]}):P.buttonText}),I?.isCancellable&&/*#__PURE__*/e.jsx(s.EmbeddedButton,{style:{marginTop:"1rem"},onClick:()=>j(null),isSubmitting:!1,children:"Not now"}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN]:()=>{let{data:t,onUserCloseViaDialogOrKeybindRef:n,setModalData:a,navigate:o}=c.usePrivyModal(),{rpcConfig:l,chains:u,closePrivyModal:h,walletProxy:p,client:g,showFiatPrices:f}=i.usePrivyInternal(),{getAccessToken:w,user:v}=c.usePrivyContext(),C=c.useAppConfig(),[x,E]=r.useState(0),S=(e=>e?.sendTransaction?"transactionRequest"in e.sendTransaction?0:e.sendTransaction.transactionRequests.length-1:0)(t),[T,A]=r.useState(qu(t,x)),[b,_]=r.useState(null),[I,P]=r.useState(),[j,k]=r.useState(!1),[N,M]=r.useState(null),[R,O]=r.useState(null),[W,L]=r.useState(null),[U,F]=r.useState(void 0),[D,B]=r.useState(void 0),[H,z]=r.useState(!1),[q,V]=r.useState(!1),[G,$]=r.useState([]),[Y,Z]=r.useState([]),[X,Q]=r.useState(!1),[J,ee]=r.useState(void 0);if(!T||!t?.sendTransaction||!t?.sendTransaction.transactingWallet)/*#__PURE__*/return e.jsx(io,{error:Error("Invalid transaction request"),onClick:()=>{t?.sendTransaction?.onFailure(zu),h({shouldCallAuthOnSuccess:!1})}});let{entropyId:te,entropyIdVerifier:re,transactingWallet:ne}=t.sendTransaction,ae=r.useMemo((()=>u.find((e=>Number(e.id)===Number(T.chainId)))),[T.chainId]),ie=ae?.nativeCurrency.symbol??"ETH",oe=r.useMemo((()=>Fu(T.data,!!C.embeddedWallets.extendedCalldataDecoding)),[T.data]),{action:se,isErc20Ish:le,isNFTIsh:ce}=oe,{toAddress:de,tokenAddress:ue}=r.useMemo((()=>({toAddress:oe.isErc20Ish?oe.transferTo:T.to??void 0,tokenAddress:oe.isErc20Ish?T.to:void 0})),[oe]);r.useEffect((()=>{T.to&&ae&&le&&s.getErc20TokenInfo({address:T.to,chain:ae,rpcConfig:C.rpcConfig,privyAppId:C.id}).then(_).catch(console.error)}),[T.to,ae]);let{tokenPrice:he,isTokenPriceLoading:pe}=Po(T.chainId),{balance:ye}=s.useWalletBalance({rpcConfig:C.rpcConfig,appId:C.id,address:ne.address,chain:ae}),me=r.useMemo((()=>m.getPublicClient(Number(T.chainId),u,l,{appId:C.id})),[T.chainId,l]),ge=Hu(T,ne,me);r.useEffect((()=>{A(qu(t,x))}),[x]),r.useEffect((()=>{t.sendTransaction?.getIsSponsored?t.sendTransaction.getIsSponsored().then(P).catch(console.error):P(!1)}),[t.sendTransaction.getIsSponsored]);let fe=()=>{if(!j)return N?t?.sendTransaction?.onSuccess({hash:N}):W||ge?.errors[0]?t?.sendTransaction?.onFailure(W??ge?.errors[0]??zu):t?.sendTransaction?.onFailure(new d.PrivyProviderRpcError(new d.ProviderRpcError("The user rejected the request",K.ProviderErrors.E4001_USER_REJECTED_REQUEST.eipCode))),h({shouldCallAuthOnSuccess:!1})};n.current=fe;let we=!!(t.funding&&t.funding.supportedOptions.length>0),ve=s.getNativeCurrencyFromWei(BigInt(ge?.totalGasEstimate??0n),ie),Ce=f&&he?s.getDollarsFromWei(BigInt(ge?.totalGasEstimate??0n),he):void 0,xe=s.getNativeCurrencyFromWei(ye??0n,ie,void 0,!0),Ee=f&&he?s.getDollarsFromWei(ye??0n,he):void 0,Se=t.sendTransaction?.uiOptions?.transactionInfo?.title;Se||(Se="approve"===se?le?"Confirm address":"Confirm action":`Approve ${se}`);let Te=t.sendTransaction?.uiOptions?.description||(le&&"approve"===se?`${C.name} would like your permission for ${s.formatWalletAddress(oe.spender)} to spend tokens on your behalf.`:`${C.name} wants your permission to approve the following transaction.`),Ae=t.sendTransaction?.uiOptions?.transactionInfo?.contractInfo?.imgUrl?/*#__PURE__*/e.jsx("img",{src:t.sendTransaction.uiOptions.transactionInfo.contractInfo.imgUrl,alt:t.sendTransaction.uiOptions.transactionInfo.contractInfo.imgAltText}):null,be=!(!ge||ge.errors[0]||ge.hasFunds||!1!==I),_e=be&&we,Ie=_e?"Add funds":t.sendTransaction?.uiOptions?.buttonText||(x<S?"Continue":"Approve");if(r.useEffect((()=>{let e=(e,t,r)=>{if(t.isErc20Ish&&t.amount&&r)ee(s.formatErc20TokenAmount({amount:t.amount,decimals:r.decimals})),$([{value:J,symbol:r?.symbol}]);else if(e.value){let t=BigInt(e.value),r=he&&s.getDollarsFromWei(t,he);$(f&&r?[{value:r}]:[{value:s.parseNativeCurrencyFromWei(t),symbol:ie}])}else $(f?[{value:"$0"}]:[{value:"0",symbol:ie}])},t=ge?.tx??T;C.embeddedWallets.transactionScanning.enabled&&t?(Q(!0),(async e=>{if(g)return await g.scanTransaction({metadata:{domain:C.embeddedWallets.transactionScanning.domain},chain_id:e.chainId.toString(),request:{method:"eth_sendTransaction",params:[{from:e.from,to:e.to,value:e.value?.toString(),gas:e.gas?.toString(),gasPrice:e.gasPrice?.toString(),nonce:e.nonce?.toString(),data:e.data}]}})})(t).then((e=>{if(!e)throw Error("Transaction scan failed");if("Success"===e.validation.status&&("Benign"===e.validation.result_type?B("safe"):"Warning"===e.validation.result_type?B("warn"):"Malicious"===e.validation.result_type&&(B("error"),V(!0))),"Success"!==e.simulation.status)throw Error("Simulation failed");{F(e.simulation.params);let{assetsIn:t,assetsOut:r}=function(e,t){let r=[],n=[];if(e)for(let t of e)if(t.in[0]){let e;e="ERC721"===t.asset.type||"approve_for_all"===t.in[0].value?{nftName:t.asset.name}:{iconUrl:t.asset.logo_url,value:t.in[0].value,symbol:t.asset.symbol,usdValue:t.in[0].usd_price},r.push(e)}else if(t.out[0]?.value){let e;e="ERC721"===t.asset.type||"approve_for_all"===t.out[0].value?{nftName:t.asset.name}:{iconUrl:t.asset.logo_url,value:t.out[0].value,symbol:t.asset.symbol,usdValue:t.out[0].usd_price},n.push(e)}for(let e of t)for(let t of Object.keys(e.spenders)){let r;r="ERC721"===e.asset.type||"approve_for_all"===e.spenders[t]?.value?{nftName:e.asset.name}:{iconUrl:e.asset.logo_url,value:e.spenders[t]?.value,symbol:e.asset.symbol,usdValue:e.spenders[t]?.usd_price},n.push(r)}return{assetsIn:r,assetsOut:n}}(e.simulation.assets_diffs,e.simulation.exposures);if(0===r.length&&0===t.length)throw Error("No tokens found");$(r),Z(t)}Q(!1)})).catch((()=>{Q(!1),e(t,oe,b)}))):e(t,oe,b)}),[T,ge?.tx,oe,b]),R/*#__PURE__*/)return e.jsx(Iu,{txn:ge?.tx??T,onClose:fe,receipt:R,transactionInfo:t.sendTransaction?.uiOptions.transactionInfo,tokenPrice:he,tokenSymbol:ie,receiptHeader:t.sendTransaction?.uiOptions.successHeader,receiptDescription:t.sendTransaction?.uiOptions.successDescription});if(W)/*#__PURE__*/return e.jsx(Yd,{transactionError:W,transactionHash:N??void 0,network:"ethereum",chainId:ge?.tx.chainId??T.chainId,onClose:fe,onRetry:({resetNonce:e})=>{L(null);let t={...ge?.tx??T};e&&(t.nonce=void 0),A(t)}});let Pe=0!==S&&"number"==typeof x&&0!==x?()=>{E(x-1)}:void 0;return H&&U?/*#__PURE__*/e.jsx(bu,{details:U,onBack:()=>z(!1)}):/*#__PURE__*/e.jsx(zd,{transactionIndex:x,onBack:Pe,maxIndex:S,disabled:be&&!we||q,isSubmitting:j,submitError:W,isPreparing:!ge,isTokenPriceLoading:pe,isTokenContractInfoLoading:!ce&&!b,prepareError:ge?.errors[0],symbol:b?.symbol,chain:ae,img:Ae,title:Se,subtitle:Te,txValue:T.value,fee:Ce??ve,isSponsored:I,from:ne?.address??"",to:de,tokenAddress:ue??void 0,network:C.chains.find((e=>e.id===T.chainId))?.name??"",transactionDetails:{...oe,formattedAmount:J},cta:Ie,missingFunds:be,action:se,balance:Ee??xe,onClose:fe,onClick:_e?async()=>{if(!ne)return;if(!we)throw Error("Funding wallet is not enabled");let e=c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;a({...t,funding:{...t.funding,methodScreen:e,chainType:"ethereum",amount:y.formatEther(BigInt(ge?.tx.value??0)+BigInt(ge?.totalGasEstimate?.toString()??0)),chain:ae}}),o(e)}:async()=>{if(x<S)E(x+1);else{k(!0);try{let e=await w();if(j||!e||!ne||!p||!v)return;let r=t?.sendTransaction?.onConfirm?await t.sendTransaction.onConfirm():await vu({accessToken:e,transactingWallet:ne,entropyId:te,entropyIdVerifier:re,walletProxy:p,transactionRequest:ge?.tx??T,publicClient:me,requesterAppId:t.sendTransaction?.requesterAppId});if(M(r),t.sendTransaction?.signOnly)return await new Promise((e=>setTimeout(e,c.DEFAULT_SUCCESS_SCREEN_DURATION_MS))),t?.sendTransaction?.onSuccess({hash:r}),h({shouldCallAuthOnSuccess:!1});let n=await me.waitForTransactionReceipt({hash:r});if("reverted"===n.status)throw Error("Transaction failed");O(n)}catch(e){console.warn({transaction:ge?.tx??T,error:e}),L(e)}finally{k(!1)}}},validation:D,hasScanDetails:!!U,setIsScanDetailsOpen:z,preventMaliciousTransaction:q,setPreventMaliciousTransaction:V,tokensSent:G,tokensReceived:Y,isScanning:X,isCancellable:t.sendTransaction?.uiOptions?.isCancellable??!1})},[c.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN]:()=>{let{data:t,onUserCloseViaDialogOrKeybindRef:n,setModalData:a,navigate:o}=c.usePrivyModal(),{client:s,closePrivyModal:l,walletProxy:d,showFiatPrices:u}=i.usePrivyInternal(),h=c.useAppConfig(),{user:p,getAccessToken:m}=c.usePrivyContext(),[g,f]=r.useState(t?.sendSolanaTransaction?.transactionRequest),[w,v]=r.useState(),[C,x]=r.useState(),[E,S]=r.useState(0),[T,A]=r.useState({value:0n,isLoading:!1}),[b,_]=r.useState(!1),[I,P]=r.useState(),[j,k]=r.useState(),N=t?.sendSolanaTransaction?.connection,M=t?.sendSolanaTransaction?.transactingWallet,R=t?.sendSolanaTransaction?.signOnly??!1,O=w?.instructions.length??1,W=M?.imported?c.getImportedPrivySolanaWallet(p):c.getPrivyPrimaryWallet(p),L=c.getSolanaNetworkFromRpcEndpoint(N?.rpcEndpoint||""),{solPrice:U,isSolPriceLoading:F}=Io({enabled:u}),D=r.useMemo((()=>{let e,t;if(!w)return;let r=w.spender;0===E&&M?.address===r&&(e=No(w.fee));let n=No(T.value,3,!0),a=w.instructions[E];if(!a)return{fee:e,spender:r,balance:n};if("unknown"===a.type)return{fee:e,spender:r,program:a.program,balance:n};if("ata-creation"===a.type)return{fee:e,spender:r,balance:n,tokenAccountOwner:a.owner,tokenAccount:a.ata,tokenAddress:a.mint};let i=a.fromAccount,o="sol-transfer"===a.type?a.toAccount:a.toAccount||a.toAta,s="spl-transfer"===a.type?a.token.address:void 0;return null!=e&&"SOL"===a.token.symbol&&(t=No(a.value+w.fee)),{fee:e,spender:r,from:i,to:o,tokenAddress:s,amount:`${y.formatUnits(a.value,a.token.decimals)} ${a.token.symbol}`.trim(),total:t,balance:n}}),[w,E,M?.address,T]),B=r.useMemo((()=>{let e,t;if(!w||!u||!U||F)return;function r(...e){return Mo(e.reduce(((e,t)=>e+t),0n),U??0)}0===E&&M?.address===w.spender&&(e=r(w.fee));let n=r(T.value),a=w.instructions[E];return a&&"unknown"!==a.type&&"ata-creation"!==a.type?(null!=e&&"SOL"===a.token.symbol&&(t=r(a.value,w.fee)),{fee:e,amount:"SOL"===a.token.symbol?r(a.value):`${y.formatUnits(a.value,a.token.decimals)} ${a.token.symbol}`.trim(),total:t,balance:n}):{fee:e,balance:n}}),[w,u,U,F,M?.address,E,T]),H=r.useMemo((()=>{if(R||!w||T.isLoading||E>0)return!1;let e=w.instructions[E];if(!e)return!1;let t=0n;return M?.address===w.spender&&(t+=w.fee),"value"in e&&M?.address===e.fromAccount&&"SOL"===e.token.symbol&&(t+=e.value),T.value<t}),[w,T,E,R]);if(r.useEffect((()=>{!async function(){if(g&&N&&s)try{x(void 0);let e=await Lo({tx:g,connection:N,client:s});v(e),S(0)}catch(e){console.error("Failed to prepare transaction",e),x(e)}}()}),[g,N,s]),r.useEffect((()=>{(async function(){if(!M||!N)return;A({value:T.value,isLoading:!0});let e=new K.SolanaClient({name:"mainnet-beta",rpcUrl:N.rpcEndpoint});A({value:await e.getBalance(M.address).catch((()=>0n))??0n,isLoading:!1})})().catch(console.error)}),[w,N]),!(g&&t?.sendSolanaTransaction&&M&&N)){let r=Error("Invalid transaction request");/*#__PURE__*/return e.jsx(io,{error:r,onClick:()=>{t?.sendSolanaTransaction?.onFailure(r),l({shouldCallAuthOnSuccess:!1})}})}let z=()=>{if(!b)return I?t?.sendSolanaTransaction?.onSuccess(I):(t?.sendSolanaTransaction?.onFailure(j??C??Error("User exited the modal before submitting the transaction")),S(0)),l({shouldCallAuthOnSuccess:!1})};n.current=z;let q=t.sendSolanaTransaction?.uiOptions?.transactionInfo?.contractInfo?.imgUrl?/*#__PURE__*/e.jsx("img",{src:t.sendSolanaTransaction.uiOptions.transactionInfo.contractInfo.imgUrl,alt:t.sendSolanaTransaction.uiOptions.transactionInfo.contractInfo.imgAltText}):null,V=!!(t.funding&&t.funding.supportedOptions.length>0),G=H&&V;return I?/*#__PURE__*/e.jsx(fu,{instructions:w?.instructions.reduce(((e,t)=>("ata-creation"===t.type&&e.push({tokenAccountOwner:t.owner,tokenAccount:t.ata}),"spl-transfer"===t.type&&e.push({from:t.fromAccount,to:t.toAccount||t.toAta,amount:t.value,token:t.token}),"sol-transfer"===t.type&&e.push({from:t.fromAccount,to:t.toAccount,amount:t.value,token:t.token}),e)),[])??[],fees:0===E?I.fees:0n,onClose:z,transactionInfo:t.sendSolanaTransaction?.uiOptions.transactionInfo,solPrice:U,receiptHeader:t.sendSolanaTransaction?.uiOptions.successHeader,receiptDescription:t.sendSolanaTransaction?.uiOptions.successDescription,rpcEndpoint:N.rpcEndpoint,signOnly:R}):j?/*#__PURE__*/e.jsx(Yd,{transactionError:j,connection:N,onClose:z,network:"solana",onRetry:async()=>{k(void 0);let{blockhash:e}=await N.getLatestBlockhash();Oo(g)?g.message.recentBlockhash=e:g.recentBlockhash=e,f(g)}}):/*#__PURE__*/e.jsx(qd,{img:q,title:t.sendSolanaTransaction?.uiOptions?.transactionInfo?.title||"Confirm transaction",subtitle:t.sendSolanaTransaction?.uiOptions?.description||`${h.name} wants your permission to approve the following transaction.`,cta:G?"Add funds":t.sendSolanaTransaction?.uiOptions?.buttonText||"Approve",transactionIndex:E,maxIndex:O-1,network:"mainnet-beta"==L?"Solana":L,blockExplorerUrl:"https://explorer.solana.com",total:u?B?.total:D?.total,amount:u?B?.amount:D?.amount,fee:u?B?.fee:D?.fee,balance:u?B?.balance:D?.balance,from:D?.from,to:D?.to,tokenAccount:D?.tokenAccount,tokenAccountOwner:D?.tokenAccountOwner,tokenAddress:D?.tokenAddress,transactingWalletAddress:M.address,programAddress:D?.program,disabled:H&&!V,isSubmitting:b,isPreparing:!w||T.isLoading,isTokenPriceLoading:u&&F,isMissingFunds:H,submitError:j??void 0,parseError:C,onClick:G?async()=>{if(!M)return;if(!V)throw Error("Funding wallet is not enabled");let e=c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;a({...t,funding:{...t.funding,methodScreen:e}}),o(e)}:async()=>{if(E<(w?.instructions.length??1)-1)S(E+1);else try{_(!0);let e=await m();if(b||!e||!M||!d||!p||!W)return;let{rootWallet:r}=c.getSolanaSigningAndRootWallet(p,M.address);if(!r)throw Error("No root wallet for transacting wallet found");let{entropyId:n,entropyIdVerifier:a}=c.getEntropyDetailsFromAccount(r);if(R)await jd({tx:g,accessToken:e,walletProxy:d,entropyId:n,entropyIdVerifier:a,transactingWalletAddress:M.address,transactingWalletIndex:M.walletIndex??0}),P(Wo("",g,null));else{let{signature:r,receipt:i}=await kd({tx:g,accessToken:e,connection:N,walletProxy:d,entropyId:n,entropyIdVerifier:a,transactingWalletAddress:M.address,transactingWalletIndex:M.walletIndex??0,transactionOptions:t.sendSolanaTransaction?.transactionOptions});P(Wo(r,g,i))}}catch(e){console.warn({transaction:g,error:e}),k(e)}finally{_(!1)}},onClose:z,onBack:E>0&&O>1?()=>S(E-1):void 0})},[c.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN]:()=>{let{app:t,data:n}=c.usePrivyModal(),{closePrivyModal:a}=i.usePrivyInternal(),[o,l]=r.useState(!1),[d,u]=r.useState(),{address:h,onDelegate:p,onSuccess:y,onError:m}=n.delegatedActions.consent,g=async()=>{o?y():m(d??new i.PrivyClientError("User declined delegating actions.")),a({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!o&&!d)return;let e=setTimeout(g,c.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[o,d]),o||d?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:g}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.HorizontallyCenteredItem,{children:[d?/*#__PURE__*/e.jsx(ke.default,{stroke:"var(--privy-color-error)",width:"64px",height:"64px"}):/*#__PURE__*/e.jsx(De.default,{stroke:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(s.ConfigurableSpacer,{height:20}),/*#__PURE__*/e.jsx(Zn,{title:d?"Something went wrong":"Success!",description:d?"Please try again.":`You’ve successfully granted delegated action permissions to ${t.name}.`})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{closeable:!0,onClose:g}),/*#__PURE__*/e.jsx(Be.default,{width:56,height:56,style:{margin:"auto"}}),/*#__PURE__*/e.jsx(bn,{style:{marginTop:24,color:"var(--privy-color-foreground)"},children:"Enable offline access"}),/*#__PURE__*/e.jsxs(_n,{style:{marginBottom:24,textWrap:"pretty"},children:["By confirming, ",t.name," will be able to use your wallet for you even when you're not around. You can revoke this later."]}),/*#__PURE__*/e.jsx(ka,{showIcon:!0,address:h,title:"Wallet",isLoading:!1}),/*#__PURE__*/e.jsxs(ja,{style:{marginTop:24},children:[/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:g,children:"Not now"}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:async()=>{try{await p(),l(!0)}catch(e){u(e)}},children:"Accept"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN]:()=>{let{app:t,data:n}=c.usePrivyModal(),{closePrivyModal:a}=i.usePrivyInternal(),[o,l]=r.useState(!1),[d,u]=r.useState(),{onRevoke:h,onSuccess:p,onError:y}=n.delegatedActions.revoke,m=async()=>{o?p():y(d??new i.PrivyClientError("User declined revoking access to their delegated wallet.")),a({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!o&&!d)return;let e=setTimeout(m,c.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[o,d]),o||d?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:m}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.HorizontallyCenteredItem,{children:[d?/*#__PURE__*/e.jsx(ke.default,{stroke:"var(--privy-color-error)",width:"64px",height:"64px"}):/*#__PURE__*/e.jsx(De.default,{stroke:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(s.ConfigurableSpacer,{height:20}),/*#__PURE__*/e.jsx(Zn,{title:d?"Something went wrong":"Success!",description:d?"Please try again.":"You've successfully revoked permissions."})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{closeable:!0,onClose:m}),/*#__PURE__*/e.jsx(He.default,{width:56,height:56,style:{margin:"auto"}}),/*#__PURE__*/e.jsx(bn,{style:{marginTop:24},children:"Revoke offline access to wallet"}),/*#__PURE__*/e.jsxs(_n,{children:["By confirming, ",t.name," will no longer be able to use this wallet on your behalf when you are not online."]}),/*#__PURE__*/e.jsxs(Na,{style:{marginTop:24},children:[/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:m,children:"Deny"}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:async()=>{try{await h(),l(!0)}catch(e){u(e)}},children:"Confirm"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN]:()=>{let{wallets:t}=c.useWallets(),{wallets:n}=d.useSolanaWallets(),{navigate:o,data:l,setModalData:u}=c.usePrivyModal(),{client:h}=i.usePrivyInternal(),p=c.useAppConfig(),y=l?.funding,m=Gs(Js),g=Gs(el),f="solana"===y.chainType,w=f?void 0:y,v=r.useMemo((()=>((e,t,r,n,a,i)=>{let o,s,l="solana"===r.chainType,d=l?void 0:r,u=r.isUSDC?"USDC":d?.erc20Address?void 0:"native-currency",h=!!l||u&&K.isSupportedChainIdForMoonpay(Number(r.chain.id),u),p=!!l||u&&K.isSupportedChainIdForCoinbaseOnramp(Number(r.chain.id),u),y=[];for(let o of(r.preferredCardProvider&&r.supportedOptions.sort((e=>e.provider===r.preferredCardProvider?-1:1)),r.supportedOptions))"card"===o.method&&"coinbase"===o.provider&&p&&y.push((()=>Zs(t,r,n,a,i,"buy"))),"card"===o.method&&"moonpay"===o.provider&&h&&u&&y.push((()=>Xs(t,r,e,u,n,a,i,"credit_debit_card")));for(let e of r.supportedOptions)"exchange"===e.method&&"coinbase"===e.provider&&p&&(o=()=>Zs(t,r,n,a,i,"buy"));for(let e of i?.funding?.supportedOptions??[])"wallets"===e.method&&(s=()=>a(c.ModalScreen.FUNDING_TRANSFER_FROM_WALLET_SCREEN));return{onFundWithCard:y,onFundWithExchange:o,onFundWithWallet:s}})(p,h,y,u,o,l)),[p,h,y,l,u,o]);r.useEffect((()=>{if(y?.defaultFundingMethod&&y.usingDefaultFundingMethod)switch(u({funding:{...y,usingDefaultFundingMethod:!1}}),y?.defaultFundingMethod){case"card":v.onFundWithCard[0]&&v.onFundWithCard[0]();break;case"exchange":v.onFundWithExchange&&v.onFundWithExchange();break;case"wallet":v.onFundWithWallet&&v.onFundWithWallet();break;case"manual":o(c.ModalScreen.FUNDING_MANUAL_TRANSFER_SCREEN)}}),[]),r.useEffect((()=>{w?.erc20Address&&!w.erc20ContractInfo&&s.getErc20TokenInfo({address:w.erc20Address,chain:w.chain,rpcConfig:p.rpcConfig,privyAppId:p.id}).then((e=>{u({...l,funding:{...w,erc20ContractInfo:e?{symbol:e.symbol,decimals:e.decimals}:void 0}})})).catch(console.error)}),[w?.erc20Address,w?.chain]);let C=f?n.find((({address:e})=>e===y.address)):t.find((({address:e})=>a.getAddress(e)===a.getAddress(y.address))),x=s.useExternalWalletListing(C?.walletClientType||"unknown"),E=x?.name||"wallet",S=C&&"privy"!==C.walletClientType?E:p.name,T=!(!w?.erc20Address||w?.erc20ContractInfo);/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsxs("h3",{children:["Add funds to your"," ",S?.toLowerCase().endsWith("wallet")?S:S+" wallet"]}),/*#__PURE__*/e.jsxs(Cs,{children:[y.errorMessage&&/*#__PURE__*/e.jsx(Ds,{theme:p.appearance.palette.colorScheme,children:y.errorMessage}),v.onFundWithCard?.[0]&&/*#__PURE__*/e.jsxs(rn,{disabled:T,onClick:v.onFundWithCard[0],children:[/*#__PURE__*/e.jsx(xs,{children:/*#__PURE__*/e.jsx(rt.default,{style:{width:24}})}),"Pay with card",m?/*#__PURE__*/e.jsx(qs,{style:{marginLeft:"auto",maxWidth:"100%",width:"auto",height:"0.875rem"}}):g?/*#__PURE__*/e.jsx(Vs,{style:{marginLeft:"auto",maxWidth:"100%",width:"auto",height:"0.875rem"}}):null]}),v.onFundWithExchange&&/*#__PURE__*/e.jsxs(rn,{disabled:T,onClick:v.onFundWithExchange,children:[/*#__PURE__*/e.jsx(xs,{children:/*#__PURE__*/e.jsx(tt.default,{style:{width:24}})}),"Transfer from an exchange"]}),v.onFundWithWallet&&/*#__PURE__*/e.jsxs(rn,{disabled:T,onClick:v.onFundWithWallet,children:[/*#__PURE__*/e.jsx(xs,{children:/*#__PURE__*/e.jsx(s.WalletCards,{style:{width:24}})}),"Transfer from wallet"]}),/*#__PURE__*/e.jsxs(rn,{disabled:T,onClick:()=>o(c.ModalScreen.FUNDING_MANUAL_TRANSFER_SCREEN),children:[/*#__PURE__*/e.jsx(xs,{children:/*#__PURE__*/e.jsx(nt.default,{style:{width:24}})}),"Receive funds"]}),y?.showAlternateFundingMethod&&v.onFundWithCard?.[1]&&/*#__PURE__*/e.jsx(Hs,{theme:p.appearance.palette.colorScheme,children:/*#__PURE__*/e.jsxs(Is,{children:["Having trouble or facing location restrictions?"," ",/*#__PURE__*/e.jsx(Ps,{onClick:v.onFundWithCard[1],children:"Try a different provider."})]})})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.MOONPAY_STATUS_SCREEN]:()=>{let{app:t,data:r,setModalData:n,navigateBack:a}=c.usePrivyModal(),{closePrivyModal:o}=i.usePrivyInternal(),{externalTransactionId:l}=r?.moonpayStatus,u=d.usePollMoonpayTransactionStatus(l||null,t.fundingMethodConfig.moonpay.useSandbox??!1);/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{title:"Fund account",backFn:()=>{let e={...r?.funding,showAlternateFundingMethod:!0};e.usingDefaultFundingMethod&&(e.usingDefaultFundingMethod=!1),n({funding:e}),a()}}),/*#__PURE__*/e.jsx(al,{status:u,onClickCta:o}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.COINBASE_ONRAMP_STATUS_SCREEN]:()=>{let{data:t,setModalData:n,navigate:a,navigateBack:o}=c.usePrivyModal(),{closePrivyModal:l,createAnalyticsEvent:u,client:h}=i.usePrivyInternal(),[p,y]=r.useState("pending-in-flow"),m=r.useRef(0),g={...t?.funding,showAlternateFundingMethod:!0};g.usingDefaultFundingMethod&&(g.usingDefaultFundingMethod=!1);let{partnerUserId:f,popup:w}=t?.coinbaseOnrampStatus??{};return r.useEffect((()=>{if("pending-in-flow"===p||"pending-after-flow"===p){let e=setInterval((async()=>{if(f)try{let{status:e}=await h.getCoinbaseOnRampStatus({partnerUserId:f});if("success"===e)return void y("success");if("failure"===e)throw Error("There was an error completing Coinbase Onramp flow.");if(m.current>=3)return n({funding:g}),void a(c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN);w?.closed&&(m.current=m.current+1,y("pending-after-flow"))}catch(e){console.error(e),y("error"),u({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{status:"failure",provider:"coinbase-onramp",error:e.message}}),n({funding:{...g,errorMessage:"Something went wrong adding funds. Please try again or use another method."}}),a(c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN)}}),1500);return()=>clearInterval(e)}}),[f,w,p]),/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{title:"Fund account",backFn:()=>{n({funding:g}),o()}},"header"),/*#__PURE__*/e.jsx(Ws,{status:p,onClickCta:l}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_TRANSFER_FROM_WALLET_SCREEN]:()=>{let t,{connectors:n}=i.usePrivyInternal(),{app:a,setModalData:o,data:l,navigate:u}=c.usePrivyModal(),{wallets:h}=c.useWallets(),{wallets:p}=d.useSolanaWallets(),[y,m]=r.useState("default"),g="solana"===l?.funding?.chainType,f=!!l?.funding?.crossChainBridgingEnabled;t="ethereum"===l?.funding?.chainType?l.funding.erc20Address&&!l.funding.isUSDC?"ethereum-only":f&&!l.funding.chain.testnet?"ethereum-and-solana":"ethereum-only":f?"ethereum-and-solana":"solana-only";let w=h.filter((e=>"privy"!==e.walletClientType)),v=w.map((e=>e.walletClientType)),C=p.filter((e=>"privy"!==e.walletClientType)),x=C.map((e=>e.walletClientType)),E=[],S={...l.funding};S.usingDefaultFundingMethod&&(S.usingDefaultFundingMethod=!1);let T=({address:e,walletChainType:t})=>{o({...l,funding:{...S,connectedWalletAddress:e,onContinueWithExternalWallet:()=>u(b({destChainType:g?"solana":"ethereum",sourceChainType:t}))}}),u(c.ModalScreen.FUNDING_EDIT_AMOUNT_SCREEN)};"solana-only"!==t&&E.push(...w.map(((t,r)=>/*#__PURE__*/e.jsx(cl,{onClick:()=>T({address:t.address,walletChainType:"ethereum"}),icon:t.meta.icon,name:t.meta.name,chainType:t.type},r)))),"ethereum-only"!==t&&E.push(...C.map(((t,r)=>/*#__PURE__*/e.jsx(cl,{onClick:()=>T({address:t.address,walletChainType:"solana"}),icon:t.meta.icon,name:t.meta.name,chainType:t.type},r)))),E.push(...ba({walletList:a.appearance.walletList.filter((e=>!w.some((t=>t.walletClientType===e))&&!C.some((t=>t.walletClientType===e)))),walletChainType:t,connectors:n,connectOnly:!0,ignore:[...a.appearance.walletList,...v,...x],walletConnectEnabled:a.externalWallets.walletConnect.enabled}));let A=/*#__PURE__*/e.jsx(ll,{text:"More wallets",onClick:()=>m("overflow")}),b=({sourceChainType:e,destChainType:t})=>"ethereum"===e&&"solana"===t?c.ModalScreen.FUNDING_AWAITING_EVM_TO_SOL_BRIDGING_SCREEN:"ethereum"===e&&"ethereum"===t?c.ModalScreen.FUNDING_AWAITING_TRANSFER_FROM_EXTERNAL_WALLET_SCREEN:"solana"===e&&"ethereum"===t?c.ModalScreen.FUNDING_AWAITING_SOL_TO_EVM_BRIDGING_SCREEN:c.ModalScreen.FUNDING_AWAITING_TRANSFER_FROM_EXTERNAL_SOLANA_WALLET_SCREEN;return r.useEffect((()=>{o({...l,externalConnectWallet:{onCompleteNavigateTo:({walletChainType:e})=>(o({...l,funding:{...S,onContinueWithExternalWallet:()=>{u(b({destChainType:g?"solana":"ethereum",sourceChainType:e??"ethereum"}))}}}),c.ModalScreen.FUNDING_EDIT_AMOUNT_SCREEN)}})}),[]),"overflow"===y?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:()=>m("default")},"header"),/*#__PURE__*/e.jsxs(Qr,{children:[/*#__PURE__*/e.jsx(s.Subtitle,{style:{color:"var(--privy-color-foreground-3)",textAlign:"left"},children:"More wallets"}),E]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(Zn,{title:"Transfer from wallet",description:"Connect a wallet to deposit funds or send funds manually to your wallet address."}),/*#__PURE__*/e.jsxs(Qr,{children:[E.length>4?E.slice(0,3):E,E.length>4&&A]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_EDIT_AMOUNT_SCREEN]:()=>{let{data:t,setModalData:n}=c.usePrivyModal(),a=t?.funding,i="solana"===a.chainType,o=r.useRef(null),{tokenPrice:l}=Po(i?"solana":a.chain.id),d=i?void 0:a,u=!(!d?.erc20Address||d?.erc20ContractInfo),h=i?"SOL":a.erc20Address?a.erc20ContractInfo?.symbol:a.chain.nativeCurrency.symbol||"ETH",p=parseFloat(a.amount),y=!isNaN(p)&&p>0,m=l?s.getDollarsFromStringFloat(a.amount,l):void 0;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(s.Title,{children:"Confirm or edit amount"}),/*#__PURE__*/e.jsxs(s.FlexContainer,{style:{marginTop:"32px"},children:[/*#__PURE__*/e.jsx(Es,{children:u?/*#__PURE__*/e.jsx(So,{size:"50px"}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsxs(Ss,{onClick:()=>o.current?.focus(),children:[/*#__PURE__*/e.jsx(As,{ref:o,value:a.amount,onChange:e=>{let r=e.target.value;/^[0-9.]*$/.test(r)&&r.split(".").length-1<=1&&n({...t,funding:{...a,amount:r}})}}),/*#__PURE__*/e.jsx(bs,{children:h})]}),!d?.erc20Address&&/*#__PURE__*/e.jsx(_s,{children:m&&y?`${m} USD`:""})]})}),/*#__PURE__*/e.jsx(s.PrimaryButtonWithoutGray,{style:{marginTop:"1rem"},disabled:!y,onClick:a.onContinueWithExternalWallet,children:"Continue"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_AWAITING_TRANSFER_FROM_EXTERNAL_WALLET_SCREEN]:()=>{let{rpcConfig:t,appId:n,closePrivyModal:a,createAnalyticsEvent:o}=i.usePrivyInternal(),{navigate:l,setModalData:u,app:h,data:p}=c.usePrivyModal(),{wallets:g}=c.useWallets(),[f,w]=r.useState(!1),[v,C]=r.useState(0n),[x,E]=r.useState(!1),[S,T]=r.useState(null),[A,b]=r.useState(null),[_,I]=r.useState([]),[P,j]=r.useState(0),[k,N]=r.useState(!1),[M,R]=r.useState(!1),[O,W]=r.useState(!1),[L,U]=r.useState(!1),[F,D]=r.useState(),[B,H]=r.useState();if(!p?.funding||"ethereum"!==p.funding.chainType)throw Error("Invalid funding data");let{erc20ContractInfo:z,chain:q,connectedWalletAddress:V}=p.funding,G=p.funding.address,$=p.funding.erc20Address,[K,Y]=r.useState(p.funding.amount);r.useEffect((()=>{$&&!z&&T(Error("Unable to fetch token details"))}),[]);let Z=!!$&&!!z,X=Z?BigInt(parseFloat(K)*10**z.decimals):y.parseEther(K),Q=V?g.find((({address:e})=>e===V)):g[0],J=s.useExternalWalletListing(Q?.walletClientType||"unknown"),ee=J?.name||"wallet",[te,re]=r.useState(null);r.useEffect((()=>{(async()=>{if(!Q)return;let e=await Q.getEthereumProvider();re(y.createWalletClient({account:Q.address,transport:y.custom(e)}).extend(y.publicActions))})().catch(console.error)}),[Q]);let[ne,ae]=r.useState(0n);r.useEffect((()=>{y.createPublicClient({chain:q,transport:y.http(m.getJsonRpcEndpointFromChain(q,t,n))}).getBalance({address:G}).then(ae).catch(console.error)}),[]);let[ie,oe]=r.useState(0n);r.useEffect((()=>{Z&&s.getErc20Balance({chain:q,address:G,appId:n,rpcConfig:t,erc20Address:$}).then((e=>oe(e.balance))).catch(console.error)}),[]);let{tokenPrice:se}=Po(q.id),[le,ce]=r.useState({to:G,chain:q,value:X,data:void 0});r.useEffect((()=>{(async()=>{let e,r;if(!te||!Q||k||O)return;N(!0);let a=y.createPublicClient({chain:le.chain,transport:y.http(m.getJsonRpcEndpointFromChain(le.chain,t,n))});if(Z&&!le.data)return await a.simulateContract({address:$,chain:le.chain,abi:Os,functionName:"transfer",args:[G,X],account:Q.address}).catch((e=>{console.warn("Simulated token transfer failed with error, fetching bridge options.",e)}))?(N(!1),void ce({to:$,chain:le.chain,data:y.encodeFunctionData({abi:Os,functionName:"transfer",args:[G,X]}),value:"0x0"})):(N(!1),void E(!0));try{e=await a.prepareTransactionRequest({account:Q.address,to:le.to,chain:le.chain,data:le.data,value:BigInt(le.value??0)})}catch(e){if(console.error(e),_.length>1)b(e.shortMessage??"Something went wrong");else if(M&&0===_.length)return void T(new i.PrivyClientError(`Wallet ${s.formatWalletAddress(Q.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE))}if(!e)return N(!1),void E(!0);N(!1),W(!0),w(!0),C(e.gas);try{await te.switchChain({id:le.chain.id})}catch(e){await te.addChain({chain:le.chain}),await te.switchChain({id:le.chain.id})}try{r=await te.sendTransaction(e)}catch(e){if(console.error(e),"TransactionExecutionError"===e.name)if(_.length<1){let t=e.shortMessage;(e.shortMessage.includes("rejected the request")||e.details.includes("rejected the request"))&&(t="User rejected the request."),T(new i.PrivyClientError(t,void 0,i.PrivyErrorCode.TRANSACTION_FAILURE))}else b(e.shortMessage??"Something went wrong")}if(r)return await te.waitForTransactionReceipt({hash:r}),W(!1),M?(D(r),void H("pending")):(U(!0),void o({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:r,address:Q.address,chainId:le.chain.id,chainType:"ethereum",value:le.value?y.formatUnits(BigInt(le.value),z?.decimals??18):void 0,token:z?.symbol??$??"ETH",destinationAddress:G,destinationChainId:q.id,destinationChainType:"ethereum",destinationValue:X?y.formatUnits(X,z?.decimals??18):void 0,destinationToken:z?.symbol??$??q.nativeCurrency.name}}));W(!1)})().catch(console.error)}),[te,le]),r.useEffect((()=>{(async()=>{if(!x||!te||!Q)return;let e=c.addToDefaultChains(h.chains).filter((e=>e.id!==q.id&&!!e.testnet==!!q.testnet));Z&&e.unshift(q);let r=await Bo({chains:e,address:Q.address,appId:n,rpcConfig:t}),a=Z?r.filter((e=>e.balance>0n)):r.filter((e=>e.balance>X));if(a.length<1)return void T(new i.PrivyClientError(`Wallet ${s.formatWalletAddress(Q.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE));a.sort(((e,t)=>Number(t.balance-e.balance)));let o=(await Promise.allSettled(a.map((async e=>({quote:await to({isTestnet:!!q.testnet,input:Qi({amount:X.toString(),user:Q.address,recipient:G,destinationChainId:q.id,destinationCurrency:$,originChainId:e.chain.id})}),...e}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(o.length<1)return void T(new i.PrivyClientError(`Wallet ${s.formatWalletAddress(Q.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE));let l=o.map((e=>({bridgeTx:ro(e.quote),balance:e.balance,chain:e.chain}))).filter((e=>!!e.bridgeTx));if(l.length>1)return void I(l);let d=l[0];d?(R(!0),ce({data:d.bridgeTx.data,to:d.bridgeTx.to,value:d.bridgeTx.value,chain:d.chain})):T(new i.PrivyClientError(`Wallet ${s.formatWalletAddress(Q.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE))})().catch(console.error)}),[x]),no({transactionHash:F,wallet:Q,isTestnet:!!q.testnet,bridgingStatus:B,setBridgingStatus:H,onSuccess({transactionHash:e,wallet:t}){R(!1),U(!0),o({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:e,address:t.address,chainId:le.chain.id,chainType:"ethereum",value:le.value?y.formatUnits(BigInt(le.value),z?.decimals??18):void 0,token:z?.symbol??$??"ETH",destinationAddress:G,destinationChainId:q.id,destinationChainType:"ethereum",destinationValue:X?y.formatUnits(X,z?.decimals??18):void 0,destinationToken:z?.symbol??$??q.nativeCurrency.name}})},onFailure({error:e}){R(!1),T(e)}}),r.useEffect((()=>{if(!S)return;let e={error:S,previousScreen:c.ModalScreen.FUNDING_TRANSFER_FROM_WALLET_SCREEN};u({funding:p?.funding,sendTransaction:p?.sendTransaction,errorModalData:e}),l(c.ModalScreen.ERROR_SCREEN,!1)}),[S]);let de=!Z&&se?s.getDollarsFromStringFloat(K??"0",se):void 0,ue=Z?v:s.sumWeiQuantities([v,X]),he=ue&&se?s.getDollarsFromWei(ue,se):void 0,pe=ue?s.getNativeCurrencyFromWei(ue,"ETH"):void 0,ye=v&&se?s.getDollarsFromWei(v,se):void 0,me=v?s.getNativeCurrencyFromWei(v,"ETH"):void 0;if(r.useEffect((()=>{if(!L)return;let e=setTimeout(a,c.DEFAULT_SUCCESS_SCREEN_EXTRA_LONG_DURATION_MS);return()=>clearTimeout(e)}),[L]),L/*#__PURE__*/)return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(De.default,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(Zn,{title:"Success!",description:`You’ve successfully added ${K} ${Z?z.symbol:q.nativeCurrency.symbol} to your ${h.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let ge=Z?`${s.formatErc20TokenAmount({amount:ie,decimals:z.decimals})} ${z.symbol}`:s.getNativeCurrencyFromWei(ne,q.nativeCurrency.symbol,3,!0),fe=_[P];return _.length>1&&fe?/*#__PURE__*/e.jsx(js,{displayName:ee,configuredFundingChain:q,formattedBalance:ge,fundingAmount:K,fundingCurrency:Z?z.symbol:q.nativeCurrency.symbol,fundingAmountInUsd:de,options:_,selectedOption:fe,isPreparing:k,isSubmitting:O,addressToFund:G,fundingWalletAddress:Q?.address||"",errorMessage:A,onSubmit:()=>{p.funding?.amount!==K?async function(){if(Q&&fe)try{let e=await to({isTestnet:!!q.testnet,input:Qi({amount:X.toString(),user:Q.address,recipient:G,destinationChainId:q.id,destinationCurrency:$,originChainId:fe.chain.id})}),t=ro(e);if(!t)throw Error("Invalid transaction request");R(!0),ce({data:t.data,to:t.to,value:t.value,chain:fe.chain})}catch(e){console.error(e),T(new i.PrivyClientError("Unable to fetch quotes for bridging",e,i.PrivyErrorCode.INSUFFICIENT_BALANCE))}}().catch(console.error):ce({to:fe.bridgeTx.to,data:fe.bridgeTx.data,value:fe.bridgeTx.value,chain:fe.chain})},onSelect:e=>{e!==P&&(b(null),j(e))},onAmountChange:Y}):f&&v&&Q&&p?.funding?/*#__PURE__*/e.jsx(ks,{wallet:Q,displayName:ee,addressToFund:G,isBridging:M,isErc20Flow:Z,totalPriceInUsd:he,totalPriceInNativeCurrency:pe,gasPriceInUsd:ye,gasPriceInNativeCurrency:me,chainId:q.id,chainName:q.name}):
16
16
  /*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(So,{}),/*#__PURE__*/e.jsx("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_AWAITING_TRANSFER_FROM_EXTERNAL_SOLANA_WALLET_SCREEN]:()=>{let{closePrivyModal:t,createAnalyticsEvent:n}=i.usePrivyInternal(),{navigate:a,setModalData:o,app:l,data:u}=c.usePrivyModal(),{wallets:h}=d.useSolanaWallets(),p=d.usePlugins(),[m,g]=r.useState(0n),[f,w]=r.useState(null),[v,C]=r.useState(!1),[x,E]=r.useState(!1),S=r.useRef(!1);if(!u?.funding||"solana"!==u.funding.chainType)throw Error("Invalid funding data");let{address:T,amount:A,cluster:b,connectedWalletAddress:_}=u.funding,I=c.getSolanaRpcEndpointForCluster(b),{tokenPrice:P}=Po("solana"),{fundingAmountInBaseUnit:j,totalPriceInUsd:k,totalPriceInNativeCurrency:N,feePriceInNativeCurrency:M,feePriceInUsd:R}=Ro({amount:A,fee:m,tokenPrice:P}),O=_?h.find((({address:e})=>e===_)):h[0],W=s.useExternalWalletListing(O?.walletClientType||"unknown"),L=W?.name||"wallet";return r.useEffect((()=>{(async()=>{if("solana"===O?.type&&O.sendTransaction&&!v&&!S.current){S.current=!0;try{let e=p(d.SOLANA_FUNDING_PLUGIN_ID);if(!e)throw new i.PrivyClientError("Unable to load solana plugin");let{connection:t,transaction:r}=await e.createTransferTransaction({from:O.address,to:T,amount:j,cluster:b}),a=await r.getEstimatedFee(t);null!=a&&g(BigInt(a)),C(!0);let o=await t.simulateTransaction(r);if(o.value.err)return o.value.logs?.find((e=>/insufficient (lamports|funds)/gi.test(e)))?void w(new i.PrivyClientError(`Wallet ${s.formatWalletAddress(O.address,void 0,void 0,"solana")} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE)):(console.error("Transaction failed:",o.value.err),void w(new i.PrivyClientError("Something went wrong",void 0,i.PrivyErrorCode.TRANSACTION_FAILURE)));let l=await O.sendTransaction(r,t);n({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:l,rpcEndpoint:I,address:O.address,value:y.formatUnits(j,9),chainType:"solana",clusterName:b.name,token:"SOL",destinationAddress:T,destinationValue:y.formatUnits(j,9),destinationChainType:"solana",destinationClusterName:b.name,destinationToken:"SOL"}}),C(!1),E(!0)}catch(e){if(console.error(e),C(!1),/user rejected the request/gi.test(e.message||""))return void w(new i.PrivyClientError("Transaction was rejected by the user",void 0,i.PrivyErrorCode.TRANSACTION_FAILURE));w(new i.PrivyClientError("Something went wrong",void 0,i.PrivyErrorCode.TRANSACTION_FAILURE))}}})().catch(console.error).finally((()=>S.current=!1))}),[]),r.useEffect((()=>{if(!f)return;let e={error:f,previousScreen:c.ModalScreen.FUNDING_TRANSFER_FROM_WALLET_SCREEN};o({funding:u?.funding,sendTransaction:u?.sendTransaction,errorModalData:e}),a(c.ModalScreen.ERROR_SCREEN,!1)}),[f]),r.useEffect((()=>{if(!x)return;let e=setTimeout(t,c.DEFAULT_SUCCESS_SCREEN_EXTRA_LONG_DURATION_MS);return()=>clearTimeout(e)}),[x]),x?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(De.default,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(Zn,{title:"Success!",description:`You’ve successfully added ${A} SOL to your ${l.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]}):O&&v?/*#__PURE__*/e.jsx(ks,{wallet:O,displayName:L,addressToFund:T,isBridging:!1,isErc20Flow:!1,totalPriceInUsd:k,totalPriceInNativeCurrency:N,gasPriceInUsd:R,gasPriceInNativeCurrency:M,chainId:"solana",chainName:b.name}):
17
17
  /*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(So,{}),/*#__PURE__*/e.jsx("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_AWAITING_EVM_TO_SOL_BRIDGING_SCREEN]:()=>{let{rpcConfig:t,appId:n,closePrivyModal:a,createAnalyticsEvent:o}=i.usePrivyInternal(),{navigate:l,setModalData:u,app:h,data:p}=c.usePrivyModal(),{wallets:g}=c.useWallets(),f=d.usePlugins(),[w,v]=r.useState(null),[C,x]=r.useState(null),[E,S]=r.useState([]),[T,A]=r.useState(0),[b,_]=r.useState(!1),[I,P]=r.useState(!1),[j,k]=r.useState(!1),[N,M]=r.useState(!1),[R,O]=r.useState(),[W,L]=r.useState();if(!p?.funding||"solana"!==p.funding.chainType)throw Error("Invalid funding data");let{address:U,cluster:F,connectedWalletAddress:D}=p.funding,[B,H]=r.useState(p.funding.amount),z=D?g.find((({address:e})=>e===D)):g[0],q=s.useExternalWalletListing(z?.walletClientType||"unknown"),V=q?.name||"wallet",[G,$]=r.useState(null);r.useEffect((()=>{(async()=>{if(!z)return;let e=await z.getEthereumProvider();$(y.createWalletClient({account:z.address,transport:y.custom(e)}).extend(y.publicActions))})().catch(console.error)}),[z]);let[K,Y]=r.useState(0n),Z=No(K);r.useEffect((()=>{let e=f(d.SOLANA_FUNDING_PLUGIN_ID);e?e.getBalance({address:U,cluster:F}).then((e=>Y(BigInt(e)))):console.warn("Unable to load solana plugin, skipping balance")}),[]);let[X,Q]=r.useState(),{tokenPrice:J}=Po("solana"),{fundingAmountInBaseUnit:ee,fundingAmountInUsd:te}=Ro({amount:B,fee:0n,tokenPrice:J});if(r.useEffect((()=>{(async()=>{if(!G||!z)return;let e=["testnet","devnet"].includes(F.name);e&&console.warn("Solana testnets are not supported for bridging");let r=c.addToDefaultChains(h.chains).filter((({testnet:t})=>!!t===e)),a=(await Bo({chains:r,address:z.address,appId:n,rpcConfig:t})).filter((e=>e.balance>0n));if(a.length<1)return void v(new i.PrivyClientError(`Wallet ${s.formatWalletAddress(z.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE));a.sort(((e,t)=>Number(t.balance-e.balance)));let o=(await Promise.allSettled(a.map((async e=>({...e,quote:await to({isTestnet:!1,input:Qi({amount:ee.toString(),user:z.address,recipient:U,destinationChainId:c.RELAY_SOLANA_MAINNET_CLUSTER_CHAIN_ID,destinationCurrency:c.RELAY_SOLANA_NATIVE_CURRENCY_ID,originChainId:e.chain.id})})}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(o.length<1)return void v(new i.PrivyClientError(`Unable to fetch quotes for bridging. Wallet ${s.formatWalletAddress(z.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE));let l=o.map((({quote:e,balance:t,chain:r})=>({bridgeTx:ro(e),balance:t,chain:r}))).filter((({bridgeTx:e})=>!!e));if(l.length>1)return void S(l);let d=l.at(0);d?(P(!0),Q({data:d.bridgeTx.data,to:d.bridgeTx.to,value:d.bridgeTx.value,chain:d.chain})):v(new i.PrivyClientError(`Unable to select bridge option from quotes. Wallet ${s.formatWalletAddress(z.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE))})().catch(console.error)}),[G]),r.useEffect((()=>{(async()=>{let e,r;if(!G||!z||b||j||!X)return;_(!0);let a=y.createPublicClient({chain:X.chain,transport:y.http(m.getJsonRpcEndpointFromChain(X.chain,t,n))});try{e=await a.prepareTransactionRequest({account:z.address,to:X.to,chain:X.chain,data:X.data,value:BigInt(X.value??0)})}catch(e){console.error(e),E.length>1&&x(e.shortMessage??"Something went wrong")}if(e){_(!1),k(!0);try{await G.switchChain({id:X.chain.id})}catch(e){await G.addChain({chain:X.chain}),await G.switchChain({id:X.chain.id})}try{r=await G.sendTransaction(e)}catch(e){console.error(e),"TransactionExecutionError"===e.name&&(E.length<1?v(new i.PrivyClientError(e.shortMessage,void 0,i.PrivyErrorCode.TRANSACTION_FAILURE)):x(e.shortMessage??"Something went wrong"))}if(r)return await G.waitForTransactionReceipt({hash:r}),I?(L("pending"),void O(r)):(k(!1),M(!0),void o({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:r,address:z.address,chainId:X.chain.id,chainType:"ethereum",value:X.value?y.formatUnits(BigInt(X.value),18):void 0,token:"ETH",destination:U,destinationClusterName:"mainnet-beta",destinationChainType:"solana",destinationValue:y.formatUnits(ee,9),destinationToken:"SOL"}}));k(!1)}else _(!1)})().catch(console.error)}),[G,X]),no({transactionHash:R,wallet:z,isTestnet:!1,bridgingStatus:W,setBridgingStatus:L,onSuccess({transactionHash:e,wallet:t}){P(!1),M(!0),o({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:e,address:t.address,chainId:X?.chain.id,chainType:"ethereum",value:X?.value?y.formatUnits(BigInt(X.value),18):void 0,token:"ETH",destination:U,destinationClusterName:"mainnet-beta",destinationChainType:"solana",destinationValue:y.formatUnits(ee,9),destinationToken:"SOL"}})},onFailure({error:e}){P(!1),v(e)}}),r.useEffect((()=>{if(!w)return;let e={error:w,previousScreen:c.ModalScreen.FUNDING_TRANSFER_FROM_WALLET_SCREEN};u({funding:p?.funding,sendTransaction:p?.sendTransaction,errorModalData:e}),l(c.ModalScreen.ERROR_SCREEN,!1)}),[w]),r.useEffect((()=>{if(!N)return;let e=setTimeout(a,c.DEFAULT_SUCCESS_SCREEN_EXTRA_LONG_DURATION_MS);return()=>clearTimeout(e)}),[N]),N/*#__PURE__*/)return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(De.default,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(Zn,{title:"Success!",description:`You’ve successfully added ${B} SOL to your ${h.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let re=E[T];return E.length>1&&re?/*#__PURE__*/e.jsx(js,{displayName:V,configuredFundingChain:F,formattedBalance:Z,fundingAmount:B,fundingCurrency:"SOL",fundingAmountInUsd:te,options:E,selectedOption:re,isPreparing:b,isSubmitting:j,addressToFund:U,fundingWalletAddress:z?.address||"",errorMessage:C,onSubmit:()=>{p.funding?.amount!==B?async function(){if(z&&re)try{let e=await to({isTestnet:!1,input:Qi({amount:ee.toString(),user:z.address,recipient:U,destinationChainId:c.RELAY_SOLANA_MAINNET_CLUSTER_CHAIN_ID,destinationCurrency:c.RELAY_SOLANA_NATIVE_CURRENCY_ID,originChainId:re.chain.id})}),t=ro(e);if(!t)throw Error("Invalid transaction request");P(!0),Q({data:t.data,to:t.to,value:t.value,chain:re.chain})}catch(e){console.error(e),v(new i.PrivyClientError("Unable to fetch quotes for bridging",e,i.PrivyErrorCode.INSUFFICIENT_BALANCE))}}().catch(console.error):Q({to:re.bridgeTx.to,data:re.bridgeTx.data,value:re.bridgeTx.value,chain:re.chain})},onSelect:e=>{e!==T&&(x(null),A(e))},onAmountChange:H}):j&&z?/*#__PURE__*/e.jsx(ks,{wallet:z,displayName:V,addressToFund:U,isBridging:I,isErc20Flow:!1,chainId:"solana",chainName:F.name,totalPriceInUsd:void 0,totalPriceInNativeCurrency:void 0,gasPriceInUsd:void 0,gasPriceInNativeCurrency:void 0}):
18
18
  /*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(So,{}),/*#__PURE__*/e.jsx("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_AWAITING_SOL_TO_EVM_BRIDGING_SCREEN]:function(){let{closePrivyModal:t,createAnalyticsEvent:n}=i.usePrivyInternal(),{navigate:a,setModalData:o,app:l,data:u}=c.usePrivyModal(),{wallets:h}=d.useSolanaWallets(),p=r.useRef(!1),m=d.usePlugins(),[g,f]=r.useState(!1),[w,v]=r.useState(!1),[C,x]=r.useState(null),[E,S]=r.useState(),[T,A]=r.useState();if(!u?.funding||"ethereum"!==u.funding.chainType)throw Error("Invalid funding data");let{amount:b,connectedWalletAddress:_,chain:I,cluster:P,isUSDC:j}=u.funding,k=u.funding.address,N=u.funding.erc20Address,M=u.funding.isUSDC?"USDC":I.nativeCurrency.symbol,R=P??{name:"mainnet-beta"},O=_?h.find((({address:e})=>e===_)):h[0],W=s.useExternalWalletListing(O?.walletClientType||"unknown"),L=W?.name||"wallet";return r.useEffect((()=>{(async function(){if(!O||!I||p.current)return;let e=m(d.SOLANA_FUNDING_PLUGIN_ID);if(!e)return void x(new i.PrivyClientError("Unable to solana plugin"));p.current=!0,I?.testnet&&console.warn("Solana testnets are not supported for bridging");let t=j?1e6*parseFloat(b):y.parseEther(b),r=await to({isTestnet:!!I.testnet,input:Qi({amount:t.toString(),user:O.address,recipient:k,destinationChainId:I.id,originChainId:c.RELAY_SOLANA_MAINNET_CLUSTER_CHAIN_ID,originCurrency:j?c.RELAY_SOLANA_USDC_TOKEN_ID:c.RELAY_SOLANA_NATIVE_CURRENCY_ID,destinationCurrency:j?N:void 0})}).catch(console.error);if(!r)return void x(new i.PrivyClientError(`Unable to fetch quotes for bridging. Wallet ${s.formatSolanaWalletAddress(O.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE));let n=await e.createBridgeTransactionFromRelayQuote({quote:r,from:O.address,cluster:R});if(n)try{f(!0);let{connection:e,transaction:t}=n,a=await e.simulateTransaction(t);if(a.value.err)return a.value.logs?.find((e=>/insufficient (lamports|funds)/gi.test(e)))?void x(new i.PrivyClientError(`Wallet ${s.formatSolanaWalletAddress(O?.address)} does not have enough funds. ${r.details.currencyIn.amountFormatted} ${M} are needed to complete the transaction.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE)):(console.error("Transaction failed:",a.value.err),void x(new i.PrivyClientError("Something went wrong",void 0,i.PrivyErrorCode.TRANSACTION_FAILURE)));let o=await O.sendTransaction(t,e),l=await e.confirmTransaction(o);if(l.value.err)return console.error("Transaction failed:",l.value.err),void x(new i.PrivyClientError("Something went wrong",void 0,i.PrivyErrorCode.TRANSACTION_FAILURE));S(o),A("pending")}catch(e){if(console.error(e),/user rejected the request/gi.test(e.message||""))return void x(new i.PrivyClientError("Transaction was rejected by the user",void 0,i.PrivyErrorCode.TRANSACTION_FAILURE));x(new i.PrivyClientError("Something went wrong",void 0,i.PrivyErrorCode.TRANSACTION_FAILURE))}else x(new i.PrivyClientError(`Unable to select bridge option from quotes. Wallet ${s.formatSolanaWalletAddress(O.address)} does not have enough funds.`,void 0,i.PrivyErrorCode.INSUFFICIENT_BALANCE))})().catch(console.error)}),[]),no({transactionHash:E,wallet:O,isTestnet:!1,bridgingStatus:T,setBridgingStatus:A,onSuccess({transactionHash:e,wallet:t}){f(!1),v(!0),n({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:e,address:t.address,chainType:"solana",clusterName:R.name,token:"SOL",destinationAddress:k,destinationChainId:I.id,destinationChainType:"ethereum",destinationValue:b,destinationToken:j?"USDC":"ETH"}})},onFailure({error:e}){f(!1),x(e)}}),r.useEffect((()=>{if(!w)return;let e=setTimeout(t,c.DEFAULT_SUCCESS_SCREEN_EXTRA_LONG_DURATION_MS);return()=>clearTimeout(e)}),[w]),r.useEffect((()=>{if(!C)return;let e={error:C,previousScreen:c.ModalScreen.FUNDING_TRANSFER_FROM_WALLET_SCREEN};o({funding:u?.funding,sendTransaction:u?.sendTransaction,errorModalData:e}),a(c.ModalScreen.ERROR_SCREEN,!1)}),[C]),w?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(De.default,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(Zn,{title:"Success!",description:`You’ve successfully added ${b} ${M} to your ${l.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]}):g&&O?/*#__PURE__*/e.jsx(ks,{wallet:O,displayName:L,addressToFund:k,isBridging:g,isErc20Flow:!1,chainId:I.id,chainName:I.name,totalPriceInUsd:void 0,totalPriceInNativeCurrency:void 0,gasPriceInUsd:void 0,gasPriceInNativeCurrency:void 0}):
19
19
  /*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),/*#__PURE__*/e.jsx(So,{}),/*#__PURE__*/e.jsx("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.FUNDING_MANUAL_TRANSFER_SCREEN]:()=>{let{wallets:t}=c.useWallets(),{wallets:n}=d.useSolanaWallets(),{data:a,setModalData:o,navigate:l,lastScreen:u}=c.usePrivyModal(),{rpcConfig:h,appId:p,createAnalyticsEvent:m,closePrivyModal:g}=i.usePrivyInternal(),f=c.useAppConfig(),[w,v]=r.useState(void 0),[C,x]=r.useState(!1),E=d.usePlugins(),S=a?.funding,{reloadBalance:T}=s.useWalletBalance({rpcConfig:h,appId:p,address:"ethereum"===S.chainType?S.address:void 0,chain:"ethereum"===S.chainType?S.chain:void 0}),A="solana"===S.chainType,b=A?"SOL":S.erc20Address?S.erc20ContractInfo?.symbol:S.chain.nativeCurrency.symbol,_=A?n.find((({address:e})=>e===S.address)):t.find((({address:e})=>s.formatWalletAddress(e)===s.formatWalletAddress(S.address)));if(!S)return o({errorModalData:{error:Error("Couldn't find funding config"),previousScreen:u||c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN},funding:a?.funding,sendTransaction:a?.sendTransaction}),l(c.ModalScreen.ERROR_SCREEN),/*#__PURE__*/e.jsx(e.Fragment,{});r.useEffect((()=>{let e=A?async function(){if("solana"!==S.chainType)return;let e=E(d.SOLANA_FUNDING_PLUGIN_ID);e?e.getBalance({address:S.address,cluster:S.cluster}).then((e=>{let t=BigInt(e);w&&t>w&&(x(!0),m({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"manual",status:"success",chainType:"solana",address:_?.address,value:y.formatUnits(t-w,9),token:"SOL"}})),v(t)})):console.warn("Unable to load solana plugin, skipping balance")}:async function(){"ethereum"===S.chainType&&(async()=>{if(!S.erc20Address)return await T()??BigInt(0);{let{balance:e}=await s.getErc20Balance({chain:S.chain,address:S.address,erc20Address:S.erc20Address,rpcConfig:h,appId:p});return e}})().then((e=>{w&&e>w&&(x(!0),m({eventName:d.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"manual",status:"success",chainType:"ethereum",address:_?.address,chainId:S.chain.id,value:y.formatUnits(e-w,S.erc20ContractInfo?.decimals??18),token:S.erc20ContractInfo?.symbol??S.erc20Address??"ETH"}})),v(e)})).catch((()=>v(void 0)))},t=setInterval(e,2e3);return e(),()=>clearInterval(t)}),[w]);let I=r.useMemo((()=>void 0!==w&&w>=parseFloat(S.amount)),[w,S.amount]),P=r.useMemo((()=>null==w?"":S.isUSDC?K.formatTokenAmount({amount:w,decimals:6}):A?No(w,3,!0,!0):null!=S.erc20ContractInfo?.decimals?K.formatTokenAmount({amount:w,decimals:S.erc20ContractInfo.decimals}):K.formatWeiAmount({wei:w})),[w,A,S]),j="ethereum"===S.chainType?S.chain.name:rl[S.cluster.name],k=r.useMemo((()=>""===S.uiConfig?.receiveFundsTitle?null:/*#__PURE__*/e.jsx(s.Title,{children:S.uiConfig?.receiveFundsTitle??`Receive ${S.amount} ${b??""}`.trim()})),[S.uiConfig?.receiveFundsTitle,S.amount,b]),N=r.useMemo((()=>""===S.uiConfig?.receiveFundsSubtitle?null:/*#__PURE__*/e.jsx(s.Subtitle,{children:S.uiConfig?.receiveFundsSubtitle??`Scan this code or copy your wallet address to receive funds on ${j}.`})),[S.uiConfig?.receiveFundsSubtitle,j]);/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Eo,{}),k,N,/*#__PURE__*/e.jsxs(s.FlexContainer,{style:{gap:"1rem",margin:k||N?"1rem 0":"0"},children:[/*#__PURE__*/e.jsx(s.QrCode,{url:`${S.chainType}:${S.address}`,size:200,squareLogoElement:tl}),/*#__PURE__*/e.jsxs(Hs,{theme:f.appearance.palette.colorScheme,children:["Make sure to send funds on ",j,"."]}),/*#__PURE__*/e.jsx(s.WalletInfoCard,{title:"Your wallet",errMsg:void 0,showIcon:!0,isLoading:!S||void 0===w,isPulsing:!I,balance:`${P} ${b}`,address:S.address,statusColor:I?"green":"gray"}),C&&/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>g({shouldCallAuthOnSuccess:!1,isSuccess:!0}),children:"Continue"})]}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_PASSWORD_UPDATE_SPLASH_SCREEN]:()=>{let{closePrivyModal:t}=i.usePrivyInternal(),{data:r,setModalData:n,navigate:a,onUserCloseViaDialogOrKeybindRef:o}=c.usePrivyModal(),{onSuccess:l,onFailure:d}=r.setWalletPassword,u=()=>{d(new i.PrivyEmbeddedWalletError("Exited before password was added to wallet")),t({shouldCallAuthOnSuccess:!1})};return o.current=u,/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:u}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsxs(s.RelativeContainer,{children:[/*#__PURE__*/e.jsx(Qe.default,{stroke:"var(--privy-color-accent)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(s.Circle,{style:{width:24,height:24,position:"absolute",bottom:0,right:0},children:/*#__PURE__*/e.jsx(Je.default,{width:"12px",height:"12px",fill:"white"})})]}),/*#__PURE__*/e.jsxs(Zn,{title:"Secure Your Account",children:["Please set a password to secure your account.",/*#__PURE__*/e.jsx("p",{children:"Losing access to this password and this device will make your account inaccessible."})]})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{n({createWallet:{onFailure:d,onSuccess:l,callAuthOnSuccessOnClose:!1,addPasswordToExistingWallet:!0}}),a(c.ModalScreen.EMBEDDED_WALLET_PASSWORD_UPDATE_SCREEN)},children:"Add password"}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.EMBEDDED_WALLET_PASSWORD_UPDATE_SCREEN]:()=>{let[t,n]=r.useState(null),[a,o]=r.useState(!1),[s,l]=r.useState(null),[d,u]=r.useState(""),{authenticated:h,getAccessToken:p,user:y}=c.usePrivyContext(),{walletProxy:m,refreshSessionAndUser:g,closePrivyModal:f,createAnalyticsEvent:w}=i.usePrivyInternal(),{app:v,navigate:C,data:x,onUserCloseViaDialogOrKeybindRef:E}=c.usePrivyModal(),{onSuccess:S,onFailure:T}=x.createWallet,A=c.getPrivyPrimaryWallet(y),b="user-passcode"===t?.recoveryMethod,_="user-passcode"===A?.recoveryMethod;r.useEffect((()=>{h||(C(c.ModalScreen.LANDING),T(new i.PrivyUnauthenticatedError("User must be authenticated before setting a password on a Privy wallet")))}),[h]);let I=()=>s?(T(s),void f({shouldCallAuthOnSuccess:!1})):b?(S(t),void f({shouldCallAuthOnSuccess:!1})):(T(new i.PrivyEmbeddedWalletError("Exited before password was added to wallet")),void f({shouldCallAuthOnSuccess:!1}));E.current=I;/*#__PURE__*/return e.jsx(Zi,{appName:v?.name||"privy",config:{initiatedBy:"user",onCancel:I},error:s?"An error has occurred, please try again.":void 0,buttonLoading:a,buttonHideAnimations:!1,password:d,isResettingPassword:_,onPasswordGenerate:()=>u(Di()),onPasswordChange:u,onSubmit:async()=>{b?(S(t),f({shouldCallAuthOnSuccess:!1})):(o(!0),l(null),await(async()=>{let e=await p();if(e&&A?.address&&d&&m)try{w({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:A.address,existingRecoveryMethod:A.recoveryMethod,targetRecoveryMethod:"user-passcode",isResettingPassword:_}});let{entropyId:t,entropyIdVerifier:r}=c.getEntropyDetailsFromAccount(A);if(!(await m.setRecovery({accessToken:e,entropyId:t,entropyIdVerifier:r,recoveryPassword:d,recoveryMethod:"user-passcode"})).entropyId)return l(new i.PrivyEmbeddedWalletError("Error setting password on privy wallet")),void w({eventName:"embedded_wallet_set_recovery_failed",payload:{walletAddress:A.address,existingRecoveryMethod:A.recoveryMethod,targetRecoveryMethod:"user-passcode",isResettingPassword:_,reason:"error setting password"}});let a=await g(),o=c.getPrivyPrimaryWallet(a);if(!o)return l(new i.PrivyEmbeddedWalletError("Error setting password on privy wallet")),void w({eventName:"embedded_wallet_set_recovery_failed",payload:{walletAddress:A.address,existingRecoveryMethod:A.recoveryMethod,targetRecoveryMethod:"user-passcode",isResettingPassword:_,reason:"wallet disconnected"}});n(o),w({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:A.address,existingRecoveryMethod:A.recoveryMethod,targetRecoveryMethod:"user-passcode",isResettingPassword:_}})}catch(e){console.warn(e),l(e instanceof Error?e:Error("Error setting password on privy wallet")),w({eventName:"embedded_wallet_set_password_failed",payload:{walletAddress:A.address,reason:e}})}})(),o(!1))},onClose:I})},[c.ModalScreen.EMBEDDED_WALLET_PASSWORD_CREATE_SCREEN]:()=>{let{app:t,navigate:n,data:a,onUserCloseViaDialogOrKeybindRef:o}=c.usePrivyModal(),[l,d]=r.useState(""),[u,h]=r.useState(!1),[p,y]=r.useState(),[m,g]=r.useState(null),{authenticated:f,user:w}=c.usePrivyContext(),{closePrivyModal:v,isNewUserThisSession:C,initializeWalletProxy:x}=i.usePrivyInternal(),{onSuccess:E,onFailure:S,callAuthOnSuccessOnClose:T}=a.createWallet,{createWallet:A}=ii(),[b,_]=r.useState(null),I=new s.RunEffectOnce((async()=>{try{let e=await A({recoveryPassword:p,user:w});if(!e)return;_(e),C?n(c.ModalScreen.EMBEDDED_WALLET_CREATED_SCREEN):(E(e),v({shouldCallAuthOnSuccess:T}))}catch(e){d(e.message)}}));r.useEffect((()=>{m||x(3e4).then((e=>g(e)))}),[m]),r.useEffect((()=>{if(!f||!w)return n(c.ModalScreen.LANDING),void S(Error("User must be authenticated before creating a Privy wallet"))}),[f]),o.current=()=>null;/*#__PURE__*/return e.jsx(Zi,{config:{initiatedBy:"automatic"},appName:t?.name||"privy",loading:!m,buttonLoading:u,buttonHideAnimations:!b&&u,isResettingPassword:!1,error:l,password:p||"",onClose:()=>{b&&"user-passcode"!==b?.recoveryMethod?(S(new i.PrivyEmbeddedWalletError("User created a wallet but failed to set a password for it")),v({shouldCallAuthOnSuccess:!1})):b?(E(b),v({shouldCallAuthOnSuccess:T})):(S(new i.PrivyEmbeddedWalletError("User wallet creation failed")),v({shouldCallAuthOnSuccess:!1}))},onPasswordChange:y,onPasswordGenerate:()=>y(Di()),onSubmit:async()=>(h(!0),I.execute().then((()=>new Promise((e=>setTimeout(e,250))))).finally((()=>h(!1))))})},[c.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN]:()=>{let{user:t,enrollInMfa:n}=c.usePrivyContext(),[a,o]=r.useState(null),{unenrollWithSms:l,unenrollWithTotp:d,unenrollWithPasskey:u}=rc(),{app:h,ready:p,data:y,onUserCloseViaDialogOrKeybindRef:m}=c.usePrivyModal(),{closePrivyModal:g}=i.usePrivyInternal(),{promptMfa:f}=tc(),{initEnrollmentWithTotp:w}=rc(),[v,C]=r.useState(!1),[x,E]=r.useState(null),[S,T]=r.useState(null),A=()=>{g({shouldCallAuthOnSuccess:!0}),n(!1),setTimeout((()=>{o(null),E(null)}),500)},{initEnrollmentWithPasskey:b,submitEnrollmentWithPasskey:_}=rc(),[I,P]=r.useState(!1),[j,k]=r.useState(null);m.current=A;let N=t?.mfaMethods.includes("sms"),M=!!t?.phone,R=t?.mfaMethods.includes("totp"),O=t?.mfaMethods.includes("passkey"),W=N||R||O,L=t?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function U(){o(null),E(null)}if(r.useEffect((()=>{W&&C(!0)}),[W]),!p||!t||!h/*#__PURE__*/)return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:A},"header"),/*#__PURE__*/e.jsx(An,{children:/*#__PURE__*/e.jsx(nc,{})}),/*#__PURE__*/e.jsx(In,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("sms"===a)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:U,onClose:A},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(Ie.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Remove SMS verification?"}),/*#__PURE__*/e.jsxs(_n,{children:["MFA adds an extra layer of security to your ",h?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(Nn,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{warn:!0,onClick:async function(){o(null);try{await l()}catch(e){o(null)}},children:"Remove SMS for MFA"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("totp"===a)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:U,onClose:A},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(Ie.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Remove Authenticator App verification?"}),/*#__PURE__*/e.jsxs(_n,{children:["MFA adds an extra layer of security to your ",h?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(Nn,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{warn:!0,onClick:async function(){o(null);try{await d()}catch(e){o(null)}},children:"Remove Authenticator App for MFA"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("passkey"===a){let t=y?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:U,onClose:A},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(Ie.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/e.jsx(_n,{children:t?"Removing your passkey will remove as both a verification method and a login method.":"Removing your passkey will remove as a verification method."}),/*#__PURE__*/e.jsx(Nn,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{warn:!0,onClick:async function(){o(null);try{await u({removeForLogin:y?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){o(null)}},children:"Yes, remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})}if(0===y.mfaEnrollmentFlow.mfaMethods.length&&!W)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:A},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(dt.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Add more security"}),/*#__PURE__*/e.jsxs(_n,{children:[h?.name," does not have any verification methods enabled."]}),/*#__PURE__*/e.jsx(Nn,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:A,children:"Close"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});let F=!W&&!v;return F?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:A},"header"),/*#__PURE__*/e.jsx(Bn,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(dt.default,{})}),/*#__PURE__*/e.jsx(bn,{children:"Transaction Protection"}),/*#__PURE__*/e.jsx(_n,{children:"Set up transaction protection to add an extra layer of security to your account"}),/*#__PURE__*/e.jsxs(Pn,{children:[/*#__PURE__*/e.jsxs(kn,{children:[/*#__PURE__*/e.jsx(jn,{children:/*#__PURE__*/e.jsx(ct.default,{})}),"Enable 2-Step verification for your ",h?.name," wallet."]}),/*#__PURE__*/e.jsxs(kn,{children:[/*#__PURE__*/e.jsx(jn,{children:/*#__PURE__*/e.jsx(ut.default,{})}),"You'll be prompted to authenticate to complete transactions."]})]}),/*#__PURE__*/e.jsxs(Nn,{children:[/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>C(!0),children:"Continue"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:A,children:"Not now"})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):"sms"===x?/*#__PURE__*/e.jsx(Tc,{appName:h?.name||"Privy",onComplete:A,onReset:U,onClose:A}):"totp"===x&&S?/*#__PURE__*/e.jsx(bc,{onComplete:A,onClose:A,onReset:U,totpInfo:{...S,appName:h?.name||"Privy"}}):"passkey"===x?/*#__PURE__*/e.jsx(sc,{appName:h?.name||"Privy",onComplete:A,onReset:U,onClose:A}):/*#__PURE__*/e.jsx(ic,{showIntro:F,userMfaMethods:t.mfaMethods,appMfaMethods:h.mfa.methods,userHasAuthSms:M,onBackToIntro:function(){C(!1)},handleSelectMethod:async function(e){return await f().catch(k),"totp"===e?(E(e),T(null),void w().then((e=>{T(e)})).catch((()=>{T(null),U()}))):"passkey"===e&&1===L.length?await async function(){P(!0);try{await b(),await _({credentialIds:L},{removeForLogin:y?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){k(e)}finally{P(!1)}}():void E(e)},isTotpLoading:"totp"===x&&!S,isPasskeyLoading:I,error:j,onClose:A,setRemovingMfaMethod:async e=>{await f().catch(k),o(e)}})},[c.ModalScreen.CAPTCHA_SCREEN]:()=>{let{lastScreen:t,currentScreen:n,data:a,navigateBack:i,navigate:o,setModalData:l}=c.usePrivyModal(),{status:d,token:u,waitForResult:h,reset:p,execute:y}=s.useCaptcha(),m=r.useRef([]),g=e=>{m.current=[e,...m.current]},[f,w]=r.useState(!0);r.useEffect((()=>(g(setTimeout(w,1e3,!1)),()=>{m.current.forEach((e=>clearTimeout(e))),m.current=[]})),[]);let[v,C]=r.useState(""),[x,E]=r.useState("Checking that you are a human..."),[S,T]=r.useState(/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{},disabled:!0,children:"Continue"})),[A,b]=r.useState(!1),[_,I]=r.useState(3),P=a?.captchaModalData,j=async e=>{try{await(P?.callback(e)),P?.onSuccessNavigateTo&&o(P?.onSuccessNavigateTo,!1)}catch(e){if(e instanceof s.CaptchaError)return;l({errorModalData:{error:e,previousScreen:t||c.ModalScreen.LANDING}}),o(P?.onErrorNavigateTo||c.ModalScreen.ERROR_SCREEN,!1)}};r.useEffect((()=>{"success"===d?g(setTimeout((async()=>{let e=await h();!e||P?.userIntentRequired||j(e)}),1e3)):"ready"===d&&g(setTimeout((()=>{"ready"===d&&y()}),500))}),[d]),r.useEffect((()=>{if(!f)switch(d){case"success":C("Success!"),E("CAPTCHA passed successfully."),T(/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{b(!0),j(u)},disabled:!P?.userIntentRequired,loading:A,children:P?.userIntentRequired?"Continue":"Continuing..."}));break;case"loading":C(""),E("Checking that you are a human..."),T(/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>{},disabled:!0,children:"Continue"}));break;case"error":C("Something went wrong"),_<=0?(E("If you use an adblocker or VPN, try disabling and re-attempting."),T(null)):(E("You did not pass CAPTCHA. Please try again."),T(/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:k,children:"Retry"})))}}),[d,f,A]);let k=async()=>{if(_<=0)return;I((e=>e-1)),p(),y();let e=await h();!e||P?.userIntentRequired||j(e)};/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t&&n!==t?i:void 0}),/*#__PURE__*/e.jsxs(pa,{children:["success"===d?/*#__PURE__*/e.jsx(Ue.default,{fill:"var(--privy-color-success)",width:"64px",height:"64px"}):"error"===d?/*#__PURE__*/e.jsx(Fe.default,{fill:"var(--privy-color-error)",width:"64px",height:"64px"}):/*#__PURE__*/e.jsx(ua,{}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[v?/*#__PURE__*/e.jsx("h3",{children:v}):null,/*#__PURE__*/e.jsx("p",{children:x})]}),S]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.ERROR_SCREEN]:()=>{let{navigate:t,navigateBack:r,data:n,lastScreen:a,currentScreen:i}=c.usePrivyModal(),o=n?.errorModalData?.previousScreen||(a===i?void 0:a);/*#__PURE__*/return e.jsx(io,{error:n?.errorModalData?.error||Error(),backFn:()=>o?t(o,!1):r(),onClick:()=>t(o||c.ModalScreen.LANDING,!1)})},[c.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE]:()=>{let{closePrivyModal:t}=i.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(dl,{children:/*#__PURE__*/e.jsx(Me.default,{style:{width:32,height:32}})}),/*#__PURE__*/e.jsx(Yn,{title:"Could not log in with provider",description:"It looks like you're using an in-app browser. To log in, please try again using an external browser.",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center"}}),/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>t(),children:"Close"})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})},[c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN]:()=>{let{user:t,logout:r}=c.usePrivyContext(),{app:n,onUserCloseViaDialogOrKeybindRef:a,setModalData:o,navigate:l}=c.usePrivyModal(),{acceptTerms:d,closePrivyModal:u,createAnalyticsEvent:h}=i.usePrivyInternal(),p=e=>{e?.preventDefault(),u({shouldCallAuthOnSuccess:!1}),r()};a.current=p;/*#__PURE__*/return e.jsx(zn,{termsAndConditionsUrl:n?.legal.termsAndConditionsUrl,privacyPolicyUrl:n?.legal.privacyPolicyUrl,onAccept:async e=>{e.preventDefault(),await d(),t&&s.shouldProceedtoEmbeddedWalletCreationFlow(t,n.embeddedWallets)?(o({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),h({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"AffirmativeConsentScreen"}}),r()},callAuthOnSuccessOnClose:!0}}),l(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)):u()},onDecline:p})},[c.ModalScreen.TELEGRAM_AUTH_SCREEN]:()=>{let{authenticated:t,logout:n,ready:a,user:o}=c.usePrivyContext(),{app:l,setModalData:d,navigate:u,resetNavigation:h,data:p}=c.usePrivyModal(),{initLoginWithTelegram:y,loginWithTelegram:m,updateWallets:g,setReadyToTrue:f,closePrivyModal:w,createAnalyticsEvent:v,getAuthMeta:C}=i.usePrivyInternal(),[x,E]=r.useState(!1),[S,T]=r.useState(void 0),A=s.useCaptcha();async function b(){try{let e=await async function(){let e;if(!t){if(A.enabled&&"error"===A.status)throw new s.CaptchaError(A.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);return A.enabled&&"success"!==A.status&&(A.execute(),e=await A.waitForResult()),e}}();await m({captchaToken:e}),E(!0),f(!0)}catch(e){if(e?.privyErrorCode===i.PrivyErrorCode.ALLOWLIST_REJECTED)return T(void 0),h(),void u(c.ModalScreen.ALLOWLIST_REJECTION_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new i.PrivyUserLimitReachedError(e).toString()),T(void 0),h(),void u(c.ModalScreen.USER_LIMIT_REACHED_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.USER_DOES_NOT_EXIST)return T(void 0),h(),void u(c.ModalScreen.ACCOUNT_NOT_FOUND_SCREEN);if(e?.privyErrorCode===i.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return T(void 0),h(),d({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,telegramAuthResult:C()?.telegramAuthResult,telegramWebAppData:C()?.telegramWebAppData,displayName:e.data?.data?.account?.displayName,linkMethod:"telegram",embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress}}),void u(c.ModalScreen.LINK_CONFLICT_SCREEN);let{retryable:t,detail:r}=Xt(e);T({retryable:t,detail:r,message:"Authentication failed"})}}r.useEffect((()=>{b()}),[]),r.useEffect((()=>{if(!(a&&t&&x&&o))return;if(l?.legal.requireUsersAcceptTerms&&!o.hasAcceptedTerms){let e=setTimeout((()=>{u(c.ModalScreen.AFFIRMATIVE_CONSENT_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(o,l.embeddedWallets)){let e=setTimeout((()=>{d({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),v({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:"telegram",screen:"TelegramAuthScreen"}}),n()},callAuthOnSuccessOnClose:!0}}),u(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)}),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}g();let e=setTimeout((()=>w({shouldCallAuthOnSuccess:!0,isSuccess:!0})),c.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}),[a,t,x,o]);let _=x?"Successfully connected with Telegram":S?S.message:"Verifying connection to Telegram",I="";return I=x?"You’re good to go!":S?S.detail:"Just a few moments more",/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(Ju,{children:[/*#__PURE__*/e.jsx(Yr,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:x,fail:!!S}),/*#__PURE__*/e.jsx(Bl,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(s.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:_}),/*#__PURE__*/e.jsx("p",{children:I})]}),S&&S?.retryable?/*#__PURE__*/e.jsx(s.SoftCtaButton,{onClick:async()=>{try{T(void 0),p?.telegramAuthModalData?.seamlessAuth||await y(void 0,p?.login?.disableSignup),await b()}catch(e){let{retryable:t,detail:r}=Xt(e);T({retryable:t,detail:r,message:"Authentication failed"})}},disabled:!x&&!S?.retryable,children:"Retry"}):null]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},[c.ModalScreen.LINK_CONFLICT_SCREEN]:()=>{let{initiateAccountTransfer:t,closePrivyModal:n}=i.usePrivyInternal(),{data:a,navigate:o,lastScreen:s,setModalData:l}=c.usePrivyModal(),[d,u]=r.useState(void 0),[h,p]=r.useState(!1),[y,m]=r.useState(!1),g=async()=>{try{if(!a?.accountTransfer?.nonce||!a?.accountTransfer?.account)throw Error("missing account transfer inputs");m(!0),await t({nonce:a?.accountTransfer?.nonce,account:a?.accountTransfer?.account,accountType:a?.accountTransfer?.linkMethod,externalWalletMetadata:a?.accountTransfer?.externalWalletMetadata,telegramWebAppData:a?.accountTransfer?.telegramWebAppData,telegramAuthResult:a?.accountTransfer?.telegramAuthResult,farcasterEmbeddedAddress:a?.accountTransfer?.farcasterEmbeddedAddress,oAuthUserInfo:a?.accountTransfer?.oAuthUserInfo}),p(!0),m(!1),setTimeout(n,1e3)}catch(e){l({errorModalData:{error:e,previousScreen:s||c.ModalScreen.LINK_CONFLICT_SCREEN}}),o(c.ModalScreen.ERROR_SCREEN,!0)}};return d?/*#__PURE__*/e.jsx(En,{address:d,onClose:n,onRetry:()=>u(void 0),onTransfer:g,isTransferring:y,transferSuccess:h}):/*#__PURE__*/e.jsx(Sn,{onClose:n,onInfo:()=>u(a?.accountTransfer?.embeddedWalletAddress),onContinue:()=>u(a?.accountTransfer?.embeddedWalletAddress),onTransfer:g,isTransferring:y,transferSuccess:h,data:a})}},gh=[c.ModalScreen.LANDING,c.ModalScreen.AWAITING_CONNECTION],fh=({isMfaVerifying:t,onMfaVerificationComplete:n})=>{let{ready:a,isModalOpen:i}=c.usePrivyContext(),{headless:o}=c.useAppConfig(),{ready:l,currentScreen:d}=c.usePrivyModal(),{status:u,execute:h,reset:p,enabled:y}=s.useCaptcha(),m=i&&d&&gh.includes(d)&&!o&&"ready"===u;return r.useEffect((()=>{m&&h()}),[m]),r.useEffect((()=>{!i&&y&&p()}),[i,y]),a&&l||d===c.ModalScreen.AWAITING_OAUTH_SCREEN||d===c.ModalScreen.CROSS_APP_AUTH_SCREEN||d===c.ModalScreen.TELEGRAM_AUTH_SCREEN?!d&&t?/*#__PURE__*/e.jsx(hd,{open:t,onClose:n}):d?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(an,{$if:!!t,children:/*#__PURE__*/e.jsx(mh[d],{})}),/*#__PURE__*/e.jsx(an,{$if:!t,children:/*#__PURE__*/e.jsx(hd,{open:t,onClose:n})})]}):null:/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(yh,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},wh=({isMfaVerifying:t,onMfaVerificationComplete:n})=>{let a=r.useRef(null);/*#__PURE__*/return e.jsx(xh,{style:{height:s.useElementHeight(a)},id:"privy-modal-content",children:/*#__PURE__*/e.jsx("div",{ref:a,children:/*#__PURE__*/e.jsx(fh,{isMfaVerifying:t,onMfaVerificationComplete:n})})})};const vh=({open:t})=>{let{app:n}=c.usePrivyModal(),{gracefulClosePrivyModal:a}=(()=>{let{closePrivyModal:e}=i.usePrivyInternal(),{onUserCloseViaDialogOrKeybindRef:t}=c.usePrivyModal();return{gracefulClosePrivyModal:r.useCallback((()=>{if(!t?.current)return e({shouldCallAuthOnSuccess:!1});t.current()}),[e])}})(),[o,s]=r.useState(!1);$r({onMfaRequired:()=>{n?.mfa.noPromptOnMfaRequired||s(!0)}});let l=t||o;return n.render.standalone?/*#__PURE__*/e.jsx(lh,{children:/*#__PURE__*/e.jsx(Ch,{id:"privy-modal-content",children:/*#__PURE__*/e.jsx(fh,{isMfaVerifying:o,onMfaVerificationComplete:()=>s(!1)})})}):/*#__PURE__*/e.jsx(ch,{open:l,id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>a(),children:/*#__PURE__*/e.jsx(lh,{children:/*#__PURE__*/e.jsx(wh,{isMfaVerifying:o,onMfaVerificationComplete:()=>s(!1)})})})};let Ch=/*#__PURE__*/C.styled.div.withConfig({displayName:"ContentWrapper",componentId:"sc-ca7fbebb-0"})(["display:flex;flex-direction:column;text-align:center;font-size:14px;line-height:20px;width:100%;background:var(--privy-color-background);padding:0 16px;"]),xh=/*#__PURE__*/C.styled(Ch).withConfig({displayName:"BaseModal",componentId:"sc-ca7fbebb-1"})(["transition:height 150ms ease-out;overflow-x:hidden;overflow-y:auto;scrollbar-width:none;max-height:calc(100svh - 32px);border-radius:var(--privy-border-radius-lg) var(--privy-border-radius-lg) 0 0;box-shadow:0px 0px 36px rgba(55,65,81,0.15);@media (min-width:441px){box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]);function Eh(t){let n=r.useRef(null),a=r.useRef();return r.useEffect((()=>{a.current?.remove(),a.current=function({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:n}=new URL(t);return r.async=!0,r.src=`${n}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}(t),n.current?.after(a.current)}),[t]),/*#__PURE__*/e.jsx("div",{ref:n,hidden:!0})}async function Sh(e,t,r,n,a,i=!1){let o=i,s=async s=>{if(o&&t&&t.length>0){s===(i?0:1)?a("configureMfa","onMfaRequired",{mfaMethods:t}):n.current?.reject(new Fa("missing_or_invalid_mfa","MFA verification failed, retry."));let o=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new Fa("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(o)}return await e()},l=null;for(let e=0;e<4;e++)try{l=await s(e),n.current?.resolve(void 0);break}catch(e){if("missing_or_invalid_mfa"!==e.type)throw n.current?.resolve(void 0),e;o=!0}if(null===l){let e=new Fa("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return l}var Th;let Ah=(Th=0,()=>"id-"+Th++);function bh(e){return void 0!==e.error}let _h=new class{enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let r=this.callbacks[t];if(!r)throw Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:wallets:create":case"privy:wallets:add":case"privy:wallets:import":case"privy:wallets:set-recovery":case"privy:wallets:connect":case"privy:wallets:recover":case"privy:wallets:rpc":case"privy:wallet:create":case"privy:mfa:verify":case"privy:mfa:init-enrollment":case"privy:mfa:submit-enrollment":case"privy:mfa:unenroll":case"privy:mfa:clear":case"privy:auth:unlink-passkey":case"privy:farcaster:init-signer":case"privy:farcaster:sign":case"privy:solana-wallet:create":case"privy:delegated-actions:consent":return r;default:throw Error(`invalid wallet event type ${e}`)}}constructor(){this.callbacks={}}},Ih=new Map,Ph=(e,t)=>"bigint"==typeof t?t.toString():t;function jh(e,t,r,n){let a=r.contentWindow;if(!a)throw Error("iframe not initialized");let i=((e,t)=>`${e}${JSON.stringify(t,Ph)}`)(e,t);if("privy:wallet:create"===e){let e=Ih.get(i);if(e)return e}let o=new Promise(((r,i)=>{let o=Ah();_h.enqueue(o,{resolve:r,reject:i}),a.postMessage({id:o,event:e,data:t},n)})).finally((()=>{Ih.delete(i)}));return Ih.set(i,o),o}function kh(t){let n=r.useRef(null),a=r.useRef(t.mfaMethods),i=d.useEmitPrivyEvent(),[o,l]=r.useState(!1);return r.useEffect((()=>{a.current=t.mfaMethods}),[t.mfaMethods]),r.useEffect((()=>{if(!o)return;let e=n.current;if(!e)return;function r(e){var r;e&&e.origin===t.origin&&"string"==typeof(r=e.data).event&&/^privy:.+/.test(r.event)&&function(e){switch(e.event){case"privy:iframe:ready":let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallets:create":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let r=_h.dequeue(e.event,e.id);return bh(e)?r.reject(new Fa(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallets:import":let n=_h.dequeue(e.event,e.id);return bh(e)?n.reject(new Fa(e.error.type,e.error.message)):n.resolve(e.data);case"privy:mfa:verify":let a=_h.dequeue(e.event,e.id);return bh(e)?a.reject(new Fa(e.error.type,e.error.message)):a.resolve(e.data);case"privy:mfa:init-enrollment":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let i=_h.dequeue(e.event,e.id);return bh(e)?i.reject(new Fa(e.error.type,e.error.message)):i.resolve(e.data);case"privy:farcaster:init-signer":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=_h.dequeue(e.event,e.id);return bh(e)?t.reject(new Fa(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let l={createWallet:r=>Sh((n=>jh("privy:wallets:create",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),addWallet:r=>Sh((n=>jh("privy:wallets:add",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),setRecovery:r=>Sh((n=>jh("privy:wallets:set-recovery",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),connect:r=>Sh((n=>jh("privy:wallets:connect",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),recover:r=>Sh((n=>jh("privy:wallets:recover",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i,!r.recoveryAccessToken&&!r.recoveryPassword&&!r.recoverySecretOverride),rpc:r=>Sh((n=>jh("privy:wallets:rpc",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),create:r=>jh("privy:wallet:create",r,e,t.origin),importWallet:r=>jh("privy:wallets:import",r,e,t.origin),createSolana:r=>Sh((n=>jh("privy:solana-wallet:create",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),createDelegatedAction:r=>jh("privy:delegated-actions:consent",r,e,t.origin),verifyMfa:r=>Sh((n=>jh("privy:mfa:verify",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i,!0),initEnrollMfa:r=>Sh((n=>jh("privy:mfa:init-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),submitEnrollMfa:r=>Sh((n=>jh("privy:mfa:submit-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),unenrollMfa:r=>Sh((n=>jh("privy:mfa:unenroll",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),clearMfa:r=>jh("privy:mfa:clear",r,e,t.origin),unlinkPasskeyAccount:r=>Sh((n=>jh("privy:auth:unlink-passkey",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,i),initFarcasterSigner:r=>jh("privy:farcaster:init-signer",r,e,t.origin),signFarcasterMessage:r=>jh("privy:farcaster:sign",r,e,t.origin)};window.addEventListener("message",r);let c=new AbortController;return s.invokeUntilSettled((()=>jh("privy:iframe:ready",{},e,t.origin)),{abortSignal:c.signal}).then((()=>t.onLoad(l)),((...e)=>{console.warn("Privy iframe failed to load: ",...e),t.onLoadFailed()})),()=>{window.removeEventListener("message",r),c.abort()}}),[o]),
20
- /*#__PURE__*/e.jsx("iframe",{ref:n,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>l(!0),src:s.constructURL(t.origin,`/apps/${t.appId}/embedded-wallets`,{caid:t.clientAnalyticsId,client_id:t.appClientId})})}const Nh=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));class Mh{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 ip({message:e.params.message,options:{address:this.address,uiOptions:{}}})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Qh())throw Error("User must be authenticated to use embedded Solana wallet");if(!await ap())throw new i.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}}const Rh=()=>{let e=c.useAppConfig();r.useEffect((()=>{(async e=>{let t=new URL("v3/wallets","https://explorer-api.walletconnect.com");t.searchParams.append("projectId",e);let r=await fetch(t);return r.ok?Object.values((await r.json()).listings).sort((({slug:e},{slug:t})=>"rainbow"===e&&"metamask"===t?1:"metamask"===e||"rainbow"===e?-1:1)):(console.debug(`Failed to fetch WalletConnect listings: ${await r.text().catch((()=>"No response."))}`),[])})(e.walletConnectCloudProjectId).then((e=>s.setExternalWalletState({listings:e}))).catch(console.error)}),[e.walletConnectCloudProjectId])},Oh="popup-privy-oauth",Wh="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class Lh{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw i.formatApiError(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function Uh({api:e,requesterAppId:t,providerAppId:r}){let n=(await e.get(`/api/v1/apps/${t}/cross-app/connections`)).connections.find((e=>e.provider_app_id===r));if(!n)throw new i.PrivyClientError("Invalid connected app");return{name:n.provider_app_name,logoUrl:n.provider_app_icon_url||void 0,apiUrl:n.provider_app_custom_api_url,readOnly:n.read_only}}const Fh=async({user:e,address:t,client:r,request:n,requesterAppId:a,reconnect:o})=>{r.createAnalyticsEvent({eventName:"cross_app_request_started",payload:{address:t,method:n.method}});let s=e?.linkedAccounts.find((e=>"cross_app"===e.type&&(e.embeddedWallets.some((e=>e.address===t))||e.smartWallets.some((e=>e.address===t)))));if(!e||!s)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Cannot request a signature with this wallet address",address:t}}),new i.PrivyClientError("Cannot request a signature with this wallet address");let l=r.getProviderAccessToken(s.providerApp.id),c=await Uh({api:r.api,requesterAppId:a,providerAppId:s.providerApp.id});if(!l){if(c.readOnly)throw console.error("cannot transact against a read-only provider app"),new i.PrivyClientError("Cannot transact against a read-only provider app");await o({appId:s.providerApp.id,action:"link"})&&(l=r.getProviderAccessToken(s.providerApp.id))}if(!l)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Transactions require a valid token",address:t}}),new i.PrivyClientError("Transactions require a valid token");let d=$s();if(!d)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new i.PrivyClientError("Failed to initialize signature request");let u=new URL(`${c.apiUrl}/oauth/transact`);return u.searchParams.set("token",l||""),u.searchParams.set("request",Dh(n)),d.location=u.href,new Promise(((e,a)=>{let o=setTimeout((()=>{u(),a(new i.PrivyClientError("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),l=setInterval((()=>{d.closed&&(u(),a(new i.PrivyClientError("User rejected request")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"User rejected request",address:t}}))}),300),c=i=>{i.data&&("set"===i.data.token?.action&&void 0!==i.data.token?.value?r.storeProviderAccessToken(s.providerApp.id,i.data.token.value):"clear"===i.data.token?.action&&r.storeProviderAccessToken(s.providerApp.id,null),"PRIVY_CROSS_APP_ACTION_RESPONSE"===i.data.type&&i.data.result&&(u(),e(i.data.result),r.createAnalyticsEvent({eventName:"cross_app_request_success",payload:{address:t,method:n.method}})),"PRIVY_CROSS_APP_ACTION_ERROR"===i.data.type&&i.data.error&&(u(),a(i.data.error),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:i.data.error,address:t}})))};window.addEventListener("message",c);let u=()=>{d.close(),clearInterval(l),clearTimeout(o),window.removeEventListener("message",c)}}))};let Dh=e=>JSON.stringify({content:{request:{request:Bh(e,y.toHex)}},timestamp:Date.now(),callbackUrl:window.origin});const Bh=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>Bh(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,Bh(r,t)]))):e,Hh=e=>!!e.fundingConfig&&d.filterSupportedOptions(e.fundingConfig.options).length>=1;async function zh({url:e,popup:t,provider:r}){return t.location=e,new Promise(((e,r)=>{function n(){t?.close(),window.removeEventListener("message",a)}function a(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(e(t.data),n()),"https://cdn.apple-cloudkit.com"===t.origin&&t.data.ckSession&&(e({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:t.data.ckSession}),n()),"PRIVY_OAUTH_ERROR"===t.data.type&&(r(t.data.error),n()))}window.addEventListener("message",a)}))}let qh,Vh,Gh,$h,Kh,Yh,Zh,Xh;async function Qh(){return qh?qh.getAccessToken():Promise.resolve(d.i.get(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||d.i.get(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const Jh=(e,t)=>Vh(e,t),ep=(e,t)=>Gh(e,t),tp=(e,t)=>$h(e,t),rp=(e,t)=>Kh(e,t),np=()=>Yh(),ap=()=>Zh(),ip=({message:e,options:t})=>Xh({message:e,options:t});let op=l=>{let u=l.client,h=d.usePlugins();Rh();let[p,y]=r.useState(!1),[g,f]=r.useState(!1),[w,v]=r.useState(!1),[C,x]=r.useState(null),[E,S]=r.useState([]),[T,A]=r.useState([]),[b,_]=r.useState([]),[I,P]=r.useState(!1),[j,k]=r.useState(null),[N,M]=r.useState(!1),[R,O]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:i.notImplemented}),[W,L]=r.useState({status:"initial"}),[U,F]=r.useState({status:"initial"}),[D,B]=r.useState({status:"initial"}),[H,z]=r.useState({status:"initial"}),[q,V]=r.useState({status:"initial"}),[G,$]=r.useState({status:"initial"}),[K,Y]=r.useState(null),Z=c.useAppConfig(),X=c.useIsServerConfigLoaded(),[Q,J]=r.useState(!0),[ee,te]=r.useState({}),[re,ne]=r.useState(null),[ae,ie]=r.useState(null),[oe,se]=r.useState(!1),[le,ce]=r.useState(!1),[de,ue]=r.useState(Z.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),he=r.useRef(null),pe=r.useRef(null),ye=r.useRef(d.privyEventsDefault),[me,ge]=r.useState(!1);u.onStoreCustomerAccessToken=e=>{e&&d.emitPrivyEvent(ye,"accessToken","onAccessTokenGranted",{accessToken:e})},u.onDeleteCustomerAccessToken=()=>{x(null),v(!1),d.emitPrivyEvent(ye,"accessToken","onAccessTokenRemoved")};let fe=r.useRef(null),we=r.useRef(null),ve=r.useRef(!1),Ce=({showWalletUIs:e})=>ve.current?ve.current:void 0!==e?!e:!Z.embeddedWallets.showWalletUIs,xe=e=>{k(e),setTimeout((()=>{y(!0)}),15)},Ee=e=>{("off"!==Z.embeddedWallets.ethereum.createOnLogin||"off"!==Z.embeddedWallets.solana.createOnLogin)&&J(!0),xe(e)};r.useEffect((()=>{let e=[...c.getPrivySolanaHDWallets(C),c.getImportedPrivySolanaWallet(C)].filter((e=>!!e));K&&_(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 i.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new i.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new Mh(K,e.address),async signMessage(t){let r=await Qh();if(!r||!K)throw new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.MUST_BE_AUTHENTICATED);let n=e.imported?c.getImportedPrivySolanaWallet(C):c.getPrivyPrimaryWallet(C);if(!n)throw new i.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);if(!await Ke.recoverPrimaryWallet().catch((()=>!1)))throw new i.PrivyClientError("Wallet couldn't be connected",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);if(!C)throw new i.PrivyClientError("Attempting to sign a transaction with no user initialized");let{response:s}=await K.rpc({accessToken:r,entropyId:a,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:e.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(s.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:n}=await Be({transaction:e,connection:t,transactionOptions:r,wallet:this,signOnly:!1});return n},async signTransaction(t){let r=await Qh();if(!r||!K)throw new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Ke.recoverPrimaryWallet().catch((()=>!1)))throw new i.PrivyClientError("Wallet couldn't be connected",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let n=e.imported?e:c.getPrivyPrimaryWallet(C);if(!n)throw new i.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);return await jd({tx:t,accessToken:r,walletProxy:K,entropyId:a,entropyIdVerifier:o,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0}),t},async signAllTransactions(t){let r=await Qh();if(!r||!K)throw new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Ke.recoverPrimaryWallet().catch((()=>!1)))throw new i.PrivyClientError("Wallet couldn't be connected",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let n=e.imported?e:c.getPrivyPrimaryWallet(C);if(!n)throw new i.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);for(let n of t)await jd({tx:n,accessToken:r,walletProxy:K,entropyId:a,entropyIdVerifier:o,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0});return t},loginOrLink:async()=>{throw new i.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[K,C]),r.useEffect((()=>{if(!C)return void u.connectors?.removeEmbeddedWalletConnectors();let e=c.getPrivyEthereumWallet(C),t=c.getPrivyEthereumHDWallets(C),r=c.getImportedPrivyEthereumWallet(C);e&&t.length||u.connectors?.removeEmbeddedWalletConnectors(),r||u.connectors?.removeImportedWalletConnector(),u.connectors?K?(e&&u.connectors.addEmbeddedWalletConnectors({walletProxy:K,rootWallet:e,embeddedWallets:t,defaultChain:Z.defaultChain,appId:l.appId}),r&&u.connectors.addImportedWalletConnector(K,r.address,Z.defaultChain,l.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")}),[K,C]),r.useEffect((()=>{K&&ae?.(K)}),[K]);let Se=r.useRef();r.useEffect((()=>{(async()=>{if(!Z.customAuth?.enabled)return void ue({status:"not-enabled"});J(!0);let{getCustomAccessToken:e,isLoading:t}=Z.customAuth;if(g&&!t&&"loading"!==de.status){ue({status:"loading"});try{let t=await e();if(t===Se.current)return void ue({status:"done"});if(!t&&w)return Se.current=t,await $e.logout(),ue({status:"done"}),void d.emitPrivyEvent(ye,"customAuth","onUnauthenticated");if(!t)return Se.current=t,void ue({status:"done"});u.startAuthFlow(new xt(t));let{user:r,isNewUser:n}=await u.authenticate();if(!r)return await $e.logout(),ue({status:"error",error:new i.PrivyClientError("Failed to sync with custom auth provider")}),void d.emitPrivyEvent(ye,"customAuth","onUnauthenticated");void 0!==n&&d.emitPrivyEvent(ye,"login","onComplete",{user:r,isNewUser:n,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),Se.current=t,d.emitPrivyEvent(ye,"customAuth","onAuthenticated",{user:r}),ue({status:"done"}),x(r||null),P(n||!1),v(!0),ce(!0)}catch(e){if(console.warn(e),await $e.logout(),d.emitPrivyEvent(ye,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void ue({status:"initial"});d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),ue({status:"error",error:e})}}})()}),["initial"===de.status,Z.customAuth?.enabled,Z.customAuth?.getCustomAccessToken,Z.customAuth?.isLoading,g,w]),r.useEffect((()=>{le&&K&&C&&(async()=>{let e=s.shouldCreateEmbeddedEthWallet(C,Z.embeddedWallets.ethereum.createOnLogin),t=s.shouldCreateEmbeddedSolWallet(C,Z.embeddedWallets.solana.createOnLogin),r=await Qh();if(r){if(e&&t){let e=await Oe(C,c.WALLET_PROXY_TIMEOUT);return await K.createSolana({accessToken:r,ethereumAddress:e?.address}),void ce(!1)}if(t)return await K.createSolana({accessToken:r,ethereumAddress:c.getPrivyEthereumWallet(C)?.address}),await Ke.refreshSessionAndUser(),void ce(!1);if(e)return await Oe(C,c.WALLET_PROXY_TIMEOUT),void ce(!1)}})().catch(console.error)}),[le&&K&&C]),r.useEffect((()=>{if(Z.externalWallets.solana.connectors)return Z.externalWallets.solana.connectors.onMount(),()=>Z.externalWallets.solana.connectors?.onUnmount()}),[Z.externalWallets.solana.connectors]),r.useEffect((()=>{!g&&X&&async function(){let e,r=Te(),n=Ae(),a=t.createStore();u.initializeConnectorManager({walletConnectCloudProjectId:Z.walletConnectCloudProjectId,rpcConfig:Z.rpcConfig,chains:Z.chains,defaultChain:Z.defaultChain,store:a,walletList:Z.appearance.walletList,shouldEnforceDefaultChainOnConnect:Z.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Z.externalWallets,appName:Z.name??"Privy",walletChainType:Z.appearance.walletChainType}),u.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=u.connectors.walletConnectors.length,r=u.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?ge(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),ge(!0)}),1500)})),u.connectors?.initialize().then((()=>{je()}));let i=await u.getAuthenticatedUser(),o=!!i;Z.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await u.logout(),Ke.setReadyToTrue(!0),d.emitPrivyEvent(ye,"logout","onSuccess")):(Z.customAuth?.enabled||(v(!!i),i&&d.emitPrivyEvent(ye,"login","onComplete",{user:i,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),x(i)),r?we.current=o?"link":"login":n&&!o?(we.current="login",te({telegramAuthModalData:{seamlessAuth:!0}}),Ee(c.ModalScreen.TELEGRAM_AUTH_SCREEN)):Ke.setReadyToTrue(!!i))}()}),[u,re,g,X]),r.useEffect((()=>{if(g){if(!C||!C.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void se(!0);se([...E,...b].some((e=>"privy"===e.walletClientType)))}}),[g,C,E,b]),r.useEffect((()=>{u.connectors?.setWalletList(Z.appearance.walletList)}),[Z.appearance.walletList.join()]);let Te=()=>{let e=Vt();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&&function(e){return e.startsWith("privy:")}(e.provider)&&!e.popupFlow&&(new BroadcastChannel(Oh).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(u.startAuthFlow(new kt(e)),Ee(c.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},Ae=()=>{let e=function(){let e;return(e=function(){let e=new URLSearchParams(window.location.search),t=Number(e.get("id")||""),r=e.get("hash"),n=Number(e.get("auth_date")||""),a=e.get("first_name");if(t&&a&&n&&r)return Object.fromEntries(e.entries())}())?(Jt(),{flowType:"login-url",authData:e}):(e=function(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=Qt(e.replace("#tgWebAppData=","")),{user:r,auth_date:n,hash:a}=t;return r&&n&&a?t:void 0}())?(Jt(),{flowType:"web-app",authData:e}):void 0}();if(!e||!Z.loginMethods.telegram||!Z.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Zt;return u.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},be=async(e,t,r,n)=>{if("solana_adapter"!==e)_e(await(u.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,n);else{let e=u.connectors?.findSolanaWalletConnector(t);if(!e)return;_e(e,t,r,n)}};async function _e(e,t,r,n){if(!e)return O({status:"disconnected",connectedWallet:null,connectError:new i.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:i.notImplemented}),n?.(null,r);O({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:i.notImplemented}),e instanceof s.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),O({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>_e(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||s.isBaseConnectedEthereumWallet(t))&&Z.shouldEnforceDefaultChainOnConnect&&!Z.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){O((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:i.notImplemented})));try{await(t?.switchChain(Z.defaultChain.id)),t&&(t.chainId=s.formatChainIdToCAIP2(s.toHex(Z.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Z.defaultChain.id}`)}}return O((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:i.notImplemented}))),t&&d.emitPrivyEvent(ye,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof i.PrivyError?(console.warn(e.cause?e.cause:e.message),d.emitPrivyEvent(ye,"connectWallet","onError",e.privyErrorCode||i.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),d.emitPrivyEvent(ye,"connectWallet","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),O((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Ie=async(e,t,r)=>{if(null===e||!s.isBaseConnectedEthereumWallet(e))return;let n=new s.SiweFlow(e,u,t,r);u.startAuthFlow(n)},Pe=async(e,t,r)=>{if(null===e||!d.isBaseConnectedSolanaWallet(e))return;let n=new s.SiwsFlow(e,u,t,r);u.startAuthFlow(n)},je=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),n="true"===e.get("privy_connect_only");if(!t||!r)return;let a=_r({connectorType:t,walletClientType:r});if(!a||!a.isInstalled)return Ee(c.ModalScreen.LOGIN_FAILED_SCREEN);if(!u.connectors)throw new i.PrivyClientError("Connector not initialized");xe(n?c.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION:c.ModalScreen.AWAITING_CONNECTION);let o=new URL(window.location.href);o.searchParams.delete("privy_connector"),o.searchParams.delete("privy_wallet_client"),o.searchParams.delete("privy_connect_only"),window.history.pushState({},"",o),be(t,r,void 0,n?void 0:"solana_adapter"===t?Pe:Ie)};r.useEffect((()=>{g&&w&&null===C&&u.getAuthenticatedUser().then(x)}),[g,w,C,u]);let ke=e=>{if(!w)throw d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new i.PrivyClientError("User must be authenticated before linking an account.")},Ne=e=>{if(!w||!C)return!1;if("privy"===e.walletClientType)return!0;for(let t of C.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Me=async e=>{let t;if(!u.connectors)throw new i.PrivyClientError("Connector not initialized");t="ethereum"===e.type?u.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:u.connectors.findSolanaWalletConnector(e.walletClientType)||null,O((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:i.notImplemented}))),Z.captchaEnabled&&!w?(te({captchaModalData:{callback:t=>s.isBaseConnectedEthereumWallet(e)?Ie(e,t):Pe(e,t),userIntentRequired:!1,onSuccessNavigateTo:c.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:c.ModalScreen.ERROR_SCREEN}}),Ee(c.ModalScreen.CAPTCHA_SCREEN)):(s.isBaseConnectedEthereumWallet(e)?await Ie(e):await Pe(e),Ee(c.ModalScreen.AWAITING_CONNECTION))},Re=()=>{S((e=>{let t=u.connectors?.wallets.filter(s.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Ne(e),loginOrLink:async()=>{if(!await e.isConnected())throw new i.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot link or login with embedded wallet");Me(e)},fund:async t=>{await Ke.fundWallet(e.address,t)},unlink:async()=>{if(!w)throw new i.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot unlink an embedded wallet");x(await u.unlinkEthereumWallet(e.address))}})))||[];return s.areWalletArraysEqual(e,t)?e:t})),A((e=>{let t=(u.connectors?.wallets??[]).filter(d.isBaseConnectedSolanaWallet).map((e=>({...e,linked:Ne(e),loginOrLink:async()=>{if(!await e.isConnected())throw new i.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot link or login with embedded wallet");Me(e)},fund:async()=>{throw new i.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!w)throw new i.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot unlink an embedded wallet");x(await u.unlinkSolanaWallet(e.address))}})));return s.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{Re()}),[C?.linkedAccounts,w,g]),r.useEffect((()=>{if(g){if(!u.connectors)throw new i.PrivyClientError("Connector not initialized");Re(),u.connectors.on("walletsUpdated",Re)}}),[g]),r.useEffect((()=>{[...Z.loginMethodsAndOrder?.primary??[],...Z.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>u.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!u]);let Oe=async(e,t,r)=>{let n=c.getPrivyEthereumWallet(e),a=c.getPrivySolanaWallet(e);if(r&&"walletIndex"in r&&"number"==typeof r.walletIndex)return Le(e,t,r.walletIndex,n,a);let o=r&&"createAdditional"in r&&r.createAdditional;if(n&&!o)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[s,l]=await Promise.all([Ke.initializeWalletProxy(t),Qh()]);if(!s&&Z.customAuth?.enabled)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!s||!l||Z.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return We();if(!n)return a&&await Ke.recoverPrimaryWallet(),await s.create({accessToken:l,solanaAddress:a?.address}),Fe(0,"ethereum");{let t=(c.getLatestPrivyEthereumWallet(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:n}=c.getEntropyDetailsFromAccount(c.getPrivyPrimaryWallet(e));return await Ke.recoverPrimaryWallet(),await s.addWallet({accessToken:l,entropyId:r,entropyIdVerifier:n,chainType:"ethereum",hdWalletIndex:t}),Fe(t,"ethereum")}},We=async()=>new Promise(((e,t)=>{J(!0),te({createWallet:{onSuccess:t=>{d.emitPrivyEvent(ye,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),xe(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),Le=async(e,t,r,n,a)=>{if(r<0)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[o,s]=await Promise.all([Ke.initializeWalletProxy(t),Qh()]);if(!o&&Z.customAuth?.enabled)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||Z.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return We();throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==r){if(n)return n;await o.create({accessToken:s,solanaAddress:a?.address})}else{if(!n)throw d.emitPrivyEvent(ye,"createWallet","onError",i.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=c.getPrivyEthereumHDWallets(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:a,entropyIdVerifier:l}=c.getEntropyDetailsFromAccount(c.getPrivyPrimaryWallet(e));await Ke.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:a,entropyIdVerifier:l,chainType:"ethereum",hdWalletIndex:r})}return Fe(r,"ethereum")},Ue=async({user:e,wp:t,accessToken:r,walletIndex:n,ethereumWallet:a})=>{let o=c.getPrivySolanaHDWallets(e).find((e=>e.walletIndex===n));if(o)return o;if(0===n)a&&await Ke.recoverPrimaryWallet(),await t.createSolana({accessToken:r,ethereumAddress:a?.address});else{let a=c.getPrivyPrimaryWallet(e);if(!a)throw d.emitPrivyEvent(ye,"createWallet","onError",i.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:o,entropyIdVerifier:s}=c.getEntropyDetailsFromAccount(a);await Ke.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:o,entropyIdVerifier:s,chainType:"solana",hdWalletIndex:n})}return Fe(n,"solana")},Fe=async(e,t)=>{let r=await Ke.refreshSessionAndUser(),n=("ethereum"===t?c.getPrivyEthereumHDWallets(r):c.getPrivySolanaHDWallets(r)).find((t=>t.walletIndex===e));if(!n)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return d.emitPrivyEvent(ye,"createWallet","onSuccess",{wallet:n}),n},De=({transaction:e,uiOptions:t,fundWalletConfig:r,address:n,signOnly:o})=>new Promise((async(s,u)=>{let{requesterAppId:h}=t||{},p=o?"signTransaction":"sendTransaction";if(!w||!C)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void u(Error("User must be authenticated before signing with a Privy wallet"));let y=n??c.getPrivyEthereumWallet(C)?.address;if(!y)throw new i.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:g,rootWallet:f}=c.getEthereumSigningAndRootWallet(C,y);if(!f||!g)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have a Privy wallet before signing"));J(!0);let v=Ye.wallets.find((e=>"privy"===e.walletClientType&&a.getAddress(e.address)===a.getAddress(g.address))),x=await(v?.getEthereumProvider());if(!v||!x)throw new i.PrivyClientError(`Cannot sendTransaction before embedded wallet ${g.address} is connected`);let E=e.chainId?Number(e.chainId):d.extractChainIdFromCAIP2(v.chainId);(e=>{if(!Z.chains.map((e=>e.id)).includes(e))throw new i.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,i.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(E);let S={...e,from:e.from??g.address,chainId:E},T=await Qh();if(!T||!K)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have valid access token and Privy wallet to send transaction"));let A=m.getPublicClient(S.chainId,Z.chains,Z.rpcConfig,{appId:l.appId});if(Ce({showWalletUIs:t?.showWalletUIs}))(async()=>{try{if(!await Ke.recoverPrimaryWallet())return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void u(Error("Unable to connect to wallet"));let e=await ld(S,A,S.from),{entropyId:t,entropyIdVerifier:r}=c.getEntropyDetailsFromAccount(f),n=o?await Cu({accessToken:T,entropyId:t,entropyIdVerifier:r,transactingWallet:g,walletProxy:K,transactionRequest:S,requesterAppId:h}):await vu({accessToken:T,entropyId:t,entropyIdVerifier:r,transactingWallet:g,walletProxy:K,transactionRequest:e,publicClient:A,requesterAppId:h});o?d.emitPrivyEvent(ye,"signTransaction","onSuccess",{signature:n}):d.emitPrivyEvent(ye,"sendTransaction","onSuccess",{hash:n}),s({hash:n})}catch(e){d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)}})();else{let{entropyId:e,entropyIdVerifier:n}=c.getEntropyDetailsFromAccount(f),a={entropyId:e,entropyIdVerifier:n,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}},l=Hh(Z)?d.prepareFundingModalData({address:g.address,appConfig:Z,fundWalletConfig:r,methodScreen:c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:S.chainId,comingFromSendTransactionScreen:!0}):void 0;te({connectWallet:a,sendTransaction:{transactionRequest:S,transactingWallet:g,entropyId:e,entropyIdVerifier:n,signOnly:o,onConfirm:o?async()=>await Cu({accessToken:T,entropyId:e,entropyIdVerifier:n,transactingWallet:g,walletProxy:K,transactionRequest:S,requesterAppId:h}):void 0,onSuccess:e=>{o?d.emitPrivyEvent(ye,"signTransaction","onSuccess",{signature:e.hash}):d.emitPrivyEvent(ye,"sendTransaction","onSuccess",{hash:e.hash}),s(e)},onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)},uiOptions:t||{},fundWalletConfig:r,requesterAppId:h},funding:l}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),Be=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:n,uiOptions:a,wallet:o,signOnly:s})=>new Promise((async(l,u)=>{let{requesterAppId:h}=a||{},p=s?"signSolanaTransaction":"sendSolanaTransaction";if(!w||!C)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void u(new i.PrivyClientError("User must be authenticated before signing with a Privy wallet",i.PrivyErrorCode.MUST_BE_AUTHENTICATED));let y=o?C.linkedAccounts.find((e=>"wallet"===e.type&&e.address===o.address)):c.getPrivySolanaWallet(C);if(!y)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(new i.PrivyClientError("Must have a Privy wallet before signing",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));J(!0);let{rootWallet:m}=c.getSolanaSigningAndRootWallet(C,y.address);if(!await Ke.recoverPrimaryWallet().catch((()=>!1))||!m)throw d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new i.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${y.address} is connected`,i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);if(Ce({showWalletUIs:a?.showWalletUIs}))(async()=>{let n=await Qh();if(!n||!K)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{let o;if(!await Ke.recoverPrimaryWallet())return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void u(new i.PrivyClientError("Unable to connect to wallet",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Ce({showWalletUIs:a?.showWalletUIs})&&!s)try{if(!await async function(e,t){let{value:r}=await t.simulateTransaction(e);if("BlockhashNotFound"===r.err)throw Error("Simulation failed: Blockhash not found");return null==r.err&&r.logs?.every((e=>!/insufficient funds/gi.test(e)))}(e,t))return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.INSUFFICIENT_BALANCE),void u(new i.PrivyClientError("Solana wallet has insufficient funds for this transaction.",i.PrivyErrorCode.INSUFFICIENT_BALANCE))}catch(e){return console.error(e),d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),void u(new i.PrivyClientError(e instanceof Error?e.message:"Transaction failed.",i.PrivyErrorCode.TRANSACTION_FAILURE))}let{entropyId:h,entropyIdVerifier:m}=c.getEntropyDetailsFromUser(C);if(s)await jd({accessToken:n,tx:e,walletProxy:K,entropyId:h,entropyIdVerifier:m,transactingWalletAddress:y.address,transactingWalletIndex:y.walletIndex??0}),o=Wo("",e,null),d.emitPrivyEvent(ye,"signSolanaTransaction","onSuccess",{signedTransaction:e});else{let{signature:a,receipt:i}=await kd({accessToken:n,tx:e,connection:t,walletProxy:K,transactionOptions:r,entropyId:h,entropyIdVerifier:m,transactingWalletAddress:y.address,transactingWalletIndex:y.walletIndex??0});o=Wo(a,e,i),d.emitPrivyEvent(ye,"sendSolanaTransaction","onSuccess",{response:o})}l(o)}catch(e){d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)}})();else{let{entropyId:o,entropyIdVerifier:g}=c.getEntropyDetailsFromAccount(m),f={entropyId:o,entropyIdVerifier:g,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}},w=Hh(Z)?d.prepareSolanaFundingModalData({address:y.address,appConfig:Z,methodScreen:c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:n,comingFromSendTransactionScreen:!0}):void 0;te({connectWallet:f,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:y,onSuccess:e=>{s?d.emitPrivyEvent(ye,"signSolanaTransaction","onSuccess",{signedTransaction:e.signedTransaction}):d.emitPrivyEvent(ye,"sendSolanaTransaction","onSuccess",{response:e}),l(e)},onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)},uiOptions:a||{},requesterAppId:h,signOnly:s},funding:w}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function He(){return new Promise((async(e,t)=>{let r=await Qh();if(!r||!K)throw Error("Must have valid access token to enroll in MFA");try{await K.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let ze=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],qe=e=>{let t=C?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=wl(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new i.PrivyClientError(`User already has an account of type ${r} linked.`)};async function Ve({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){k(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!w||!C)throw d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=c.getPrivyPrimaryWallet(C);if(!n||!K)throw d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await He()}catch(e){throw d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((a,o)=>{J(!0);let s={onSuccess:e=>{d.emitPrivyEvent(ye,r,"onSuccess",{method:"user-passcode",wallet:e}),a(e)},onFailure:e=>{d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),o(e)},callAuthOnSuccessOnClose:!1},l="user-passcode"===n.recoveryMethod,u=Ka({walletAction:"update",availableRecoveryMethods:Z.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:l,showAutomaticRecovery:e}),{entropyId:h,entropyIdVerifier:p}=c.getEntropyDetailsFromAccount(n);te({setWalletPassword:s,recoverWallet:{entropyId:h,entropyIdVerifier:p,onFailure:o},createWallet:s,connectWallet:{onCompleteNavigateTo:u,shouldForceMFA:!1,entropyId:h,entropyIdVerifier:p,onFailure:e=>{d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:l}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function Ge({appId:e,action:t}){let r=await Qh();if("link"===t&&!r)throw d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new i.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw d.emitPrivyEvent(ye,"login","onError",i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new i.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");fe.current=`privy:${e}`,we.current=t;let n=$s();return u.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,a)=>{let{name:i,logoUrl:o}=await Uh({api:u.api,providerAppId:e,requesterAppId:Z.id});te({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:n,onSuccess:r,onError:a}}),Ee(c.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let $e={ready:g,authenticated:w,user:C,walletConnectors:u.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),te({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress,walletChainType:e?.walletChainType}}),xe(w?c.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:c.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),ke("siwe"),fe.current="siwe",we.current="link",te({...ee,externalConnectWallet:{...ee.externalConnectWallet,suggestedAddress:e?.suggestedAddress,walletList:e?.walletList,walletChainType:e?.walletChainType}}),xe(c.ModalScreen.LINK_WALLET_SCREEN)},startCrossAppAuthFlow:Ge,linkEmail:()=>{ke("email"),qe("email"),fe.current="email",we.current="link",xe(c.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{ke("sms"),qe("phone"),fe.current="sms",we.current="link",xe(c.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{ke("google"),qe("google_oauth"),we.current="link",await Ke.initLoginWithOAuth("google")},linkTwitter:async()=>{ke("twitter"),qe("twitter_oauth"),we.current="link",await Ke.initLoginWithOAuth("twitter")},linkDiscord:async()=>{ke("discord"),qe("discord_oauth"),we.current="link",await Ke.initLoginWithOAuth("discord")},linkGithub:async()=>{ke("github"),qe("github_oauth"),we.current="link",await Ke.initLoginWithOAuth("github")},linkSpotify:async()=>{ke("spotify"),qe("spotify_oauth"),we.current="link",await Ke.initLoginWithOAuth("spotify")},linkInstagram:async()=>{ke("instagram"),qe("instagram_oauth"),we.current="link",await Ke.initLoginWithOAuth("instagram")},linkTiktok:async()=>{ke("tiktok"),qe("tiktok_oauth"),we.current="link",await Ke.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{ke("linkedin"),qe("linkedin_oauth"),we.current="link",await Ke.initLoginWithOAuth("linkedin")},linkApple:async()=>{ke("apple"),qe("apple_oauth"),we.current="link",await Ke.initLoginWithOAuth("apple")},linkPasskey:async()=>{ke("passkey"),qe("passkey"),await Ke.initLinkWithPasskey(),xe(c.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if(ke("telegram"),qe("telegram"),we.current="link",fe.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new Zt;u.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=Qt(e.launchParams.initDataRaw),te({telegramAuthModalData:{seamlessAuth:!0}}),Ee(c.ModalScreen.TELEGRAM_AUTH_SCREEN)}else d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await Ke.initLoginWithTelegram();xe(c.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{ke("farcaster"),qe("farcaster"),await Ke.initLoginWithFarcaster(),we.current="link",fe.current="farcaster",xe(c.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(ke("email"),!C?.email)throw new i.PrivyClientError("User does not have an email linked to their account.");we.current="update",fe.current="email",xe(c.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(ke("sms"),!C?.phone)throw new i.PrivyClientError("User does not have a phone number linked to their account.");we.current="update",fe.current="sms",xe(c.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(!g){let e=await new Promise((e=>{ne((t=>e.bind(t)))}));if(ne(null),e)return void console.warn(t)}!C||C.isGuest?(we.current="login",te({login:e}),Ee(c.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{g||(await new Promise((e=>{ne((()=>e))})),ne(null)),w?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(we.current="login",Ee(c.ModalScreen.CONNECT_OR_CREATE))},logout:async()=>{if(we.current=null,fe.current=null,C&&u.clearProviderAcccessTokens(C),k(null),await u.logout(),C&&K)try{await K.clearMfa({userId:C.id})}catch(e){}x(null),v(!1),d.emitPrivyEvent(ye,"logout","onSuccess"),y(!1),d.i.del(c.CLIENT_ANALYTICS_ID_KEY),d.i.del(c.getGuestCredentialStorageKey(Z.id))},getAccessToken:r.useCallback((()=>u.getCustomerAccessToken()),[u]),unlinkWallet:async e=>{let t;return x(t=e.startsWith("0x")?await u.unlinkEthereumWallet(e):await u.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await u.unlinkEmail(e);return x(t),t},unlinkPhone:async e=>{let t=await u.unlinkPhone(e);return x(t),t},unlinkGoogle:async e=>{let t=await u.unlinkOAuth("google",e);return x(t),t},unlinkTwitter:async e=>{let t=await u.unlinkOAuth("twitter",e);return x(t),t},unlinkDiscord:async e=>{let t=await u.unlinkOAuth("discord",e);return x(t),t},unlinkGithub:async e=>{let t=await u.unlinkOAuth("github",e);return x(t),t},unlinkSpotify:async e=>{let t=await u.unlinkOAuth("spotify",e);return x(t),t},unlinkInstagram:async e=>{let t=await u.unlinkOAuth("instagram",e);return x(t),t},unlinkTiktok:async e=>{let t=await u.unlinkOAuth("tiktok",e);return x(t),t},unlinkLinkedIn:async e=>{let t=await u.unlinkOAuth("linkedin",e);return x(t),t},unlinkApple:async e=>{let t=await u.unlinkOAuth("apple",e);return x(t),t},unlinkFarcaster:async e=>{let t=await u.unlinkFarcaster(e);return x(t),t},unlinkTelegram:async e=>{let t=await u.unlinkTelegram(e);return x(t),t},unlinkPasskey:async e=>{let t=await Qh();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!K)throw Error("Wallet proxy not initialized.");let r=Z.passkeys.shouldUnenrollMfaOnUnlink;await K.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let n=await u.getAuthenticatedUser();return x(n),n},unlinkCrossAppAccount:async({subject:e})=>{let t=C?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new i.PrivyClientError("Invalid subject");u.storeProviderAccessToken(t.id,null);let r=await u.unlinkOAuth(`privy:${t.id}`,e);return x(r),r},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await Ke.refreshSessionAndUser();if(!t)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return Oe(t,15e3,e)},setWalletRecovery:async e=>Ve({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>Ve({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:a}=t?.uiOptions||{},o=e.message;if(!w||!C)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let s=t?.address??c.getPrivyEthereumWallet(C)?.address;if(!s)throw new i.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=c.getEthereumSigningAndRootWallet(C,s);if(!l||!h)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof o||o.length<1)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));J(!0);let p=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Qh();if(!K||!e||!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:l.address,requesterAppId:a}});let{entropyId:t,entropyIdVerifier:r}=c.getEntropyDetailsFromAccount(h),{response:n}=await K.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:l.walletIndex??0,requesterAppId:a,request:{method:"personal_sign",params:[o,l.address]}}),i=n.data;return u.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:l.address,requesterAppId:a}}),i};if(Ce({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await p();d.emitPrivyEvent(ye,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new d.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"personal_sign",data:o,confirmAndSign:p,onSuccess:e=>{d.emitPrivyEvent(ye,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},{entropyId:a,entropyIdVerifier:s}=c.getEntropyDetailsFromAccount(h);te({signMessage:e,connectWallet:{entropyId:a,entropyIdVerifier:s,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:a}=t?.uiOptions||{};if(!w||!C)return d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let o=t?.address??c.getPrivyEthereumWallet(C)?.address;if(!o)throw new i.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=c.getEthereumSigningAndRootWallet(C,o);if(!h||!l)return d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));J(!0);let p=s.generateTypedDataWithDomainType(e),y=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Qh();if(!K||!e||!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:l.address,requesterAppId:a}});let{entropyId:t,entropyIdVerifier:r}=c.getEntropyDetailsFromAccount(h),{response:n}=await K.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:l.walletIndex??0,requesterAppId:a,request:{method:"eth_signTypedData_v4",params:[l.address,p]}}),i=n.data;return u.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:l.address,requesterAppId:a}}),i};if(Ce({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await y();d.emitPrivyEvent(ye,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new d.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:p,confirmAndSign:y,onSuccess:e=>{d.emitPrivyEvent(ye,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(h);te({signMessage:e,connectWallet:{entropyId:a,entropyIdVerifier:o,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t)=>await De({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await De({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!w||!C)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let n=e?.address??c.getPrivyEthereumWallet(C)?.address;if(!n)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`."));if(!a.isAddress(n))return void r(Error("Must provide a valid Ethereum address."));let{signingWallet:i,rootWallet:o}=c.getEthereumSigningAndRootWallet(C,n);if(!i||!o)return void r(Error("Must have a Privy wallet before exporting"));J(!0);let{entropyId:s,entropyIdVerifier:d}=c.getEntropyDetailsFromAccount(o),h={entropyId:s,entropyIdVerifier:d,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0};te(ee),await Qh()&&K?K?(te({keyExport:{appId:l.appId,appClientId:l.clientId,origin:u.apiUrl,walletToExport:i,primaryWallet:o,onSuccess:t,onFailure:r},connectWallet:h}),xe(c.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:He,async init(e){switch(e){case"sms":return void await u.initMfaSmsVerification();case"passkey":return await u.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 i.PrivyClientError("Invalid MFA code");he.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{pe.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new i.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=(e=>({id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}))(await r.startAuthentication(t));he.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{pe.current={resolve:e,reject:t}}));break;default:throw he.current?.reject(new i.PrivyClientError("Unsupported MFA method")),new i.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){he.current?.reject(new i.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Qh();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Ke.closePrivyModal(),void t();Z.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."),te({mfaEnrollmentFlow:{mfaMethods:Z.mfa.methods,shouldUnlinkOnUnenrollMfa:Z.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),xe(c.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await Qh();if(!e||!K)throw Error("Must have valid access token to enroll in MFA");let t=await K.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Qh();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),x(await u.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Qh();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),x(await u.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await Qh();if(!r||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),x(await u.getAuthenticatedUser())},async unenroll(e,t={}){let r=await Qh();if(!r||!K)throw Error("Must have valid access token to remove MFA");"passkey"===e?await K.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await K.unenrollMfa({method:e,accessToken:r}),x(await u.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Qh(),t=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!K||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await K.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&x(await u.getAuthenticatedUser()||C||null),te({farcasterSigner:r}),xe(c.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await Qh(),r=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!C.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=C.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Qh(),r=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!C.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),a=await K.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(C.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(a.signature))},createGuestAccount:async()=>{if(C&&!C.isGuest)throw Error("User cannot already be authenticated to create a guest account");return C?.isGuest?C:Ke.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let n=C?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Fh({user:C,client:u,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:Ge})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let n=C?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),a=s.generateTypedDataWithDomainType(e);return Fh({user:C,client:u,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,a],chainId:r},reconnect:Ge})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=C?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Fh({user:C,client:u,address:t,requesterAppId:Z.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:Ge})},isModalOpen:p,mfaMethods:Z.mfa.methods};Vh=$e.signMessage,Gh=$e.signTypedData,Kh=async(e,t)=>await De({transaction:e,...t,signOnly:!1}),$h=async(e,t)=>({signature:(await De({transaction:e,...t,signOnly:!0})).hash});let Ke={setAuthenticated:v,setUser:x,isNewUserThisSession:I,pendingTransaction:null,walletConnectionStatus:R,connectors:u.connectors?.walletConnectors??[],solanaWallets:T,rpcConfig:Z.rpcConfig,chains:Z.chains,appId:l.appId,showFiatPrices:"native-token"!==Z.embeddedWallets.priceDisplay.primary,clientAnalyticsId:u.clientAnalyticsId,customAuthStatus:de,hideWalletUIs:ve,isHeadlessSigning:r.useCallback(Ce,[Z.embeddedWallets.showWalletUIs]),emailOtpState:U,setEmailOtpState:F,smsOtpState:D,setSmsOtpState:B,oAuthState:q,setOAuthState:V,telegramAuthState:G,setTelegramAuthState:$,siweState:H,setSiweState:z,isHeadlessOAuthLoading:N,nativeTokenSymbolForChainId:e=>Z.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(K)return K;let t=new Promise((e=>{ie((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return ie(null),n},getAuthFlow:()=>u.authFlow,getAuthMeta:()=>u.authFlow?.meta,client:u,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=g&&w&&C;r&&fe.current&&(t=ze(C)),"login"===we.current?e.shouldCallAuthOnSuccess&&r&&fe.current?d.emitPrivyEvent(ye,"login","onComplete",{user:C,isNewUser:I,wasAlreadyAuthenticated:!1,loginMethod:fe.current,loginAccount:t??null}):d.emitPrivyEvent(ye,"login","onError",i.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===we.current&&t?e.isSuccess&&r&&fe.current?d.emitPrivyEvent(ye,"linkAccount","onSuccess",{user:C,linkMethod:fe.current,linkedAccount:t}):fe.current&&d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:fe.current}):"update"===we.current&&t&&(e.isSuccess&&r&&fe.current?d.emitPrivyEvent(ye,"update","onSuccess",{user:C,updateMethod:fe.current,updatedAccount:t}):fe.current&&d.emitPrivyEvent(ye,"update","onError",i.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:fe.current}));let n=j&&Ms.includes(j),a=j===c.ModalScreen.ERROR_SCREEN&&ee.errorModalData&&Ms.includes(ee.errorModalData.previousScreen);if((n||a)&&ee.funding){let e,t=Rs[j]??null;if("solana"===ee.funding.chainType){let r=h(d.SOLANA_FUNDING_PLUGIN_ID);if(!r)return void console.warn("Unable to load solana plugin, skipping balance");try{e=BigInt(await r.getBalance({address:ee.funding.address,cluster:ee.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}d.emitPrivyEvent(ye,"fundSolanaWallet","onUserExited",{address:ee.funding.address,cluster:ee.funding.cluster,fundingMethod:t,balance:e})}else{let r=m.getPublicClient(ee.funding.chain.id,Z.chains,Z.rpcConfig,{appId:l.appId});try{e=await r.getBalance({address:ee.funding.address})}catch{console.error("Unable to pull wallet balance")}d.emitPrivyEvent(ye,"fundWallet","onUserExited",{address:ee.funding.address,chain:ee.funding.chain,fundingMethod:t,balance:e})}}te({...ee,externalConnectWallet:{suggestedAddress:void 0}}),we.current=null,fe.current=null,P(!1),y(!1),setTimeout((()=>{u.authFlow=void 0}),200)},solanaSignMessage:({message:e,options:t})=>new Promise((async(r,n)=>{if(!w||!C)return d.emitPrivyEvent(ye,"signSolanaMessage","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let a=t?.address??c.getPrivySolanaWallet(C)?.address;if(!a)throw new i.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:o,rootWallet:s}=c.getSolanaSigningAndRootWallet(C,a);if(!o||!s)return d.emitPrivyEvent(ye,"signSolanaMessage","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));J(!0);let l=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let t=await u.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=Ke.walletProxy??await Ke.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!s)throw Error("No root wallet for signing wallet found");let{entropyId:n,entropyIdVerifier:a}=c.getEntropyDetailsFromUser(C),{response:i}=await r.rpc({accessToken:t,entropyId:n,entropyIdVerifier:a,chainType:"solana",hdWalletIndex:o.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return i.data.signature};if(Ce({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await l();d.emitPrivyEvent(ye,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})}catch(e){n(e)}else{let a={method:"solana_signMessage",data:e,confirmAndSign:l,onSuccess:e=>{d.emitPrivyEvent(ye,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})},onFailure:e=>{n(e)},uiOptions:t?.uiOptions},{entropyId:o,entropyIdVerifier:u}=c.getEntropyDetailsFromAccount(s);te({signMessage:a,connectWallet:{entropyId:o,entropyIdVerifier:u,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,"signSolanaMessage","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),Ee(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:n,address:a})=>{let o=a?b.find((e=>e.address===a)):b.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw d.emitPrivyEvent(ye,"signSolanaTransaction","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new i.PrivyClientError("Embedded wallet not found",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);let{signedTransaction:s}=await Be({transaction:e,connection:t,transactionOptions:n,uiOptions:r,wallet:o,signOnly:!0});return s},sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:n,fundWalletConfig:a,address:o})=>{let s=o?b.find((e=>e.address===o)):b.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!s)throw d.emitPrivyEvent(ye,"sendSolanaTransaction","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new i.PrivyClientError("Embedded wallet not found",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);return await Be({transaction:e,connection:t,transactionOptions:n,uiOptions:r,fundWalletConfig:a,wallet:s,signOnly:!1})},openPrivyModal:xe,connectWallet:_e,initLoginWithWallet:async(e,t,r)=>{s.isBaseConnectedEthereumWallet(e)?(fe.current="siwe",Ie(e,t,r)):(fe.current="siws",Pe(e,t,r))},loginWithWallet:async()=>{let e,t,r;if(!g)throw new i.PrivyNotReadyError;if(u.authFlow instanceof s.SiweFlow?e="siwe":u.authFlow instanceof s.SiwsFlow&&(e="siws"),!e)throw new i.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await u.getAccessToken())try{({user:t}=await u.link()),fe.current=e}catch(t){throw d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await u.authenticate()),fe.current=e}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}x(t||C||null),P(r||!1),v(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,a)=>{let o=await Qh();if(!w||!C||!o)throw new i.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new i.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let s=Ke.walletProxy??await Ke.initializeWalletProxy(15e3);if(!s)throw new i.PrivyClientError("Wallet proxy not initialized.");if((({address:e,chainType:t,user:r})=>!!Nh(r).find((r=>r.address===e&&r.chainType===t)))({address:e,chainType:t,user:C}))return n();let l=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new i.PrivyClientError("Address to delegate is not associated with current user.");return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}})({address:e,user:C}),d=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new i.PrivyClientError("Address to delegate is not associated with current user.");let n=r.imported?r:c.getPrivyPrimaryWallet(t);if(!n)throw new i.PrivyClientError("Unable to determine root address for delegated address.");return{address:n.address,chainType:n.chainType,imported:n.imported}})({address:e,user:C}),u=async()=>{await s.createDelegatedAction({accessToken:o,rootWallet:d,delegatedWallets:[l]}),await Ke.refreshSessionAndUser()};if(await Ke.recoverPrimaryWallet(),r)te({delegatedActions:{consent:{address:e,onDelegate:u,onSuccess:async()=>{n()},onError:async e=>{a(e)}}}}),xe(c.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN);else try{await u(),n()}catch(e){a(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!w||!C)throw new i.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===Nh(C).length)throw new i.PrivyClientError("User has no delegated wallets to revoke.");let n=async()=>{await u.revokeDelegatedWallet(),await Ke.refreshSessionAndUser()};if(e)te({delegatedActions:{revoke:{onRevoke:n,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),xe(c.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN);else try{await n(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new At(e,t);u.startAuthFlow(r);try{fe.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===we.current?d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof At))throw new i.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await u.getAccessToken())try{({user:e}=await u.link()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await u.authenticate()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}x(e||null),P(t||!1),v(!0)},async loginWithGuestAccountFlow(){let e=new _t(this.appId);u.startAuthFlow(e);try{we.current="login",fe.current="guest";let{user:e,isNewUser:t}=await u.authenticate();if(t=t||!1,!e)throw new i.PrivyClientError("Unable to authenticate guest account");let r=await Qh(),n=await Ke.initializeWalletProxy(c.WALLET_PROXY_TIMEOUT);if(r&&n)try{let t=s.shouldCreateEmbeddedEthWallet(e,Z.embeddedWallets.ethereum.createOnLogin),a=s.shouldCreateEmbeddedSolWallet(e,Z.embeddedWallets.solana.createOnLogin);if(t&&a){let t=await Oe(e,c.WALLET_PROXY_TIMEOUT);await n.createSolana({accessToken:r,ethereumAddress:t?.address}),e=await Ke.refreshSessionAndUser()}else a?(await n.createSolana({accessToken:r,ethereumAddress:c.getPrivyEthereumWallet(e)?.address}),e=await Ke.refreshSessionAndUser()):t?(await Oe(e,c.WALLET_PROXY_TIMEOUT),e=await Ke.refreshSessionAndUser()):x(e)}catch(t){x(e),console.warn("Unable to create embedded wallet for guest account")}return P(t),v(!0),d.emitPrivyEvent(ye,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;fe.current=n;let{url:a,stateCode:s,codeVerifier:l}=await async function({api:e,appId:t}){let r=It(),n=Pt(),a=await jt(r);try{let{url:i}=await e.post(o.oAuthInitPath,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:a,state_code:n});return{url:i,stateCode:n,codeVerifier:r}}catch(e){throw i.formatApiError(e)}}({api:u.api,appId:e});if(!a)throw u.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new i.PrivyClientError("No authorization URL returned for cross-app auth.");try{let o=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,a=setTimeout((()=>{r(new i.PrivyClientError("Authorization request timed out after 2 minutes.")),o()}),12e4);function o(){t?.close(),window.removeEventListener("message",l)}let s=setInterval((()=>{t?.closed&&!n&&(o(),clearInterval(s),clearTimeout(a),r(new i.PrivyClientError("User rejected request")))}),300);function l(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(clearTimeout(a),e(t.data),o()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(a),r(new i.PrivyClientError(t.data.error)),o()),t.data.type===Wh&&((n=new BroadcastChannel(Oh)).onmessage=l))}window.addEventListener("message",l)}))}({url:a,popup:t,provider:n}),c=o.stateCode,d=o.authorizationCode;if(c!==s)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:s??"",returnedStateCode:c??""}}),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:a,client:o}){if(!n||!t)throw new i.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new i.PrivyClientError("User denied confirmation during cross-app auth flow");try{let i=new Lh({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});o.startAuthFlow(i);let s="link"===a?await o.link():await o.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=i.formatApiError(e);if(t.privyErrorCode)throw new i.PrivyClientError(t.message||"Invalid code during cross-app auth flow.",void 0,t.privyErrorCode);if("User denied confirmation during cross-app auth flow"===t.message)throw new i.PrivyClientError("Invalid code during cross-app auth flow.",void 0,i.PrivyErrorCode.OAUTH_USER_DENIED);throw new i.PrivyClientError("Invalid code during cross-app auth flow.",void 0,i.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:l,stateCode:c,authorizationCode:d,action:r,client:u});h&&u.storeProviderAccessToken(e,h);let p=await Ke.refreshSessionAndUser();if(!p)throw new i.PrivyClientError("Unable to update user");return u.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw u.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(fe.current=e,!d.e())return void Ee(c.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&ga(window.navigator.userAgent))return void Ee(c.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:Wh},"*"),d.i.del(c.HEADLESS_OAUTH_KEY),d.i.del(c.OAUTH_DISABLE_SIGNUP_KEY);let a=new kt({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&a.addCaptchaToken(t),u.startAuthFlow(a);let i=await u.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&n.isAndroid&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!g)throw new i.PrivyNotReadyError;fe.current="telegram";let r=new Zt(e,t);u.startAuthFlow(r),$({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>Z.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Z.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new i.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new i.PrivyClientError("Telegram was not initialized")):t(new i.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(u.authFlow instanceof Zt))throw new i.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");u.authFlow.meta.captchaToken||=e?.captchaToken;let n=await Qh(),a=e?.intent||we.current;if("login"===a)try{let e=await u.authenticate();t=e.user,r=e.isNewUser,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==a)throw new i.PrivyClientError("Unknown auth intent");try{t=(await u.link()).user,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}x(t),P(r||!1),v(!0),$({status:"done"});let o=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:o}},async recoveryOAuthFlow(e,t,r){let n,a;function o(t){if(!t)throw u.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new i.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,s,{url:l,codeVerifier:c,stateCode:d}=await Za({api:qh.api,provider:e});o(l);try{let n=await zh({url:l,popup:r,provider:e});if(t=n.stateCode,s=n.authorizationCode,t!==d)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:d??"",returnedStateCode:t??""}}),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw u.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new i.PrivyClientError("Recovery OAuth failed")}[n,a]=await Promise.all([Qh(),Xa({api:qh.api,provider:e,codeVerifier:c,stateCode:t,authorizationCode:s})]);break}case"icloud":{let{url:t}=await Za({api:qh.api,provider:e});o(t);let{ckWebAuthToken:i}=await zh({url:t,popup:r,provider:e});a=i,n=await Qh()}}if(!K)throw new i.PrivyClientError("Cannot connect to wallet proxy");if(!n)throw new i.PrivyClientError("Unable to authorize user");switch(t){case"recover":{let t=ee.recoverWallet?.entropyId,r=ee.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new i.PrivyClientError("Recovery OAuth failed");u.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await K.recover({accessToken:n,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:a}),u.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{u.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await K.create({accessToken:n,recoveryAccessToken:a,recoveryMethod:e});let t=c.getPrivyEthereumWallet(await Ke.refreshSessionAndUser());if(!t)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),d.emitPrivyEvent(ye,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=c.getPrivyPrimaryWallet(C);if(!t)throw d.emitPrivyEvent(ye,"setWalletRecovery","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");u.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(t);await K.setRecovery({accessToken:n,entropyId:r,entropyIdVerifier:o,recoveryMethod:e,recoveryAccessToken:a});let s=c.getPrivyPrimaryWallet(await Ke.refreshSessionAndUser());if(!s)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),d.emitPrivyEvent(ye,"setWalletRecovery","onSuccess",{method:e,wallet:s});break}default:throw new i.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,n;if(!(u.authFlow instanceof kt))throw new i.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let a=d.i.get(c.STATE_CODE_KEY),o=u.authFlow.meta.stateCode;if(a!==o)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:a??"",returnedStateCode:o??""}}),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await u.getAccessToken())try{let r=await u.link();t=r.user,n=r.oAuthTokens,fe.current=e}catch(t){throw d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let a=await u.authenticate();t=a.user,r=a.isNewUser,n=a.oAuthTokens,fe.current=e}catch(t){throw"login"===we.current?d.emitPrivyEvent(ye,"login","onError",t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return x(t),P(r||!1),v(!0),n&&t&&d.emitPrivyEvent(ye,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),n},passkeyAuthState:W,setPasskeyAuthState:L,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new $t({captchaToken:e,setPasskeyAuthState:L});u.startAuthFlow(r),we.current="login";try{fe.current="passkey",L({status:"generating-challenge"}),await r.initRegisterFlow(t),L({status:"awaiting-passkey"})}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof $t))throw new i.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current){let e=new i.PrivyClientError("Must init login with Passkey flow first.");throw L({status:"error",error:e}),e}let r=await Qh();try{fe.current="passkey",L({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await u.authenticate())}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}x(e),P(t||!1),v(!0),L({status:"done"});let n=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:n}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new $t({captchaToken:e,setPasskeyAuthState:L});u.startAuthFlow(r),we.current="login";try{fe.current="passkey",L({status:"generating-challenge"}),await r.initAuthenticationFlow(t),L({status:"awaiting-passkey"})}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof $t))throw new i.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(u.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==fe.current){let e=new i.PrivyClientError("Must init login with Passkey flow first.");throw L({status:"error",error:e}),e}let n=await Qh();try{fe.current="passkey",L({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await u.authenticate())}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}x(t),P(r||!1),v(!0),L({status:"done"});let a=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:a}},async initLinkWithPasskey(e){let t=new $t({captchaToken:e});u.startAuthFlow(t),we.current="link",fe.current="passkey",L({status:"generating-challenge"});try{await t.initLinkFlow(),L({status:"awaiting-passkey"})}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),L({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof $t))throw new i.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current)throw new i.PrivyClientError("Must init login with Passkey flow first.");try{fe.current="passkey",({user:e}=await u.link())}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return x(e||C||null),L({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!d.e())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&&ga(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 n=new kt({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&n.addCaptchaToken(t),V({status:"loading"});let a=await u.startAuthFlow(n).getAuthorizationUrl();a?.url&&window.location.assign(a.url)},async loginWithHeadlessOAuth(e){let t,r,n;M(!0),V({status:"loading"}),u.startAuthFlow(new kt(e));let a=d.i.get(c.STATE_CODE_KEY),o=e.stateCode;if(a!==o)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:a??"",returnedStateCode:o??""}}),M(!1),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await u.getAccessToken())try{({user:t,oAuthTokens:n}=await u.link()),fe.current=e.provider;let r=ze(t);t&&r&&d.emitPrivyEvent(ye,"linkAccount","onSuccess",{user:t,linkMethod:fe.current,linkedAccount:r})}catch(t){throw M(!1),d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await u.authenticate()),fe.current=e.provider;let a=ze(t);t&&a&&void 0!==r&&d.emitPrivyEvent(ye,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:fe.current,loginAccount:a})}catch(e){throw M(!1),V({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return x(t),P(r||!1),v(!0),M(!1),V({status:"done"}),n&&t&&d.emitPrivyEvent(ye,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{let a=new St({email:e,captchaToken:t,disableSignup:r});u.startAuthFlow(a);try{fe.current="email",F({status:"sending-code"}),await a.sendCodeEmail({withPrivyUi:n}),F({status:"awaiting-code-input"})}catch(e){throw F({status:"error",error:e}),"login"===we.current?d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let n=new Tt(e,t,r);u.startAuthFlow(n);try{await n.sendCodeEmail({withPrivyUi:!0})}catch(e){d.emitPrivyEvent(ye,"update","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:fe.current})}},initUpdatePhone:async(e,t,r)=>{let n=new Yt(e,t,r);u.startAuthFlow(n);try{await n.sendSmsCode({withPrivyUi:!0})}catch(e){d.emitPrivyEvent(ye,"update","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:fe.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{B({status:"sending-code"});let a=new Kt({phoneNumber:e,captchaToken:t,disableSignup:r});u.startAuthFlow(a);try{fe.current="sms",await a.sendSmsCode({withPrivyUi:n}),B({status:"awaiting-code-input"})}catch(e){throw B({status:"error",error:e}),"login"===we.current?d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(u.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(u.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function n(e){u.authFlow instanceof St?F(e):u.authFlow instanceof Kt&&B(e)}if(n({status:"submitting-code"}),!g){let e=new i.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(u.authFlow instanceof St)u.authFlow.meta.emailCode=e.trim();else{if(!(u.authFlow instanceof Kt)){let e=new i.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}u.authFlow.meta.smsCode=e.trim()}let a=await Qh();if("link"===we.current)try{({user:t}=await u.link())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:fe.current}),e}else if("update"===we.current)try{({user:t}=await u.link())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(ye,"update","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:fe.current}),e}else try{({user:t,isNewUser:r}=await u.authenticate())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let o=t||C;x(o||null),P(r||!1),v(!0),n({status:"done"});let s=null;return u.authFlow instanceof St?s=o?.linkedAccounts.find((({type:e})=>"email"===e))||null:u.authFlow instanceof Kt&&(s=o?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:o,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{we.current="link",fe.current="siwe",z({status:"generating-message"});let n=await u.generateSiweNonce({address:e,captchaToken:r});return z({status:"awaiting-signature"}),s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await u.generateSiweNonce({address:e});return s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let n;n=await u.linkSmartWallet({message:e,signature:t,smartWalletType:r}),x((n=await Ke.refreshSessionAndUser()??n)||C||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})=>{let o;ke("siwe");let s=null;try{z({status:"submitting-signature"}),o=await u.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}),o=await Ke.refreshSessionAndUser()??o,z({status:"done"}),(s=ze(o)||null)&&d.emitPrivyEvent(ye,"linkAccount","onSuccess",{user:o,linkMethod:"siwe",linkedAccount:s})}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),we.current=null,fe.current=null,z({status:"error",error:e}),e}let l=o||C;return x(l||null),we.current=null,fe.current=null,{user:l,linkedAccount:s}},refreshSessionAndUser:async()=>{let e=await u.getAuthenticatedUser();return v(!!e),x(e),e},walletProxy:K,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>u.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await u.acceptTerms();return x(e),e},getUsdTokenPrice:e=>u.getUsdTokenPrice(e),getUsdPriceForSol:()=>u.getUsdPriceForSol(),getSplTokenMetadata:e=>u.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let n=c.getPrivyPrimaryWallet(e?.user??C)||c.getImportedPrivyEthereumWallet(e?.user??C)||c.getImportedPrivySolanaWallet(e?.user??C);n||t(!0);let a=await Qh();if(!a||!K||!n)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));J(!0);let{entropyId:i,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);try{await K.connect({accessToken:a,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){Ba(e)&&"privy"===n.recoveryMethod?(u.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}}),(await K.recover({entropyId:i,entropyIdVerifier:o,accessToken:a})).entropyId||r(Error("Unable to recover wallet")),u.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)):Ba(e)&&"privy"!==n.recoveryMethod?(te({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover"}}),xe(Ya(n.recoveryMethod))):r(e)}})),embeddedSolanaWallets:b,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await Ke.refreshSessionAndUser();if(!t)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let n=c.getPrivyEthereumWallet(e),a=c.getPrivySolanaWallet(e),o=r&&"createAdditional"in r&&r.createAdditional,s=r&&"walletIndex"in r?r.walletIndex:void 0,l=(c.getLatestPrivySolanaWallet(e)?.walletIndex??-1)+1;if(a&&!o&&"number"!=typeof s)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof s&&s<0)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${s}) is invalid.`);let[u,h]=await Promise.all([Ke.initializeWalletProxy(t),Qh()]);if(!u||!h)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await Ue({user:e,wp:u,accessToken:h,walletIndex:s??l,ethereumWallet:n})})(t,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!w||!C)return void r(Error("User must be authenticated before exporting their Privy wallet"));let n=e?.address??c.getPrivySolanaWallet(C)?.address;if(!n)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:a,rootWallet:i}=c.getSolanaSigningAndRootWallet(C,n);if(!a||!i)return void r(Error("Must have a Privy wallet before exporting"));if(J(!0),!await Qh()||!K)return void r(Error("Must have valid access token to enroll in MFA"));if(!K)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=c.getEntropyDetailsFromAccount(i);te({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0},keyExport:{appId:l.appId,appClientId:l.clientId,origin:u.apiUrl,walletToExport:a,primaryWallet:i,onSuccess:t,onFailure:r}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{f(!0),re?.(e)},updateWallets:()=>Re(),fundWallet:async(e,t)=>{let r=c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;te({funding:d.prepareFundingModalData({address:e,appConfig:Z,fundWalletConfig:t,methodScreen:r})}),xe(r)},openModal:xe,requestFarcasterSignerStatus:async e=>{let t=await Qh(),r=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await u.requestFarcasterSignerStatus(e);return"approved"===n.status&&x(await u.getAuthenticatedUser()||C||null),n},connectCoinbaseSmartWallet:async()=>{Z.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=u.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||u.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),_e(e);await be("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await u.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return x(l),l}};Yh=Ke.recoverPrimaryWallet,Zh=Ke.recoverPrimaryWallet,Xh=Ke.solanaSignMessage;let Ye=r.useMemo((()=>({wallets:E,ready:oe&&me})),[E,oe,me]),Ze=u.authFlow instanceof Zt,Xe=!Z.headless&&Z.captchaEnabled&&!w&&(g||Ze);/*#__PURE__*/return e.jsx(c.PrivyContext.Provider,{value:$e,children:/*#__PURE__*/e.jsx(d.PrivyEventsContext.Provider,{value:ye,children:/*#__PURE__*/e.jsx(c.UseWalletsContext.Provider,{value:Ye,children:/*#__PURE__*/e.jsx(s.CaptchaProvider,{...Z,children:/*#__PURE__*/e.jsxs(i.InternalPrivyContext.Provider,{value:Ke,children:[/*#__PURE__*/e.jsx(s.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(c.ModalProvider,{data:ee,setModalData:te,setInitialScreen:k,initialScreen:j,authenticated:w,open:p,children:[l.children,Xe&&/*#__PURE__*/e.jsx(Gr,{delayedExecution:!1}),/*#__PURE__*/e.jsx(sh,{theme:{...Z.appearance.palette||{}}}),!Z.render.standalone&&/*#__PURE__*/e.jsx(vh,{open:p})]})}),Q&&X?/*#__PURE__*/e.jsx(kh,{appId:l.appId,appClientId:l.clientId,clientAnalyticsId:u.clientAnalyticsId,origin:u.apiUrl,mfaMethods:C?.mfaMethods,mfaPromise:he,mfaSubmitPromise:pe,onLoad:Y,onLoadFailed:()=>null}):null,Z.loginConfig.telegramAuthConfiguration&&
20
+ /*#__PURE__*/e.jsx("iframe",{ref:n,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>l(!0),src:s.constructURL(t.origin,`/apps/${t.appId}/embedded-wallets`,{caid:t.clientAnalyticsId,client_id:t.appClientId})})}const Nh=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));class Mh{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 ip({message:e.params.message,options:{address:this.address,uiOptions:{}}})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Qh())throw Error("User must be authenticated to use embedded Solana wallet");if(!await ap())throw new i.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}}const Rh=()=>{let e=c.useAppConfig();r.useEffect((()=>{(async e=>{let t=new URL("v3/wallets","https://explorer-api.walletconnect.com");t.searchParams.append("projectId",e);let r=await fetch(t);return r.ok?Object.values((await r.json()).listings).sort((({slug:e},{slug:t})=>"rainbow"===e&&"metamask"===t?1:"metamask"===e||"rainbow"===e?-1:1)):(console.debug(`Failed to fetch WalletConnect listings: ${await r.text().catch((()=>"No response."))}`),[])})(e.walletConnectCloudProjectId).then((e=>s.setExternalWalletState({listings:e}))).catch(console.error)}),[e.walletConnectCloudProjectId])},Oh="popup-privy-oauth",Wh="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class Lh{async authenticate(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw i.formatApiError(e)}}async link(){if(!this.api)throw new i.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw i.formatApiError(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function Uh({api:e,requesterAppId:t,providerAppId:r}){let n=(await e.get(`/api/v1/apps/${t}/cross-app/connections`)).connections.find((e=>e.provider_app_id===r));if(!n)throw new i.PrivyClientError("Invalid connected app");return{name:n.provider_app_name,logoUrl:n.provider_app_icon_url||void 0,apiUrl:n.provider_app_custom_api_url,readOnly:n.read_only}}const Fh=async({user:e,address:t,client:r,request:n,requesterAppId:a,reconnect:o})=>{r.createAnalyticsEvent({eventName:"cross_app_request_started",payload:{address:t,method:n.method}});let s=e?.linkedAccounts.find((e=>"cross_app"===e.type&&(e.embeddedWallets.some((e=>e.address===t))||e.smartWallets.some((e=>e.address===t)))));if(!e||!s)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Cannot request a signature with this wallet address",address:t}}),new i.PrivyClientError("Cannot request a signature with this wallet address");let l=r.getProviderAccessToken(s.providerApp.id),c=await Uh({api:r.api,requesterAppId:a,providerAppId:s.providerApp.id});if(!l){if(c.readOnly)throw console.error("cannot transact against a read-only provider app"),new i.PrivyClientError("Cannot transact against a read-only provider app");await o({appId:s.providerApp.id,action:"link"})&&(l=r.getProviderAccessToken(s.providerApp.id))}if(!l)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Transactions require a valid token",address:t}}),new i.PrivyClientError("Transactions require a valid token");let d=$s();if(!d)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new i.PrivyClientError("Failed to initialize signature request");let u=new URL(`${c.apiUrl}/oauth/transact`);return u.searchParams.set("token",l||""),u.searchParams.set("request",Dh(n)),d.location=u.href,new Promise(((e,a)=>{let o=setTimeout((()=>{u(),a(new i.PrivyClientError("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),l=setInterval((()=>{d.closed&&(u(),a(new i.PrivyClientError("User rejected request")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"User rejected request",address:t}}))}),300),c=i=>{i.data&&("set"===i.data.token?.action&&void 0!==i.data.token?.value?r.storeProviderAccessToken(s.providerApp.id,i.data.token.value):"clear"===i.data.token?.action&&r.storeProviderAccessToken(s.providerApp.id,null),"PRIVY_CROSS_APP_ACTION_RESPONSE"===i.data.type&&i.data.result&&(u(),e(i.data.result),r.createAnalyticsEvent({eventName:"cross_app_request_success",payload:{address:t,method:n.method}})),"PRIVY_CROSS_APP_ACTION_ERROR"===i.data.type&&i.data.error&&(u(),a(i.data.error),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:i.data.error,address:t}})))};window.addEventListener("message",c);let u=()=>{d.close(),clearInterval(l),clearTimeout(o),window.removeEventListener("message",c)}}))};let Dh=e=>JSON.stringify({content:{request:{request:Bh(e,y.toHex)}},timestamp:Date.now(),callbackUrl:window.origin});const Bh=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>Bh(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,Bh(r,t)]))):e,Hh=e=>!!e.fundingConfig&&d.filterSupportedOptions(e.fundingConfig.options).length>=1;async function zh({url:e,popup:t,provider:r}){return t.location=e,new Promise(((e,r)=>{function n(){t?.close(),window.removeEventListener("message",a)}function a(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(e(t.data),n()),"https://cdn.apple-cloudkit.com"===t.origin&&t.data.ckSession&&(e({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:t.data.ckSession}),n()),"PRIVY_OAUTH_ERROR"===t.data.type&&(r(t.data.error),n()))}window.addEventListener("message",a)}))}let qh,Vh,Gh,$h,Kh,Yh,Zh,Xh;async function Qh(){return qh?qh.getAccessToken():Promise.resolve(d.s.get(c.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||d.s.get(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const Jh=(e,t)=>Vh(e,t),ep=(e,t)=>Gh(e,t),tp=(e,t)=>$h(e,t),rp=(e,t)=>Kh(e,t),np=()=>Yh(),ap=()=>Zh(),ip=({message:e,options:t})=>Xh({message:e,options:t});let op=l=>{let u=l.client,h=d.usePlugins();Rh();let[p,y]=r.useState(!1),[g,f]=r.useState(!1),[w,v]=r.useState(!1),[C,x]=r.useState(null),[E,S]=r.useState([]),[T,A]=r.useState([]),[b,_]=r.useState([]),[I,P]=r.useState(!1),[j,k]=r.useState(null),[N,M]=r.useState(!1),[R,O]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:i.notImplemented}),[W,L]=r.useState({status:"initial"}),[U,F]=r.useState({status:"initial"}),[D,B]=r.useState({status:"initial"}),[H,z]=r.useState({status:"initial"}),[q,V]=r.useState({status:"initial"}),[G,$]=r.useState({status:"initial"}),[K,Y]=r.useState(null),Z=c.useAppConfig(),X=c.useIsServerConfigLoaded(),[Q,J]=r.useState(!0),[ee,te]=r.useState({}),[re,ne]=r.useState(null),[ae,ie]=r.useState(null),[oe,se]=r.useState(!1),[le,ce]=r.useState(!1),[de,ue]=r.useState(Z.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),he=r.useRef(null),pe=r.useRef(null),ye=r.useRef(d.privyEventsDefault),[me,ge]=r.useState(!1);u.onStoreCustomerAccessToken=e=>{e&&d.emitPrivyEvent(ye,"accessToken","onAccessTokenGranted",{accessToken:e})},u.onDeleteCustomerAccessToken=()=>{x(null),v(!1),d.emitPrivyEvent(ye,"accessToken","onAccessTokenRemoved")};let fe=r.useRef(null),we=r.useRef(null),ve=r.useRef(!1),Ce=({showWalletUIs:e})=>ve.current?ve.current:void 0!==e?!e:!Z.embeddedWallets.showWalletUIs,xe=e=>{k(e),setTimeout((()=>{y(!0)}),15)},Ee=e=>{("off"!==Z.embeddedWallets.ethereum.createOnLogin||"off"!==Z.embeddedWallets.solana.createOnLogin)&&J(!0),xe(e)};r.useEffect((()=>{let e=[...c.getPrivySolanaHDWallets(C),c.getImportedPrivySolanaWallet(C)].filter((e=>!!e));K&&_(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 i.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new i.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new Mh(K,e.address),async signMessage(t){let r=await Qh();if(!r||!K)throw new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.MUST_BE_AUTHENTICATED);let n=e.imported?c.getImportedPrivySolanaWallet(C):c.getPrivyPrimaryWallet(C);if(!n)throw new i.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);if(!await Ke.recoverPrimaryWallet().catch((()=>!1)))throw new i.PrivyClientError("Wallet couldn't be connected",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);if(!C)throw new i.PrivyClientError("Attempting to sign a transaction with no user initialized");let{response:s}=await K.rpc({accessToken:r,entropyId:a,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:e.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(s.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:n}=await Be({transaction:e,connection:t,transactionOptions:r,wallet:this,signOnly:!1});return n},async signTransaction(t){let r=await Qh();if(!r||!K)throw new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Ke.recoverPrimaryWallet().catch((()=>!1)))throw new i.PrivyClientError("Wallet couldn't be connected",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let n=e.imported?e:c.getPrivyPrimaryWallet(C);if(!n)throw new i.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);return await jd({tx:t,accessToken:r,walletProxy:K,entropyId:a,entropyIdVerifier:o,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0}),t},async signAllTransactions(t){let r=await Qh();if(!r||!K)throw new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Ke.recoverPrimaryWallet().catch((()=>!1)))throw new i.PrivyClientError("Wallet couldn't be connected",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let n=e.imported?e:c.getPrivyPrimaryWallet(C);if(!n)throw new i.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);for(let n of t)await jd({tx:n,accessToken:r,walletProxy:K,entropyId:a,entropyIdVerifier:o,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0});return t},loginOrLink:async()=>{throw new i.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[K,C]),r.useEffect((()=>{if(!C)return void u.connectors?.removeEmbeddedWalletConnectors();let e=c.getPrivyEthereumWallet(C),t=c.getPrivyEthereumHDWallets(C),r=c.getImportedPrivyEthereumWallet(C);e&&t.length||u.connectors?.removeEmbeddedWalletConnectors(),r||u.connectors?.removeImportedWalletConnector(),u.connectors?K?(e&&u.connectors.addEmbeddedWalletConnectors({walletProxy:K,rootWallet:e,embeddedWallets:t,defaultChain:Z.defaultChain,appId:l.appId}),r&&u.connectors.addImportedWalletConnector(K,r.address,Z.defaultChain,l.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")}),[K,C]),r.useEffect((()=>{K&&ae?.(K)}),[K]);let Se=r.useRef();r.useEffect((()=>{(async()=>{if(!Z.customAuth?.enabled)return void ue({status:"not-enabled"});J(!0);let{getCustomAccessToken:e,isLoading:t}=Z.customAuth;if(g&&!t&&"loading"!==de.status){ue({status:"loading"});try{let t=await e();if(t===Se.current)return void ue({status:"done"});if(!t&&w)return Se.current=t,await $e.logout(),ue({status:"done"}),void d.emitPrivyEvent(ye,"customAuth","onUnauthenticated");if(!t)return Se.current=t,void ue({status:"done"});u.startAuthFlow(new xt(t));let{user:r,isNewUser:n}=await u.authenticate();if(!r)return await $e.logout(),ue({status:"error",error:new i.PrivyClientError("Failed to sync with custom auth provider")}),void d.emitPrivyEvent(ye,"customAuth","onUnauthenticated");void 0!==n&&d.emitPrivyEvent(ye,"login","onComplete",{user:r,isNewUser:n,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),Se.current=t,d.emitPrivyEvent(ye,"customAuth","onAuthenticated",{user:r}),ue({status:"done"}),x(r||null),P(n||!1),v(!0),ce(!0)}catch(e){if(console.warn(e),await $e.logout(),d.emitPrivyEvent(ye,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void ue({status:"initial"});d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),ue({status:"error",error:e})}}})()}),["initial"===de.status,Z.customAuth?.enabled,Z.customAuth?.getCustomAccessToken,Z.customAuth?.isLoading,g,w]),r.useEffect((()=>{le&&K&&C&&(async()=>{let e=s.shouldCreateEmbeddedEthWallet(C,Z.embeddedWallets.ethereum.createOnLogin),t=s.shouldCreateEmbeddedSolWallet(C,Z.embeddedWallets.solana.createOnLogin),r=await Qh();if(r){if(e&&t){let e=await Oe(C,c.WALLET_PROXY_TIMEOUT);return await K.createSolana({accessToken:r,ethereumAddress:e?.address}),void ce(!1)}if(t)return await K.createSolana({accessToken:r,ethereumAddress:c.getPrivyEthereumWallet(C)?.address}),await Ke.refreshSessionAndUser(),void ce(!1);if(e)return await Oe(C,c.WALLET_PROXY_TIMEOUT),void ce(!1)}})().catch(console.error)}),[le&&K&&C]),r.useEffect((()=>{if(Z.externalWallets.solana.connectors)return Z.externalWallets.solana.connectors.onMount(),()=>Z.externalWallets.solana.connectors?.onUnmount()}),[Z.externalWallets.solana.connectors]),r.useEffect((()=>{!g&&X&&async function(){let e,r=Te(),n=Ae(),a=t.createStore();u.initializeConnectorManager({walletConnectCloudProjectId:Z.walletConnectCloudProjectId,rpcConfig:Z.rpcConfig,chains:Z.chains,defaultChain:Z.defaultChain,store:a,walletList:Z.appearance.walletList,shouldEnforceDefaultChainOnConnect:Z.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Z.externalWallets,appName:Z.name??"Privy",walletChainType:Z.appearance.walletChainType}),u.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=u.connectors.walletConnectors.length,r=u.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?ge(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),ge(!0)}),1500)})),u.connectors?.initialize().then((()=>{je()}));let i=await u.getAuthenticatedUser(),o=!!i;Z.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await u.logout(),Ke.setReadyToTrue(!0),d.emitPrivyEvent(ye,"logout","onSuccess")):(Z.customAuth?.enabled||(v(!!i),i&&d.emitPrivyEvent(ye,"login","onComplete",{user:i,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),x(i)),r?we.current=o?"link":"login":n&&!o?(we.current="login",te({telegramAuthModalData:{seamlessAuth:!0}}),Ee(c.ModalScreen.TELEGRAM_AUTH_SCREEN)):Ke.setReadyToTrue(!!i))}()}),[u,re,g,X]),r.useEffect((()=>{if(g){if(!C||!C.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void se(!0);se([...E,...b].some((e=>"privy"===e.walletClientType)))}}),[g,C,E,b]),r.useEffect((()=>{u.connectors?.setWalletList(Z.appearance.walletList)}),[Z.appearance.walletList.join()]);let Te=()=>{let e=Vt();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&&function(e){return e.startsWith("privy:")}(e.provider)&&!e.popupFlow&&(new BroadcastChannel(Oh).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(u.startAuthFlow(new kt(e)),Ee(c.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},Ae=()=>{let e=function(){let e;return(e=function(){let e=new URLSearchParams(window.location.search),t=Number(e.get("id")||""),r=e.get("hash"),n=Number(e.get("auth_date")||""),a=e.get("first_name");if(t&&a&&n&&r)return Object.fromEntries(e.entries())}())?(Jt(),{flowType:"login-url",authData:e}):(e=function(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=Qt(e.replace("#tgWebAppData=","")),{user:r,auth_date:n,hash:a}=t;return r&&n&&a?t:void 0}())?(Jt(),{flowType:"web-app",authData:e}):void 0}();if(!e||!Z.loginMethods.telegram||!Z.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Zt;return u.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},be=async(e,t,r,n)=>{if("solana_adapter"!==e)_e(await(u.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,n);else{let e=u.connectors?.findSolanaWalletConnector(t);if(!e)return;_e(e,t,r,n)}};async function _e(e,t,r,n){if(!e)return O({status:"disconnected",connectedWallet:null,connectError:new i.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:i.notImplemented}),n?.(null,r);O({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:i.notImplemented}),e instanceof s.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),O({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>_e(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||s.isBaseConnectedEthereumWallet(t))&&Z.shouldEnforceDefaultChainOnConnect&&!Z.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){O((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:i.notImplemented})));try{await(t?.switchChain(Z.defaultChain.id)),t&&(t.chainId=s.formatChainIdToCAIP2(s.toHex(Z.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Z.defaultChain.id}`)}}return O((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:i.notImplemented}))),t&&d.emitPrivyEvent(ye,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof i.PrivyError?(console.warn(e.cause?e.cause:e.message),d.emitPrivyEvent(ye,"connectWallet","onError",e.privyErrorCode||i.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),d.emitPrivyEvent(ye,"connectWallet","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),O((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Ie=async(e,t,r)=>{if(null===e||!s.isBaseConnectedEthereumWallet(e))return;let n=new s.SiweFlow(e,u,t,r);u.startAuthFlow(n)},Pe=async(e,t,r)=>{if(null===e||!d.isBaseConnectedSolanaWallet(e))return;let n=new s.SiwsFlow(e,u,t,r);u.startAuthFlow(n)},je=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),n="true"===e.get("privy_connect_only");if(!t||!r)return;let a=_r({connectorType:t,walletClientType:r});if(!a||!a.isInstalled)return Ee(c.ModalScreen.LOGIN_FAILED_SCREEN);if(!u.connectors)throw new i.PrivyClientError("Connector not initialized");xe(n?c.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION:c.ModalScreen.AWAITING_CONNECTION);let o=new URL(window.location.href);o.searchParams.delete("privy_connector"),o.searchParams.delete("privy_wallet_client"),o.searchParams.delete("privy_connect_only"),window.history.pushState({},"",o),be(t,r,void 0,n?void 0:"solana_adapter"===t?Pe:Ie)};r.useEffect((()=>{g&&w&&null===C&&u.getAuthenticatedUser().then(x)}),[g,w,C,u]);let ke=e=>{if(!w)throw d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new i.PrivyClientError("User must be authenticated before linking an account.")},Ne=e=>{if(!w||!C)return!1;if("privy"===e.walletClientType)return!0;for(let t of C.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Me=async e=>{let t;if(!u.connectors)throw new i.PrivyClientError("Connector not initialized");t="ethereum"===e.type?u.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:u.connectors.findSolanaWalletConnector(e.walletClientType)||null,O((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:i.notImplemented}))),Z.captchaEnabled&&!w?(te({captchaModalData:{callback:t=>s.isBaseConnectedEthereumWallet(e)?Ie(e,t):Pe(e,t),userIntentRequired:!1,onSuccessNavigateTo:c.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:c.ModalScreen.ERROR_SCREEN}}),Ee(c.ModalScreen.CAPTCHA_SCREEN)):(s.isBaseConnectedEthereumWallet(e)?await Ie(e):await Pe(e),Ee(c.ModalScreen.AWAITING_CONNECTION))},Re=()=>{S((e=>{let t=u.connectors?.wallets.filter(s.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Ne(e),loginOrLink:async()=>{if(!await e.isConnected())throw new i.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot link or login with embedded wallet");Me(e)},fund:async t=>{await Ke.fundWallet(e.address,t)},unlink:async()=>{if(!w)throw new i.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot unlink an embedded wallet");x(await u.unlinkEthereumWallet(e.address))}})))||[];return s.areWalletArraysEqual(e,t)?e:t})),A((e=>{let t=(u.connectors?.wallets??[]).filter(d.isBaseConnectedSolanaWallet).map((e=>({...e,linked:Ne(e),loginOrLink:async()=>{if(!await e.isConnected())throw new i.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot link or login with embedded wallet");Me(e)},fund:async()=>{throw new i.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!w)throw new i.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new i.PrivyClientError("Cannot unlink an embedded wallet");x(await u.unlinkSolanaWallet(e.address))}})));return s.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{Re()}),[C?.linkedAccounts,w,g]),r.useEffect((()=>{if(g){if(!u.connectors)throw new i.PrivyClientError("Connector not initialized");Re(),u.connectors.on("walletsUpdated",Re)}}),[g]),r.useEffect((()=>{[...Z.loginMethodsAndOrder?.primary??[],...Z.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>u.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!u]);let Oe=async(e,t,r)=>{let n=c.getPrivyEthereumWallet(e),a=c.getPrivySolanaWallet(e);if(r&&"walletIndex"in r&&"number"==typeof r.walletIndex)return Le(e,t,r.walletIndex,n,a);let o=r&&"createAdditional"in r&&r.createAdditional;if(n&&!o)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[s,l]=await Promise.all([Ke.initializeWalletProxy(t),Qh()]);if(!s&&Z.customAuth?.enabled)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!s||!l||Z.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return We();if(!n)return a&&await Ke.recoverPrimaryWallet(),await s.create({accessToken:l,solanaAddress:a?.address}),Fe(0,"ethereum");{let t=(c.getLatestPrivyEthereumWallet(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:n}=c.getEntropyDetailsFromAccount(c.getPrivyPrimaryWallet(e));return await Ke.recoverPrimaryWallet(),await s.addWallet({accessToken:l,entropyId:r,entropyIdVerifier:n,chainType:"ethereum",hdWalletIndex:t}),Fe(t,"ethereum")}},We=async()=>new Promise(((e,t)=>{J(!0),te({createWallet:{onSuccess:t=>{d.emitPrivyEvent(ye,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),xe(c.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),Le=async(e,t,r,n,a)=>{if(r<0)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[o,s]=await Promise.all([Ke.initializeWalletProxy(t),Qh()]);if(!o&&Z.customAuth?.enabled)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||Z.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return We();throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==r){if(n)return n;await o.create({accessToken:s,solanaAddress:a?.address})}else{if(!n)throw d.emitPrivyEvent(ye,"createWallet","onError",i.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=c.getPrivyEthereumHDWallets(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:a,entropyIdVerifier:l}=c.getEntropyDetailsFromAccount(c.getPrivyPrimaryWallet(e));await Ke.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:a,entropyIdVerifier:l,chainType:"ethereum",hdWalletIndex:r})}return Fe(r,"ethereum")},Ue=async({user:e,wp:t,accessToken:r,walletIndex:n,ethereumWallet:a})=>{let o=c.getPrivySolanaHDWallets(e).find((e=>e.walletIndex===n));if(o)return o;if(0===n)a&&await Ke.recoverPrimaryWallet(),await t.createSolana({accessToken:r,ethereumAddress:a?.address});else{let a=c.getPrivyPrimaryWallet(e);if(!a)throw d.emitPrivyEvent(ye,"createWallet","onError",i.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:o,entropyIdVerifier:s}=c.getEntropyDetailsFromAccount(a);await Ke.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:o,entropyIdVerifier:s,chainType:"solana",hdWalletIndex:n})}return Fe(n,"solana")},Fe=async(e,t)=>{let r=await Ke.refreshSessionAndUser(),n=("ethereum"===t?c.getPrivyEthereumHDWallets(r):c.getPrivySolanaHDWallets(r)).find((t=>t.walletIndex===e));if(!n)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return d.emitPrivyEvent(ye,"createWallet","onSuccess",{wallet:n}),n},De=({transaction:e,uiOptions:t,fundWalletConfig:r,address:n,signOnly:o})=>new Promise((async(s,u)=>{let{requesterAppId:h}=t||{},p=o?"signTransaction":"sendTransaction";if(!w||!C)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void u(Error("User must be authenticated before signing with a Privy wallet"));let y=n??c.getPrivyEthereumWallet(C)?.address;if(!y)throw new i.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:g,rootWallet:f}=c.getEthereumSigningAndRootWallet(C,y);if(!f||!g)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have a Privy wallet before signing"));J(!0);let v=Ye.wallets.find((e=>"privy"===e.walletClientType&&a.getAddress(e.address)===a.getAddress(g.address))),x=await(v?.getEthereumProvider());if(!v||!x)throw new i.PrivyClientError(`Cannot sendTransaction before embedded wallet ${g.address} is connected`);let E=e.chainId?Number(e.chainId):d.extractChainIdFromCAIP2(v.chainId);(e=>{if(!Z.chains.map((e=>e.id)).includes(e))throw new i.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,i.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(E);let S={...e,from:e.from??g.address,chainId:E},T=await Qh();if(!T||!K)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(Error("Must have valid access token and Privy wallet to send transaction"));let A=m.getPublicClient(S.chainId,Z.chains,Z.rpcConfig,{appId:l.appId});if(Ce({showWalletUIs:t?.showWalletUIs}))(async()=>{try{if(!await Ke.recoverPrimaryWallet())return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void u(Error("Unable to connect to wallet"));let e=await ld(S,A,S.from),{entropyId:t,entropyIdVerifier:r}=c.getEntropyDetailsFromAccount(f),n=o?await Cu({accessToken:T,entropyId:t,entropyIdVerifier:r,transactingWallet:g,walletProxy:K,transactionRequest:S,requesterAppId:h}):await vu({accessToken:T,entropyId:t,entropyIdVerifier:r,transactingWallet:g,walletProxy:K,transactionRequest:e,publicClient:A,requesterAppId:h});o?d.emitPrivyEvent(ye,"signTransaction","onSuccess",{signature:n}):d.emitPrivyEvent(ye,"sendTransaction","onSuccess",{hash:n}),s({hash:n})}catch(e){d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)}})();else{let{entropyId:e,entropyIdVerifier:n}=c.getEntropyDetailsFromAccount(f),a={entropyId:e,entropyIdVerifier:n,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}},l=Hh(Z)?d.prepareFundingModalData({address:g.address,appConfig:Z,fundWalletConfig:r,methodScreen:c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:S.chainId,comingFromSendTransactionScreen:!0}):void 0;te({connectWallet:a,sendTransaction:{transactionRequest:S,transactingWallet:g,entropyId:e,entropyIdVerifier:n,signOnly:o,onConfirm:o?async()=>await Cu({accessToken:T,entropyId:e,entropyIdVerifier:n,transactingWallet:g,walletProxy:K,transactionRequest:S,requesterAppId:h}):void 0,onSuccess:e=>{o?d.emitPrivyEvent(ye,"signTransaction","onSuccess",{signature:e.hash}):d.emitPrivyEvent(ye,"sendTransaction","onSuccess",{hash:e.hash}),s(e)},onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)},uiOptions:t||{},fundWalletConfig:r,requesterAppId:h},funding:l}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),Be=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:n,uiOptions:a,wallet:o,signOnly:s})=>new Promise((async(l,u)=>{let{requesterAppId:h}=a||{},p=s?"signSolanaTransaction":"sendSolanaTransaction";if(!w||!C)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void u(new i.PrivyClientError("User must be authenticated before signing with a Privy wallet",i.PrivyErrorCode.MUST_BE_AUTHENTICATED));let y=o?C.linkedAccounts.find((e=>"wallet"===e.type&&e.address===o.address)):c.getPrivySolanaWallet(C);if(!y)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(new i.PrivyClientError("Must have a Privy wallet before signing",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));J(!0);let{rootWallet:m}=c.getSolanaSigningAndRootWallet(C,y.address);if(!await Ke.recoverPrimaryWallet().catch((()=>!1))||!m)throw d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new i.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${y.address} is connected`,i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);if(Ce({showWalletUIs:a?.showWalletUIs}))(async()=>{let n=await Qh();if(!n||!K)return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void u(new i.PrivyClientError("Must have valid access token and Privy wallet to send transaction",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{let o;if(!await Ke.recoverPrimaryWallet())return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void u(new i.PrivyClientError("Unable to connect to wallet",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Ce({showWalletUIs:a?.showWalletUIs})&&!s)try{if(!await async function(e,t){let{value:r}=await t.simulateTransaction(e);if("BlockhashNotFound"===r.err)throw Error("Simulation failed: Blockhash not found");return null==r.err&&r.logs?.every((e=>!/insufficient funds/gi.test(e)))}(e,t))return d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.INSUFFICIENT_BALANCE),void u(new i.PrivyClientError("Solana wallet has insufficient funds for this transaction.",i.PrivyErrorCode.INSUFFICIENT_BALANCE))}catch(e){return console.error(e),d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),void u(new i.PrivyClientError(e instanceof Error?e.message:"Transaction failed.",i.PrivyErrorCode.TRANSACTION_FAILURE))}let{entropyId:h,entropyIdVerifier:m}=c.getEntropyDetailsFromUser(C);if(s)await jd({accessToken:n,tx:e,walletProxy:K,entropyId:h,entropyIdVerifier:m,transactingWalletAddress:y.address,transactingWalletIndex:y.walletIndex??0}),o=Wo("",e,null),d.emitPrivyEvent(ye,"signSolanaTransaction","onSuccess",{signedTransaction:e});else{let{signature:a,receipt:i}=await kd({accessToken:n,tx:e,connection:t,walletProxy:K,transactionOptions:r,entropyId:h,entropyIdVerifier:m,transactingWalletAddress:y.address,transactingWalletIndex:y.walletIndex??0});o=Wo(a,e,i),d.emitPrivyEvent(ye,"sendSolanaTransaction","onSuccess",{response:o})}l(o)}catch(e){d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)}})();else{let{entropyId:o,entropyIdVerifier:g}=c.getEntropyDetailsFromAccount(m),f={entropyId:o,entropyIdVerifier:g,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}},w=Hh(Z)?d.prepareSolanaFundingModalData({address:y.address,appConfig:Z,methodScreen:c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:n,comingFromSendTransactionScreen:!0}):void 0;te({connectWallet:f,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:y,onSuccess:e=>{s?d.emitPrivyEvent(ye,"signSolanaTransaction","onSuccess",{signedTransaction:e.signedTransaction}):d.emitPrivyEvent(ye,"sendSolanaTransaction","onSuccess",{response:e}),l(e)},onFailure:e=>{d.emitPrivyEvent(ye,p,"onError",i.PrivyErrorCode.TRANSACTION_FAILURE),u(e)},uiOptions:a||{},requesterAppId:h,signOnly:s},funding:w}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function He(){return new Promise((async(e,t)=>{let r=await Qh();if(!r||!K)throw Error("Must have valid access token to enroll in MFA");try{await K.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let ze=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],qe=e=>{let t=C?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=wl(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new i.PrivyClientError(`User already has an account of type ${r} linked.`)};async function Ve({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){k(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!w||!C)throw d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=c.getPrivyPrimaryWallet(C);if(!n||!K)throw d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await He()}catch(e){throw d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((a,o)=>{J(!0);let s={onSuccess:e=>{d.emitPrivyEvent(ye,r,"onSuccess",{method:"user-passcode",wallet:e}),a(e)},onFailure:e=>{d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),o(e)},callAuthOnSuccessOnClose:!1},l="user-passcode"===n.recoveryMethod,u=Ka({walletAction:"update",availableRecoveryMethods:Z.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:l,showAutomaticRecovery:e}),{entropyId:h,entropyIdVerifier:p}=c.getEntropyDetailsFromAccount(n);te({setWalletPassword:s,recoverWallet:{entropyId:h,entropyIdVerifier:p,onFailure:o},createWallet:s,connectWallet:{onCompleteNavigateTo:u,shouldForceMFA:!1,entropyId:h,entropyIdVerifier:p,onFailure:e=>{d.emitPrivyEvent(ye,r,"onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:l}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function Ge({appId:e,action:t}){let r=await Qh();if("link"===t&&!r)throw d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new i.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw d.emitPrivyEvent(ye,"login","onError",i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new i.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");fe.current=`privy:${e}`,we.current=t;let n=$s();return u.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,a)=>{let{name:i,logoUrl:o}=await Uh({api:u.api,providerAppId:e,requesterAppId:Z.id});te({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:n,onSuccess:r,onError:a}}),Ee(c.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let $e={ready:g,authenticated:w,user:C,walletConnectors:u.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),te({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress,walletChainType:e?.walletChainType}}),xe(w?c.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:c.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),ke("siwe"),fe.current="siwe",we.current="link",te({...ee,externalConnectWallet:{...ee.externalConnectWallet,suggestedAddress:e?.suggestedAddress,walletList:e?.walletList,walletChainType:e?.walletChainType}}),xe(c.ModalScreen.LINK_WALLET_SCREEN)},startCrossAppAuthFlow:Ge,linkEmail:()=>{ke("email"),qe("email"),fe.current="email",we.current="link",xe(c.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{ke("sms"),qe("phone"),fe.current="sms",we.current="link",xe(c.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{ke("google"),qe("google_oauth"),we.current="link",await Ke.initLoginWithOAuth("google")},linkTwitter:async()=>{ke("twitter"),qe("twitter_oauth"),we.current="link",await Ke.initLoginWithOAuth("twitter")},linkDiscord:async()=>{ke("discord"),qe("discord_oauth"),we.current="link",await Ke.initLoginWithOAuth("discord")},linkGithub:async()=>{ke("github"),qe("github_oauth"),we.current="link",await Ke.initLoginWithOAuth("github")},linkSpotify:async()=>{ke("spotify"),qe("spotify_oauth"),we.current="link",await Ke.initLoginWithOAuth("spotify")},linkInstagram:async()=>{ke("instagram"),qe("instagram_oauth"),we.current="link",await Ke.initLoginWithOAuth("instagram")},linkTiktok:async()=>{ke("tiktok"),qe("tiktok_oauth"),we.current="link",await Ke.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{ke("linkedin"),qe("linkedin_oauth"),we.current="link",await Ke.initLoginWithOAuth("linkedin")},linkApple:async()=>{ke("apple"),qe("apple_oauth"),we.current="link",await Ke.initLoginWithOAuth("apple")},linkPasskey:async()=>{ke("passkey"),qe("passkey"),await Ke.initLinkWithPasskey(),xe(c.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if(ke("telegram"),qe("telegram"),we.current="link",fe.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new Zt;u.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=Qt(e.launchParams.initDataRaw),te({telegramAuthModalData:{seamlessAuth:!0}}),Ee(c.ModalScreen.TELEGRAM_AUTH_SCREEN)}else d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await Ke.initLoginWithTelegram();xe(c.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{ke("farcaster"),qe("farcaster"),await Ke.initLoginWithFarcaster(),we.current="link",fe.current="farcaster",xe(c.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(ke("email"),!C?.email)throw new i.PrivyClientError("User does not have an email linked to their account.");we.current="update",fe.current="email",xe(c.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(ke("sms"),!C?.phone)throw new i.PrivyClientError("User does not have a phone number linked to their account.");we.current="update",fe.current="sms",xe(c.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(!g){let e=await new Promise((e=>{ne((t=>e.bind(t)))}));if(ne(null),e)return void console.warn(t)}!C||C.isGuest?(we.current="login",te({login:e}),Ee(c.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{g||(await new Promise((e=>{ne((()=>e))})),ne(null)),w?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(we.current="login",Ee(c.ModalScreen.CONNECT_OR_CREATE))},logout:async()=>{if(we.current=null,fe.current=null,C&&u.clearProviderAcccessTokens(C),k(null),await u.logout(),C&&K)try{await K.clearMfa({userId:C.id})}catch(e){}x(null),v(!1),d.emitPrivyEvent(ye,"logout","onSuccess"),y(!1),d.s.del(c.CLIENT_ANALYTICS_ID_KEY),d.s.del(c.getGuestCredentialStorageKey(Z.id))},getAccessToken:r.useCallback((()=>u.getCustomerAccessToken()),[u]),unlinkWallet:async e=>{let t;return x(t=e.startsWith("0x")?await u.unlinkEthereumWallet(e):await u.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await u.unlinkEmail(e);return x(t),t},unlinkPhone:async e=>{let t=await u.unlinkPhone(e);return x(t),t},unlinkGoogle:async e=>{let t=await u.unlinkOAuth("google",e);return x(t),t},unlinkTwitter:async e=>{let t=await u.unlinkOAuth("twitter",e);return x(t),t},unlinkDiscord:async e=>{let t=await u.unlinkOAuth("discord",e);return x(t),t},unlinkGithub:async e=>{let t=await u.unlinkOAuth("github",e);return x(t),t},unlinkSpotify:async e=>{let t=await u.unlinkOAuth("spotify",e);return x(t),t},unlinkInstagram:async e=>{let t=await u.unlinkOAuth("instagram",e);return x(t),t},unlinkTiktok:async e=>{let t=await u.unlinkOAuth("tiktok",e);return x(t),t},unlinkLinkedIn:async e=>{let t=await u.unlinkOAuth("linkedin",e);return x(t),t},unlinkApple:async e=>{let t=await u.unlinkOAuth("apple",e);return x(t),t},unlinkFarcaster:async e=>{let t=await u.unlinkFarcaster(e);return x(t),t},unlinkTelegram:async e=>{let t=await u.unlinkTelegram(e);return x(t),t},unlinkPasskey:async e=>{let t=await Qh();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!K)throw Error("Wallet proxy not initialized.");let r=Z.passkeys.shouldUnenrollMfaOnUnlink;await K.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let n=await u.getAuthenticatedUser();return x(n),n},unlinkCrossAppAccount:async({subject:e})=>{let t=C?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new i.PrivyClientError("Invalid subject");u.storeProviderAccessToken(t.id,null);let r=await u.unlinkOAuth(`privy:${t.id}`,e);return x(r),r},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await Ke.refreshSessionAndUser();if(!t)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return Oe(t,15e3,e)},setWalletRecovery:async e=>Ve({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>Ve({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:a}=t?.uiOptions||{},o=e.message;if(!w||!C)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let s=t?.address??c.getPrivyEthereumWallet(C)?.address;if(!s)throw new i.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=c.getEthereumSigningAndRootWallet(C,s);if(!l||!h)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof o||o.length<1)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));J(!0);let p=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Qh();if(!K||!e||!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:l.address,requesterAppId:a}});let{entropyId:t,entropyIdVerifier:r}=c.getEntropyDetailsFromAccount(h),{response:n}=await K.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:l.walletIndex??0,requesterAppId:a,request:{method:"personal_sign",params:[o,l.address]}}),i=n.data;return u.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:l.address,requesterAppId:a}}),i};if(Ce({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await p();d.emitPrivyEvent(ye,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new d.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"personal_sign",data:o,confirmAndSign:p,onSuccess:e=>{d.emitPrivyEvent(ye,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},{entropyId:a,entropyIdVerifier:s}=c.getEntropyDetailsFromAccount(h);te({signMessage:e,connectWallet:{entropyId:a,entropyIdVerifier:s,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:a}=t?.uiOptions||{};if(!w||!C)return d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let o=t?.address??c.getPrivyEthereumWallet(C)?.address;if(!o)throw new i.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:l,rootWallet:h}=c.getEthereumSigningAndRootWallet(C,o);if(!h||!l)return d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));J(!0);let p=s.generateTypedDataWithDomainType(e),y=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Qh();if(!K||!e||!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:l.address,requesterAppId:a}});let{entropyId:t,entropyIdVerifier:r}=c.getEntropyDetailsFromAccount(h),{response:n}=await K.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:l.walletIndex??0,requesterAppId:a,request:{method:"eth_signTypedData_v4",params:[l.address,p]}}),i=n.data;return u.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:l.address,requesterAppId:a}}),i};if(Ce({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await y();d.emitPrivyEvent(ye,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new d.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:p,confirmAndSign:y,onSuccess:e=>{d.emitPrivyEvent(ye,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{d.emitPrivyEvent(ye,"signTypedData","onError",i.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},{entropyId:a,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(h);te({signMessage:e,connectWallet:{entropyId:a,entropyIdVerifier:o,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t)=>await De({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await De({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!w||!C)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let n=e?.address??c.getPrivyEthereumWallet(C)?.address;if(!n)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`."));if(!a.isAddress(n))return void r(Error("Must provide a valid Ethereum address."));let{signingWallet:i,rootWallet:o}=c.getEthereumSigningAndRootWallet(C,n);if(!i||!o)return void r(Error("Must have a Privy wallet before exporting"));J(!0);let{entropyId:s,entropyIdVerifier:d}=c.getEntropyDetailsFromAccount(o),h={entropyId:s,entropyIdVerifier:d,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0};te(ee),await Qh()&&K?K?(te({keyExport:{appId:l.appId,appClientId:l.clientId,origin:u.apiUrl,walletToExport:i,primaryWallet:o,onSuccess:t,onFailure:r},connectWallet:h}),xe(c.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:He,async init(e){switch(e){case"sms":return void await u.initMfaSmsVerification();case"passkey":return await u.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 i.PrivyClientError("Invalid MFA code");he.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{pe.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new i.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=(e=>({id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}))(await r.startAuthentication(t));he.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{pe.current={resolve:e,reject:t}}));break;default:throw he.current?.reject(new i.PrivyClientError("Unsupported MFA method")),new i.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){he.current?.reject(new i.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Qh();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Ke.closePrivyModal(),void t();Z.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."),te({mfaEnrollmentFlow:{mfaMethods:Z.mfa.methods,shouldUnlinkOnUnenrollMfa:Z.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),xe(c.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await Qh();if(!e||!K)throw Error("Must have valid access token to enroll in MFA");let t=await K.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Qh();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),x(await u.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Qh();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),x(await u.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await Qh();if(!r||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),x(await u.getAuthenticatedUser())},async unenroll(e,t={}){let r=await Qh();if(!r||!K)throw Error("Must have valid access token to remove MFA");"passkey"===e?await K.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await K.unenrollMfa({method:e,accessToken:r}),x(await u.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Qh(),t=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!K||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await K.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&x(await u.getAuthenticatedUser()||C||null),te({farcasterSigner:r}),xe(c.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await Qh(),r=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!C.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=C.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Qh(),r=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!C.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),a=await K.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(C.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(a.signature))},createGuestAccount:async()=>{if(C&&!C.isGuest)throw Error("User cannot already be authenticated to create a guest account");return C?.isGuest?C:Ke.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let n=C?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Fh({user:C,client:u,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:Ge})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let n=C?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),a=s.generateTypedDataWithDomainType(e);return Fh({user:C,client:u,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,a],chainId:r},reconnect:Ge})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=C?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Fh({user:C,client:u,address:t,requesterAppId:Z.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:Ge})},isModalOpen:p,mfaMethods:Z.mfa.methods};Vh=$e.signMessage,Gh=$e.signTypedData,Kh=async(e,t)=>await De({transaction:e,...t,signOnly:!1}),$h=async(e,t)=>({signature:(await De({transaction:e,...t,signOnly:!0})).hash});let Ke={setAuthenticated:v,setUser:x,isNewUserThisSession:I,pendingTransaction:null,walletConnectionStatus:R,connectors:u.connectors?.walletConnectors??[],solanaWallets:T,rpcConfig:Z.rpcConfig,chains:Z.chains,appId:l.appId,showFiatPrices:"native-token"!==Z.embeddedWallets.priceDisplay.primary,clientAnalyticsId:u.clientAnalyticsId,customAuthStatus:de,hideWalletUIs:ve,isHeadlessSigning:r.useCallback(Ce,[Z.embeddedWallets.showWalletUIs]),emailOtpState:U,setEmailOtpState:F,smsOtpState:D,setSmsOtpState:B,oAuthState:q,setOAuthState:V,telegramAuthState:G,setTelegramAuthState:$,siweState:H,setSiweState:z,isHeadlessOAuthLoading:N,nativeTokenSymbolForChainId:e=>Z.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(K)return K;let t=new Promise((e=>{ie((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return ie(null),n},getAuthFlow:()=>u.authFlow,getAuthMeta:()=>u.authFlow?.meta,client:u,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=g&&w&&C;r&&fe.current&&(t=ze(C)),"login"===we.current?e.shouldCallAuthOnSuccess&&r&&fe.current?d.emitPrivyEvent(ye,"login","onComplete",{user:C,isNewUser:I,wasAlreadyAuthenticated:!1,loginMethod:fe.current,loginAccount:t??null}):d.emitPrivyEvent(ye,"login","onError",i.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===we.current&&t?e.isSuccess&&r&&fe.current?d.emitPrivyEvent(ye,"linkAccount","onSuccess",{user:C,linkMethod:fe.current,linkedAccount:t}):fe.current&&d.emitPrivyEvent(ye,"linkAccount","onError",i.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:fe.current}):"update"===we.current&&t&&(e.isSuccess&&r&&fe.current?d.emitPrivyEvent(ye,"update","onSuccess",{user:C,updateMethod:fe.current,updatedAccount:t}):fe.current&&d.emitPrivyEvent(ye,"update","onError",i.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:fe.current}));let n=j&&Ms.includes(j),a=j===c.ModalScreen.ERROR_SCREEN&&ee.errorModalData&&Ms.includes(ee.errorModalData.previousScreen);if((n||a)&&ee.funding){let e,t=Rs[j]??null;if("solana"===ee.funding.chainType){let r=h(d.SOLANA_FUNDING_PLUGIN_ID);if(r)try{e=BigInt(await r.getBalance({address:ee.funding.address,cluster:ee.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");d.emitPrivyEvent(ye,"fundSolanaWallet","onUserExited",{address:ee.funding.address,cluster:ee.funding.cluster,fundingMethod:t,balance:e})}else{let r=m.getPublicClient(ee.funding.chain.id,Z.chains,Z.rpcConfig,{appId:l.appId});try{e=await r.getBalance({address:ee.funding.address})}catch{console.error("Unable to pull wallet balance")}d.emitPrivyEvent(ye,"fundWallet","onUserExited",{address:ee.funding.address,chain:ee.funding.chain,fundingMethod:t,balance:e})}}te({...ee,externalConnectWallet:{suggestedAddress:void 0}}),we.current=null,fe.current=null,P(!1),y(!1),setTimeout((()=>{u.authFlow=void 0}),200)},solanaSignMessage:({message:e,options:t})=>new Promise((async(r,n)=>{if(!w||!C)return d.emitPrivyEvent(ye,"signSolanaMessage","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let a=t?.address??c.getPrivySolanaWallet(C)?.address;if(!a)throw new i.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:o,rootWallet:s}=c.getSolanaSigningAndRootWallet(C,a);if(!o||!s)return d.emitPrivyEvent(ye,"signSolanaMessage","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return d.emitPrivyEvent(ye,"signMessage","onError",i.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));J(!0);let l=async()=>{if(!w)throw Error("User must be authenticated before signing with a Privy wallet");let t=await u.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=Ke.walletProxy??await Ke.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await Ke.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!s)throw Error("No root wallet for signing wallet found");let{entropyId:n,entropyIdVerifier:a}=c.getEntropyDetailsFromUser(C),{response:i}=await r.rpc({accessToken:t,entropyId:n,entropyIdVerifier:a,chainType:"solana",hdWalletIndex:o.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return i.data.signature};if(Ce({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await l();d.emitPrivyEvent(ye,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})}catch(e){n(e)}else{let a={method:"solana_signMessage",data:e,confirmAndSign:l,onSuccess:e=>{d.emitPrivyEvent(ye,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})},onFailure:e=>{n(e)},uiOptions:t?.uiOptions},{entropyId:o,entropyIdVerifier:u}=c.getEntropyDetailsFromAccount(s);te({signMessage:a,connectWallet:{entropyId:o,entropyIdVerifier:u,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{d.emitPrivyEvent(ye,"signSolanaMessage","onError",i.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),Ee(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:n,address:a})=>{let o=a?b.find((e=>e.address===a)):b.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw d.emitPrivyEvent(ye,"signSolanaTransaction","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new i.PrivyClientError("Embedded wallet not found",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);let{signedTransaction:s}=await Be({transaction:e,connection:t,transactionOptions:n,uiOptions:r,wallet:o,signOnly:!0});return s},sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:n,fundWalletConfig:a,address:o})=>{let s=o?b.find((e=>e.address===o)):b.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!s)throw d.emitPrivyEvent(ye,"sendSolanaTransaction","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new i.PrivyClientError("Embedded wallet not found",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);return await Be({transaction:e,connection:t,transactionOptions:n,uiOptions:r,fundWalletConfig:a,wallet:s,signOnly:!1})},openPrivyModal:xe,connectWallet:_e,initLoginWithWallet:async(e,t,r)=>{s.isBaseConnectedEthereumWallet(e)?(fe.current="siwe",Ie(e,t,r)):(fe.current="siws",Pe(e,t,r))},loginWithWallet:async()=>{let e,t,r;if(!g)throw new i.PrivyNotReadyError;if(u.authFlow instanceof s.SiweFlow?e="siwe":u.authFlow instanceof s.SiwsFlow&&(e="siws"),!e)throw new i.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await u.getAccessToken())try{({user:t}=await u.link()),fe.current=e}catch(t){throw d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await u.authenticate()),fe.current=e}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}x(t||C||null),P(r||!1),v(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,a)=>{let o=await Qh();if(!w||!C||!o)throw new i.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new i.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let s=Ke.walletProxy??await Ke.initializeWalletProxy(15e3);if(!s)throw new i.PrivyClientError("Wallet proxy not initialized.");if((({address:e,chainType:t,user:r})=>!!Nh(r).find((r=>r.address===e&&r.chainType===t)))({address:e,chainType:t,user:C}))return n();let l=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new i.PrivyClientError("Address to delegate is not associated with current user.");return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}})({address:e,user:C}),d=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new i.PrivyClientError("Address to delegate is not associated with current user.");let n=r.imported?r:c.getPrivyPrimaryWallet(t);if(!n)throw new i.PrivyClientError("Unable to determine root address for delegated address.");return{address:n.address,chainType:n.chainType,imported:n.imported}})({address:e,user:C}),u=async()=>{await s.createDelegatedAction({accessToken:o,rootWallet:d,delegatedWallets:[l]}),await Ke.refreshSessionAndUser()};if(await Ke.recoverPrimaryWallet(),r)te({delegatedActions:{consent:{address:e,onDelegate:u,onSuccess:async()=>{n()},onError:async e=>{a(e)}}}}),xe(c.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN);else try{await u(),n()}catch(e){a(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!w||!C)throw new i.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===Nh(C).length)throw new i.PrivyClientError("User has no delegated wallets to revoke.");let n=async()=>{await u.revokeDelegatedWallet(),await Ke.refreshSessionAndUser()};if(e)te({delegatedActions:{revoke:{onRevoke:n,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),xe(c.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN);else try{await n(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new At(e,t);u.startAuthFlow(r);try{fe.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===we.current?d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof At))throw new i.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await u.getAccessToken())try{({user:e}=await u.link()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await u.authenticate()),fe.current="farcaster"}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}x(e||null),P(t||!1),v(!0)},async loginWithGuestAccountFlow(){let e=new _t(this.appId);u.startAuthFlow(e);try{we.current="login",fe.current="guest";let{user:e,isNewUser:t}=await u.authenticate();if(t=t||!1,!e)throw new i.PrivyClientError("Unable to authenticate guest account");let r=await Qh(),n=await Ke.initializeWalletProxy(c.WALLET_PROXY_TIMEOUT);if(r&&n)try{let t=s.shouldCreateEmbeddedEthWallet(e,Z.embeddedWallets.ethereum.createOnLogin),a=s.shouldCreateEmbeddedSolWallet(e,Z.embeddedWallets.solana.createOnLogin);if(t&&a){let t=await Oe(e,c.WALLET_PROXY_TIMEOUT);await n.createSolana({accessToken:r,ethereumAddress:t?.address}),e=await Ke.refreshSessionAndUser()}else a?(await n.createSolana({accessToken:r,ethereumAddress:c.getPrivyEthereumWallet(e)?.address}),e=await Ke.refreshSessionAndUser()):t?(await Oe(e,c.WALLET_PROXY_TIMEOUT),e=await Ke.refreshSessionAndUser()):x(e)}catch(t){x(e),console.warn("Unable to create embedded wallet for guest account")}return P(t),v(!0),d.emitPrivyEvent(ye,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;fe.current=n;let{url:a,stateCode:s,codeVerifier:l}=await async function({api:e,appId:t}){let r=It(),n=Pt(),a=await jt(r);try{let{url:i}=await e.post(o.oAuthInitPath,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:a,state_code:n});return{url:i,stateCode:n,codeVerifier:r}}catch(e){throw i.formatApiError(e)}}({api:u.api,appId:e});if(!a)throw u.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new i.PrivyClientError("No authorization URL returned for cross-app auth.");try{let o=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,a=setTimeout((()=>{r(new i.PrivyClientError("Authorization request timed out after 2 minutes.")),o()}),12e4);function o(){t?.close(),window.removeEventListener("message",l)}let s=setInterval((()=>{t?.closed&&!n&&(o(),clearInterval(s),clearTimeout(a),r(new i.PrivyClientError("User rejected request")))}),300);function l(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(clearTimeout(a),e(t.data),o()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(a),r(new i.PrivyClientError(t.data.error)),o()),t.data.type===Wh&&((n=new BroadcastChannel(Oh)).onmessage=l))}window.addEventListener("message",l)}))}({url:a,popup:t,provider:n}),c=o.stateCode,d=o.authorizationCode;if(c!==s)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:s??"",returnedStateCode:c??""}}),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:a,client:o}){if(!n||!t)throw new i.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new i.PrivyClientError("User denied confirmation during cross-app auth flow");try{let i=new Lh({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});o.startAuthFlow(i);let s="link"===a?await o.link():await o.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=i.formatApiError(e);if(t.privyErrorCode)throw new i.PrivyClientError(t.message||"Invalid code during cross-app auth flow.",void 0,t.privyErrorCode);if("User denied confirmation during cross-app auth flow"===t.message)throw new i.PrivyClientError("Invalid code during cross-app auth flow.",void 0,i.PrivyErrorCode.OAUTH_USER_DENIED);throw new i.PrivyClientError("Invalid code during cross-app auth flow.",void 0,i.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:l,stateCode:c,authorizationCode:d,action:r,client:u});h&&u.storeProviderAccessToken(e,h);let p=await Ke.refreshSessionAndUser();if(!p)throw new i.PrivyClientError("Unable to update user");return u.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw u.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(fe.current=e,!d.e())return void Ee(c.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&ga(window.navigator.userAgent))return void Ee(c.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:Wh},"*"),d.s.del(c.HEADLESS_OAUTH_KEY),d.s.del(c.OAUTH_DISABLE_SIGNUP_KEY);let a=new kt({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&a.addCaptchaToken(t),u.startAuthFlow(a);let i=await u.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&n.isAndroid&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!g)throw new i.PrivyNotReadyError;fe.current="telegram";let r=new Zt(e,t);u.startAuthFlow(r),$({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>Z.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Z.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new i.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new i.PrivyClientError("Telegram was not initialized")):t(new i.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(u.authFlow instanceof Zt))throw new i.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");u.authFlow.meta.captchaToken||=e?.captchaToken;let n=await Qh(),a=e?.intent||we.current;if("login"===a)try{let e=await u.authenticate();t=e.user,r=e.isNewUser,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==a)throw new i.PrivyClientError("Unknown auth intent");try{t=(await u.link()).user,fe.current="telegram"}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}x(t),P(r||!1),v(!0),$({status:"done"});let o=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:o}},async recoveryOAuthFlow(e,t,r){let n,a;function o(t){if(!t)throw u.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new i.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,s,{url:l,codeVerifier:c,stateCode:d}=await Za({api:qh.api,provider:e});o(l);try{let n=await zh({url:l,popup:r,provider:e});if(t=n.stateCode,s=n.authorizationCode,t!==d)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:d??"",returnedStateCode:t??""}}),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw u.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new i.PrivyClientError("Recovery OAuth failed")}[n,a]=await Promise.all([Qh(),Xa({api:qh.api,provider:e,codeVerifier:c,stateCode:t,authorizationCode:s})]);break}case"icloud":{let{url:t}=await Za({api:qh.api,provider:e});o(t);let{ckWebAuthToken:i}=await zh({url:t,popup:r,provider:e});a=i,n=await Qh()}}if(!K)throw new i.PrivyClientError("Cannot connect to wallet proxy");if(!n)throw new i.PrivyClientError("Unable to authorize user");switch(t){case"recover":{let t=ee.recoverWallet?.entropyId,r=ee.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new i.PrivyClientError("Recovery OAuth failed");u.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await K.recover({accessToken:n,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:a}),u.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{u.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await K.create({accessToken:n,recoveryAccessToken:a,recoveryMethod:e});let t=c.getPrivyEthereumWallet(await Ke.refreshSessionAndUser());if(!t)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),d.emitPrivyEvent(ye,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=c.getPrivyPrimaryWallet(C);if(!t)throw d.emitPrivyEvent(ye,"setWalletRecovery","onError",i.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");u.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(t);await K.setRecovery({accessToken:n,entropyId:r,entropyIdVerifier:o,recoveryMethod:e,recoveryAccessToken:a});let s=c.getPrivyPrimaryWallet(await Ke.refreshSessionAndUser());if(!s)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");u.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),d.emitPrivyEvent(ye,"setWalletRecovery","onSuccess",{method:e,wallet:s});break}default:throw new i.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,n;if(!(u.authFlow instanceof kt))throw new i.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let a=d.s.get(c.STATE_CODE_KEY),o=u.authFlow.meta.stateCode;if(a!==o)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:a??"",returnedStateCode:o??""}}),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await u.getAccessToken())try{let r=await u.link();t=r.user,n=r.oAuthTokens,fe.current=e}catch(t){throw d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let a=await u.authenticate();t=a.user,r=a.isNewUser,n=a.oAuthTokens,fe.current=e}catch(t){throw"login"===we.current?d.emitPrivyEvent(ye,"login","onError",t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return x(t),P(r||!1),v(!0),n&&t&&d.emitPrivyEvent(ye,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),n},passkeyAuthState:W,setPasskeyAuthState:L,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new $t({captchaToken:e,setPasskeyAuthState:L});u.startAuthFlow(r),we.current="login";try{fe.current="passkey",L({status:"generating-challenge"}),await r.initRegisterFlow(t),L({status:"awaiting-passkey"})}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof $t))throw new i.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current){let e=new i.PrivyClientError("Must init login with Passkey flow first.");throw L({status:"error",error:e}),e}let r=await Qh();try{fe.current="passkey",L({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await u.authenticate())}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}x(e),P(t||!1),v(!0),L({status:"done"});let n=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:n}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new $t({captchaToken:e,setPasskeyAuthState:L});u.startAuthFlow(r),we.current="login";try{fe.current="passkey",L({status:"generating-challenge"}),await r.initAuthenticationFlow(t),L({status:"awaiting-passkey"})}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof $t))throw new i.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(u.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==fe.current){let e=new i.PrivyClientError("Must init login with Passkey flow first.");throw L({status:"error",error:e}),e}let n=await Qh();try{fe.current="passkey",L({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await u.authenticate())}catch(e){throw L({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}x(t),P(r||!1),v(!0),L({status:"done"});let a=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:a}},async initLinkWithPasskey(e){let t=new $t({captchaToken:e});u.startAuthFlow(t),we.current="link",fe.current="passkey",L({status:"generating-challenge"});try{await t.initLinkFlow(),L({status:"awaiting-passkey"})}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),L({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!g)throw new i.PrivyNotReadyError;if(!(u.authFlow instanceof $t))throw new i.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==fe.current)throw new i.PrivyClientError("Must init login with Passkey flow first.");try{fe.current="passkey",({user:e}=await u.link())}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return x(e||C||null),L({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!d.e())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&&ga(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 n=new kt({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&n.addCaptchaToken(t),V({status:"loading"});let a=await u.startAuthFlow(n).getAuthorizationUrl();a?.url&&window.location.assign(a.url)},async loginWithHeadlessOAuth(e){let t,r,n;M(!0),V({status:"loading"}),u.startAuthFlow(new kt(e));let a=d.s.get(c.STATE_CODE_KEY),o=e.stateCode;if(a!==o)throw u.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:a??"",returnedStateCode:o??""}}),M(!1),new i.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,i.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await u.getAccessToken())try{({user:t,oAuthTokens:n}=await u.link()),fe.current=e.provider;let r=ze(t);t&&r&&d.emitPrivyEvent(ye,"linkAccount","onSuccess",{user:t,linkMethod:fe.current,linkedAccount:r})}catch(t){throw M(!1),d.emitPrivyEvent(ye,"linkAccount","onError",t.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await u.authenticate()),fe.current=e.provider;let a=ze(t);t&&a&&void 0!==r&&d.emitPrivyEvent(ye,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:fe.current,loginAccount:a})}catch(e){throw M(!1),V({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return x(t),P(r||!1),v(!0),M(!1),V({status:"done"}),n&&t&&d.emitPrivyEvent(ye,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{let a=new St({email:e,captchaToken:t,disableSignup:r});u.startAuthFlow(a);try{fe.current="email",F({status:"sending-code"}),await a.sendCodeEmail({withPrivyUi:n}),F({status:"awaiting-code-input"})}catch(e){throw F({status:"error",error:e}),"login"===we.current?d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let n=new Tt(e,t,r);u.startAuthFlow(n);try{await n.sendCodeEmail({withPrivyUi:!0})}catch(e){d.emitPrivyEvent(ye,"update","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:fe.current})}},initUpdatePhone:async(e,t,r)=>{let n=new Yt(e,t,r);u.startAuthFlow(n);try{await n.sendSmsCode({withPrivyUi:!0})}catch(e){d.emitPrivyEvent(ye,"update","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:fe.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{B({status:"sending-code"});let a=new Kt({phoneNumber:e,captchaToken:t,disableSignup:r});u.startAuthFlow(a);try{fe.current="sms",await a.sendSmsCode({withPrivyUi:n}),B({status:"awaiting-code-input"})}catch(e){throw B({status:"error",error:e}),"login"===we.current?d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===we.current&&d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(u.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(u.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function n(e){u.authFlow instanceof St?F(e):u.authFlow instanceof Kt&&B(e)}if(n({status:"submitting-code"}),!g){let e=new i.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(u.authFlow instanceof St)u.authFlow.meta.emailCode=e.trim();else{if(!(u.authFlow instanceof Kt)){let e=new i.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}u.authFlow.meta.smsCode=e.trim()}let a=await Qh();if("link"===we.current)try{({user:t}=await u.link())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:fe.current}),e}else if("update"===we.current)try{({user:t}=await u.link())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(ye,"update","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:fe.current}),e}else try{({user:t,isNewUser:r}=await u.authenticate())}catch(e){throw n({status:"error",error:e}),d.emitPrivyEvent(ye,"login","onError",e.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let o=t||C;x(o||null),P(r||!1),v(!0),n({status:"done"});let s=null;return u.authFlow instanceof St?s=o?.linkedAccounts.find((({type:e})=>"email"===e))||null:u.authFlow instanceof Kt&&(s=o?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:o,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{we.current="link",fe.current="siwe",z({status:"generating-message"});let n=await u.generateSiweNonce({address:e,captchaToken:r});return z({status:"awaiting-signature"}),s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await u.generateSiweNonce({address:e});return s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let n;n=await u.linkSmartWallet({message:e,signature:t,smartWalletType:r}),x((n=await Ke.refreshSessionAndUser()??n)||C||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})=>{let o;ke("siwe");let s=null;try{z({status:"submitting-signature"}),o=await u.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}),o=await Ke.refreshSessionAndUser()??o,z({status:"done"}),(s=ze(o)||null)&&d.emitPrivyEvent(ye,"linkAccount","onSuccess",{user:o,linkMethod:"siwe",linkedAccount:s})}catch(e){throw d.emitPrivyEvent(ye,"linkAccount","onError",e.privyErrorCode||i.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),we.current=null,fe.current=null,z({status:"error",error:e}),e}let l=o||C;return x(l||null),we.current=null,fe.current=null,{user:l,linkedAccount:s}},refreshSessionAndUser:async()=>{let e=await u.getAuthenticatedUser();return v(!!e),x(e),e},walletProxy:K,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>u.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await u.acceptTerms();return x(e),e},getUsdTokenPrice:e=>u.getUsdTokenPrice(e),getUsdPriceForSol:()=>u.getUsdPriceForSol(),getSplTokenMetadata:e=>u.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let n=c.getPrivyPrimaryWallet(e?.user??C)||c.getImportedPrivyEthereumWallet(e?.user??C)||c.getImportedPrivySolanaWallet(e?.user??C);n||t(!0);let a=await Qh();if(!a||!K||!n)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));J(!0);let{entropyId:i,entropyIdVerifier:o}=c.getEntropyDetailsFromAccount(n);try{await K.connect({accessToken:a,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){Ba(e)&&"privy"===n.recoveryMethod?(u.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}}),(await K.recover({entropyId:i,entropyIdVerifier:o,accessToken:a})).entropyId||r(Error("Unable to recover wallet")),u.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)):Ba(e)&&"privy"!==n.recoveryMethod?(te({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover"}}),xe(Ya(n.recoveryMethod))):r(e)}})),embeddedSolanaWallets:b,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await Ke.refreshSessionAndUser();if(!t)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let n=c.getPrivyEthereumWallet(e),a=c.getPrivySolanaWallet(e),o=r&&"createAdditional"in r&&r.createAdditional,s=r&&"walletIndex"in r?r.walletIndex:void 0,l=(c.getLatestPrivySolanaWallet(e)?.walletIndex??-1)+1;if(a&&!o&&"number"!=typeof s)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof s&&s<0)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${s}) is invalid.`);let[u,h]=await Promise.all([Ke.initializeWalletProxy(t),Qh()]);if(!u||!h)throw d.emitPrivyEvent(ye,"createWallet","onError",i.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await Ue({user:e,wp:u,accessToken:h,walletIndex:s??l,ethereumWallet:n})})(t,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!w||!C)return void r(Error("User must be authenticated before exporting their Privy wallet"));let n=e?.address??c.getPrivySolanaWallet(C)?.address;if(!n)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:a,rootWallet:i}=c.getSolanaSigningAndRootWallet(C,n);if(!a||!i)return void r(Error("Must have a Privy wallet before exporting"));if(J(!0),!await Qh()||!K)return void r(Error("Must have valid access token to enroll in MFA"));if(!K)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=c.getEntropyDetailsFromAccount(i);te({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:c.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0},keyExport:{appId:l.appId,appClientId:l.clientId,origin:u.apiUrl,walletToExport:a,primaryWallet:i,onSuccess:t,onFailure:r}}),xe(c.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{f(!0),re?.(e)},updateWallets:()=>Re(),fundWallet:async(e,t)=>{let r=c.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;te({funding:d.prepareFundingModalData({address:e,appConfig:Z,fundWalletConfig:t,methodScreen:r})}),xe(r)},openModal:xe,requestFarcasterSignerStatus:async e=>{let t=await Qh(),r=C?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!C?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await u.requestFarcasterSignerStatus(e);return"approved"===n.status&&x(await u.getAuthenticatedUser()||C||null),n},connectCoinbaseSmartWallet:async()=>{Z.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=u.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||u.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),_e(e);await be("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await u.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return x(l),l}};Yh=Ke.recoverPrimaryWallet,Zh=Ke.recoverPrimaryWallet,Xh=Ke.solanaSignMessage;let Ye=r.useMemo((()=>({wallets:E,ready:oe&&me})),[E,oe,me]),Ze=u.authFlow instanceof Zt,Xe=!Z.headless&&Z.captchaEnabled&&!w&&(g||Ze);/*#__PURE__*/return e.jsx(c.PrivyContext.Provider,{value:$e,children:/*#__PURE__*/e.jsx(d.PrivyEventsContext.Provider,{value:ye,children:/*#__PURE__*/e.jsx(c.UseWalletsContext.Provider,{value:Ye,children:/*#__PURE__*/e.jsx(s.CaptchaProvider,{...Z,children:/*#__PURE__*/e.jsxs(i.InternalPrivyContext.Provider,{value:Ke,children:[/*#__PURE__*/e.jsx(s.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(c.ModalProvider,{data:ee,setModalData:te,setInitialScreen:k,initialScreen:j,authenticated:w,open:p,children:[l.children,Xe&&/*#__PURE__*/e.jsx(Gr,{delayedExecution:!1}),/*#__PURE__*/e.jsx(sh,{theme:{...Z.appearance.palette||{}}}),!Z.render.standalone&&/*#__PURE__*/e.jsx(vh,{open:p})]})}),Q&&X?/*#__PURE__*/e.jsx(kh,{appId:l.appId,appClientId:l.clientId,clientAnalyticsId:u.clientAnalyticsId,origin:u.apiUrl,mfaMethods:C?.mfaMethods,mfaPromise:he,mfaSubmitPromise:pe,onLoad:Y,onLoadFailed:()=>null}):null,Z.loginConfig.telegramAuthConfiguration&&
21
21
  /*#__PURE__*/e.jsx(an,{$if:!0,children:/*#__PURE__*/e.jsx(Eh,{scriptHost:l.apiUrl||c.DEFAULT_PRIVY_API_URL,botUsername:Z.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};const sp=()=>{let{getAccessToken:e,user:t}=c.usePrivyContext(),{refreshSessionAndUser:n,initializeWalletProxy:a}=i.usePrivyInternal(),o=d.useEmitPrivyEvent();return{importWallet:r.useCallback((({privateKey:r})=>we.importWallet({getAccessToken:e,user:t,initializeWalletProxy:a,refreshSessionAndUser:n,emitPrivyEvent:o},{privateKey:r,chainType:"ethereum"})),[t,e,n,a,o])}};let lp=async(e,t,r,n,a)=>{if(!e)throw n("linkAccount","onError",i.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:a}),new i.PrivyClientError("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(a))))throw new i.PrivyClientError(`OAuth account of type ${a} not linked to the account.`);await r(a)};exports.EthereumWalletConnector=s.EthereumWalletConnector,exports.useActiveWallet=s.useActiveWallet,exports.useConnectWallet=s.useConnectWallet,exports.useFundWallet=s.useFundWallet,exports.useLogin=s.useLogin,exports.useLogout=s.useLogout,exports.SUPPORTED_CHAINS=c.DEFAULT_SUPPORTED_CHAINS,exports.VERSION=c.VERSION,exports.addPrivyRpcToChain=c.addPrivyRpcToChain,exports.addRpcUrlOverrideToChain=c.addRpcUrlOverrideToChain,exports.useWallets=c.useWallets,exports.WalletConnector=d.WalletConnector,exports.useSolanaWallets=d.useSolanaWallets,exports.getEmbeddedConnectedWallet=Ce.getEmbeddedConnectedWallet,exports.Captcha=Gr,exports.ConnectorManager=jr,exports.LoginModal=vh,exports.PrivyClient=qr,exports.PrivyProvider=({config:t,...r})=>{var n;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new i.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(n=r.appId)||25!==n.length)throw new i.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");qh||(qh=new qr({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let a=Object.assign({},t);/*#__PURE__*/
22
- return e.jsx(c.PrivyAppConfigProvider,{client:qh,clientConfig:a,children:/*#__PURE__*/e.jsx(d.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(op,{...r,client:qh})})})},exports.errorIndicatesMaxMfaRetries=qa,exports.errorIndicatesMfaTimeout=Ha,exports.errorIndicatesMfaVerificationFailed=za,exports.getAccessToken=function(){return qh?qh.getCustomerAccessToken():Promise.resolve(d.i.get(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=i.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useCreateWallet=function(e){let{createWallet:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("createWallet",e),{createWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:a}=c.usePrivyContext();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:a}},exports.useCustomAuth=e=>{let{customAuthStatus:t}=i.usePrivyInternal();return d.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=i.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},exports.useFarcasterSigner=function(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=c.usePrivyContext();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}},exports.useGuestAccounts=function(){let{createGuestAccount:e}=r.useContext(c.PrivyContext);return{createGuestAccount:e}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=i.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},exports.useIdentityToken=function(){let{identityToken:e}=Lr();return{identityToken:e}},exports.useImportWallet=sp,exports.useLinkAccount=function(e){let{linkEmail:t,linkPhone:n,linkWallet:a,linkGoogle:i,linkApple:o,linkTwitter:s,linkDiscord:l,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkTelegram:g,linkFarcaster:f}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("linkAccount",e),{linkEmail:t,linkPhone:n,linkWallet:a,linkGoogle:i,linkApple:o,linkTwitter:s,linkDiscord:l,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkFarcaster:f,linkTelegram:g}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:t,linkWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:o}=i.usePrivyInternal();return{linkWithPasskey:r.useCallback((async()=>{try{await t();let r=await n();if(!r)throw Error("Error, user not found");let a=r.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:r,linkMethod:"passkey",linkedAccount:a})}catch(t){throw o({status:"error",error:t}),e?.onError?.(t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[n]),state:a}},exports.useLinkWithSiwe=e=>{let t=s.useCaptcha(),{siweState:n,setSiweState:a,linkWithSiwe:o,generateSiweMessage:l}=i.usePrivyInternal();return{generateSiweMessage:r.useCallback((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await l({address:t,chainId:r}).then((e=>e))}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[l]),linkWithSiwe:r.useCallback((async({signature:r,message:n,chainId:l,walletClientType:c,connectorType:d})=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);let{user:a,linkedAccount:u}=await o({message:n,signature:r,chainId:l,walletClientType:c,connectorType:d});u&&e?.onSuccess?.({user:a,linkMethod:"siwe",linkedAccount:u})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[o,t.status]),state:n}},exports.useLoginWithEmail=e=>{let t=s.useCaptcha(),{emailOtpState:n,setEmailOtpState:a,initLoginWithEmail:o,loginWithCode:l}=i.usePrivyInternal();return{sendCode:r.useCallback((async({email:r,disableSignup:n})=>{try{let e;if(!r)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await o({email:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[o]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"email",loginAccount:c})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithOAuth=e=>{d.usePrivyEventSubscription("login",e);let t=s.useCaptcha(),n=c.useIsServerConfigLoaded(),{ready:a,user:o}=c.usePrivyContext(),{initLoginWithHeadlessOAuth:l,loginWithHeadlessOAuth:u,oAuthState:h,setOAuthState:p,isHeadlessOAuthLoading:y}=i.usePrivyInternal(),m=r.useCallback((async e=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);return await l(e.provider,t.token,e.disableSignup)}catch(e){throw p({status:"error",error:e}),e}}),[l,t]),g=r.useCallback((async()=>{let e=Vt();try{if(o)return console.warn("Cannot login with OAuth when already logged in"),o;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw p({status:"error",error:e}),e}try{return await u(e)}catch(e){throw p({status:"error",error:e}),e}finally{Gt()}}),[u]);return r.useEffect((()=>{let e=Vt();a&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&g().catch((()=>{}))}),[a,n]),{initOAuth:m,loading:y,state:h}},exports.useLoginWithPasskey=e=>{let t=s.useCaptcha(),{initLoginWithPasskey:n,loginWithPasskey:a,passkeyAuthState:o,setPasskeyAuthState:l}=i.usePrivyInternal();return{loginWithPasskey:r.useCallback((async r=>{try{let o;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),o=await t.waitForResult()),await n({captchaToken:o,withPrivyUi:!1});let{user:l,isNewUser:c,wasAlreadyAuthenticated:d,loginAccount:u}=await a(r);e?.onComplete?.({user:l,isNewUser:c,wasAlreadyAuthenticated:d,loginMethod:"passkey",loginAccount:u})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a,t.status]),state:o}},exports.useLoginWithSms=e=>{let t=s.useCaptcha(),{smsOtpState:n,setSmsOtpState:a,initLoginWithSms:o,loginWithCode:l}=i.usePrivyInternal();return{sendCode:r.useCallback((async({phoneNumber:r,disableSignup:n})=>{try{let e;if(!r)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await o({phoneNumber:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[o]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"sms",loginAccount:c})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithTelegram=e=>{let t=s.useCaptcha(),{initLoginWithTelegram:n,loginWithTelegram:a,telegramAuthState:o,setTelegramAuthState:l}=i.usePrivyInternal();return{login:r.useCallback((async r=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);await n(t.token,r?.disableSignup);let{user:o,isNewUser:l,loginAccount:c,wasAlreadyAuthenticated:d}=await a({intent:"login"});e?.onComplete?.({user:o,isNewUser:l,wasAlreadyAuthenticated:d,loginMethod:"telegram",loginAccount:c})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[n,a,t]),state:o}},exports.useMfa=tc,exports.useMfaEnrollment=rc,exports.useModalStatus=()=>{let{isModalOpen:e}=r.useContext(c.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=c.usePrivyContext(),{initLoginWithOAuth:n}=i.usePrivyInternal(),a=d.useEmitPrivyEvent();return d.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>lp(t,r,n,a,e.provider)}},exports.usePrivy=()=>{let{importWallet:e}=sp();return{...r.useContext(c.PrivyContext),importWallet:e}},exports.useRegisterMfaListener=$r,exports.useSendTransaction=function(e){let{sendTransaction:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:t}},exports.useSetWalletPassword=function(e){let{setWalletPassword:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("setWalletPassword",e),{setWalletPassword:t}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:t}},exports.useSignAuthorization=()=>{let{ready:e,wallets:t}=c.useWallets(),{user:n}=c.usePrivyContext(),{rpcConfig:a,chains:o,appId:s}=i.usePrivyInternal();return{signAuthorization:r.useCallback((async(r,i)=>{if(!n)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let l=i?.address??c.getPrivyEthereumWallet(n)?.address??y.zeroAddress,d=t.find((e=>y.getAddress(e.address)===y.getAddress(l)));if(!d)throw Error("Signing wallet not found.");let u=r.chainId??Number(d.chainId.split(":")[1]),h=o.find((e=>e.id===u));if(!h)throw Error("Error, chain not configured in PrivyProvider config");let p=y.createWalletClient({account:l,chain:h,transport:y.http(m.getJsonRpcEndpointFromChain(h,a,s))}).extend(ve.eip7702Actions()),g=await p.prepareAuthorization({...r,sponsor:r.sponsor||void 0}),f=await d.getEthereumProvider(),w=await f.request({method:"secp256k1_sign",params:[ve.hashAuthorization(g)]});return{...g,...y.parseSignature(w)}}),[e,t,n,o])}},exports.useSignMessage=function(e){let{signMessage:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("signMessage",e),{signMessage:t}},exports.useSignTransaction=function(){let{signTransaction:e}=r.useContext(c.PrivyContext);return{signTransaction:e}},exports.useSignTypedData=function(e){let{signTypedData:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("signTypedData",e),{signTypedData:t}},exports.useSignupWithPasskey=e=>{let t=s.useCaptcha(),{initSignupWithPasskey:n,signupWithPasskey:a,passkeyAuthState:o,setPasskeyAuthState:l}=i.usePrivyInternal();return{signupWithPasskey:r.useCallback((async()=>{try{let r;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),r=await t.waitForResult()),await n({captchaToken:r,withPrivyUi:!1});let{user:o,isNewUser:l,wasAlreadyAuthenticated:c,loginAccount:d}=await a();e?.onComplete?.({user:o,isNewUser:l,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:d})}catch(t){throw l({status:"error",error:t}),e?.onError?.(t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[a,t.status]),state:o}},exports.useToken=function(e){let{getAccessToken:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("accessToken",e),{getAccessToken:t}},exports.useUpdateAccount=function(e){let{updateEmail:t,updatePhone:n}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("update",e),{updateEmail:t,updatePhone:n}},exports.useUser=()=>{let{setUser:e,client:t}=r.useContext(i.InternalPrivyContext),{user:n}=r.useContext(c.PrivyContext);return{user:n,refreshUser:r.useCallback((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}};
22
+ return e.jsx(c.PrivyAppConfigProvider,{client:qh,clientConfig:a,children:/*#__PURE__*/e.jsx(d.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(op,{...r,client:qh})})})},exports.errorIndicatesMaxMfaRetries=qa,exports.errorIndicatesMfaTimeout=Ha,exports.errorIndicatesMfaVerificationFailed=za,exports.getAccessToken=function(){return qh?qh.getCustomerAccessToken():Promise.resolve(d.s.get(c.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=i.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useCreateWallet=function(e){let{createWallet:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("createWallet",e),{createWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:a}=c.usePrivyContext();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:a}},exports.useCustomAuth=e=>{let{customAuthStatus:t}=i.usePrivyInternal();return d.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=i.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},exports.useFarcasterSigner=function(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=c.usePrivyContext();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}},exports.useGuestAccounts=function(){let{createGuestAccount:e}=r.useContext(c.PrivyContext);return{createGuestAccount:e}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=i.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},exports.useIdentityToken=function(){let{identityToken:e}=Lr();return{identityToken:e}},exports.useImportWallet=sp,exports.useLinkAccount=function(e){let{linkEmail:t,linkPhone:n,linkWallet:a,linkGoogle:i,linkApple:o,linkTwitter:s,linkDiscord:l,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkTelegram:g,linkFarcaster:f}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("linkAccount",e),{linkEmail:t,linkPhone:n,linkWallet:a,linkGoogle:i,linkApple:o,linkTwitter:s,linkDiscord:l,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkSpotify:y,linkInstagram:m,linkFarcaster:f,linkTelegram:g}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:t,linkWithPasskey:n,passkeyAuthState:a,setPasskeyAuthState:o}=i.usePrivyInternal();return{linkWithPasskey:r.useCallback((async()=>{try{await t();let r=await n();if(!r)throw Error("Error, user not found");let a=r.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:r,linkMethod:"passkey",linkedAccount:a})}catch(t){throw o({status:"error",error:t}),e?.onError?.(t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[n]),state:a}},exports.useLinkWithSiwe=e=>{let t=s.useCaptcha(),{siweState:n,setSiweState:a,linkWithSiwe:o,generateSiweMessage:l}=i.usePrivyInternal();return{generateSiweMessage:r.useCallback((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await l({address:t,chainId:r}).then((e=>e))}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[l]),linkWithSiwe:r.useCallback((async({signature:r,message:n,chainId:l,walletClientType:c,connectorType:d})=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);let{user:a,linkedAccount:u}=await o({message:n,signature:r,chainId:l,walletClientType:c,connectorType:d});u&&e?.onSuccess?.({user:a,linkMethod:"siwe",linkedAccount:u})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[o,t.status]),state:n}},exports.useLoginWithEmail=e=>{let t=s.useCaptcha(),{emailOtpState:n,setEmailOtpState:a,initLoginWithEmail:o,loginWithCode:l}=i.usePrivyInternal();return{sendCode:r.useCallback((async({email:r,disableSignup:n})=>{try{let e;if(!r)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await o({email:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[o]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"email",loginAccount:c})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithOAuth=e=>{d.usePrivyEventSubscription("login",e);let t=s.useCaptcha(),n=c.useIsServerConfigLoaded(),{ready:a,user:o}=c.usePrivyContext(),{initLoginWithHeadlessOAuth:l,loginWithHeadlessOAuth:u,oAuthState:h,setOAuthState:p,isHeadlessOAuthLoading:y}=i.usePrivyInternal(),m=r.useCallback((async e=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);return await l(e.provider,t.token,e.disableSignup)}catch(e){throw p({status:"error",error:e}),e}}),[l,t]),g=r.useCallback((async()=>{let e=Vt();try{if(o)return console.warn("Cannot login with OAuth when already logged in"),o;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw p({status:"error",error:e}),e}try{return await u(e)}catch(e){throw p({status:"error",error:e}),e}finally{Gt()}}),[u]);return r.useEffect((()=>{let e=Vt();a&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&g().catch((()=>{}))}),[a,n]),{initOAuth:m,loading:y,state:h}},exports.useLoginWithPasskey=e=>{let t=s.useCaptcha(),{initLoginWithPasskey:n,loginWithPasskey:a,passkeyAuthState:o,setPasskeyAuthState:l}=i.usePrivyInternal();return{loginWithPasskey:r.useCallback((async r=>{try{let o;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),o=await t.waitForResult()),await n({captchaToken:o,withPrivyUi:!1});let{user:l,isNewUser:c,wasAlreadyAuthenticated:d,loginAccount:u}=await a(r);e?.onComplete?.({user:l,isNewUser:c,wasAlreadyAuthenticated:d,loginMethod:"passkey",loginAccount:u})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a,t.status]),state:o}},exports.useLoginWithSms=e=>{let t=s.useCaptcha(),{smsOtpState:n,setSmsOtpState:a,initLoginWithSms:o,loginWithCode:l}=i.usePrivyInternal();return{sendCode:r.useCallback((async({phoneNumber:r,disableSignup:n})=>{try{let e;if(!r)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await o({phoneNumber:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[o]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:a,wasAlreadyAuthenticated:o,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:o,loginMethod:"sms",loginAccount:c})}catch(r){throw a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithTelegram=e=>{let t=s.useCaptcha(),{initLoginWithTelegram:n,loginWithTelegram:a,telegramAuthState:o,setTelegramAuthState:l}=i.usePrivyInternal();return{login:r.useCallback((async r=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);await n(t.token,r?.disableSignup);let{user:o,isNewUser:l,loginAccount:c,wasAlreadyAuthenticated:d}=await a({intent:"login"});e?.onComplete?.({user:o,isNewUser:l,wasAlreadyAuthenticated:d,loginMethod:"telegram",loginAccount:c})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[n,a,t]),state:o}},exports.useMfa=tc,exports.useMfaEnrollment=rc,exports.useModalStatus=()=>{let{isModalOpen:e}=r.useContext(c.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=c.usePrivyContext(),{initLoginWithOAuth:n}=i.usePrivyInternal(),a=d.useEmitPrivyEvent();return d.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>lp(t,r,n,a,e.provider)}},exports.usePrivy=()=>{let{importWallet:e}=sp();return{...r.useContext(c.PrivyContext),importWallet:e}},exports.useRegisterMfaListener=$r,exports.useSendTransaction=function(e){let{sendTransaction:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:t}},exports.useSetWalletPassword=function(e){let{setWalletPassword:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("setWalletPassword",e),{setWalletPassword:t}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:t}},exports.useSignAuthorization=()=>{let{ready:e,wallets:t}=c.useWallets(),{user:n}=c.usePrivyContext(),{rpcConfig:a,chains:o,appId:s}=i.usePrivyInternal();return{signAuthorization:r.useCallback((async(r,i)=>{if(!n)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let l=i?.address??c.getPrivyEthereumWallet(n)?.address??y.zeroAddress,d=t.find((e=>y.getAddress(e.address)===y.getAddress(l)));if(!d)throw Error("Signing wallet not found.");let u=r.chainId??Number(d.chainId.split(":")[1]),h=o.find((e=>e.id===u));if(!h)throw Error("Error, chain not configured in PrivyProvider config");let p=y.createWalletClient({account:l,chain:h,transport:y.http(m.getJsonRpcEndpointFromChain(h,a,s))}).extend(ve.eip7702Actions()),g=await p.prepareAuthorization({...r,sponsor:r.sponsor||void 0}),f=await d.getEthereumProvider(),w=await f.request({method:"secp256k1_sign",params:[ve.hashAuthorization(g)]});return{...g,...y.parseSignature(w)}}),[e,t,n,o])}},exports.useSignMessage=function(e){let{signMessage:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("signMessage",e),{signMessage:t}},exports.useSignTransaction=function(){let{signTransaction:e}=r.useContext(c.PrivyContext);return{signTransaction:e}},exports.useSignTypedData=function(e){let{signTypedData:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("signTypedData",e),{signTypedData:t}},exports.useSignupWithPasskey=e=>{let t=s.useCaptcha(),{initSignupWithPasskey:n,signupWithPasskey:a,passkeyAuthState:o,setPasskeyAuthState:l}=i.usePrivyInternal();return{signupWithPasskey:r.useCallback((async()=>{try{let r;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,i.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),r=await t.waitForResult()),await n({captchaToken:r,withPrivyUi:!1});let{user:o,isNewUser:l,wasAlreadyAuthenticated:c,loginAccount:d}=await a();e?.onComplete?.({user:o,isNewUser:l,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:d})}catch(t){throw l({status:"error",error:t}),e?.onError?.(t.privyErrorCode||i.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[a,t.status]),state:o}},exports.useToken=function(e){let{getAccessToken:t}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("accessToken",e),{getAccessToken:t}},exports.useUpdateAccount=function(e){let{updateEmail:t,updatePhone:n}=r.useContext(c.PrivyContext);return d.usePrivyEventSubscription("update",e),{updateEmail:t,updatePhone:n}},exports.useUser=()=>{let{setUser:e,client:t}=r.useContext(i.InternalPrivyContext),{user:n}=r.useContext(c.PrivyContext);return{user:n,refreshUser:r.useCallback((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}};