@privy-io/react-auth 1.78.2-beta-20240812183115 → 1.78.2-beta-20240813141643

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var hd=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var xu=(e,t,r)=>(hd(e,t,"read from private field"),r?r.call(e):t.get(e)),Es=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},yd=(e,t,r,o)=>(hd(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);var ku=(e,t,r)=>(hd(e,t,"access private method"),r);import{getAddress as Oo}from"@ethersproject/address";import{Web3Provider as Cu}from"@ethersproject/providers";import{createStore as k_}from"mipd";import{useEffect as Zr,useMemo as R_,useRef as aa,useState as ct}from"react";import{isAndroid as I_}from"react-device-detect";import{ProviderErrors as M_,calculateTotalGasEstimate as W_,populateTransactionRequest as O_}from"@privy-io/js-sdk-core";import{FetchError as KC}from"ofetch";var tt=class extends Error{constructor(r,o,n){super(r);o instanceof Error&&(this.cause=o),this.privyErrorCode=n}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},Wt=class extends tt{constructor(r,o,n,i,a){super(n,i,a);this.type=r;this.status=o}},w=class extends tt{constructor(r,o,n){super(r,o,n);this.type="client_error"}},Ts=class extends w{constructor(){super("Request timed out",void 0,"client_request_timeout")}};var pe=class extends tt{constructor(r,o,n){super(r,o,n);this.type="connector_error"}},le=e=>{if(e instanceof tt)return e;if(!(e instanceof KC))return rt(e);if(!e.response)return new Wt("api_error",null,e.message,e);let{type:t,message:r,error:o,code:n}=e.data;return new Wt(t||"ApiError",e.response.status,r||o,e,n)},rt=e=>e instanceof tt?e:e instanceof Error?new w(e.message,e):new w(`Internal error: ${e}`);var Eo=class extends w{constructor(){super("Method called before `ready`. Ensure you wait until `ready` is true before calling.")}},Ot=class extends w{constructor(t="Embedded wallet error",r){super(t,r,"unknown_embedded_wallet_error")}},Ss=class extends w{constructor(t="User must be authenticated"){super(t,void 0,"must_be_authenticated")}};var Sr=class extends w{constructor(t){super("This application is in development mode and must be upgraded to production to log in new users.",t,"max_accounts_reached")}};var _s="/api/v1/sessions",Ps="/api/v1/sessions/logout",Ru="/api/v1/sessions/fork",As="/api/v1/sessions/fork/recover",Iu="/api/v1/siwe/init",Mu="/api/v1/siwe/authenticate",Wu="/api/v1/siwe/link",Ou="/api/v1/siwe/unlink",Lu="/api/v1/farcaster/init",Nu="/api/v1/farcaster/authenticate",Du="/api/v1/farcaster/link",Uu="/api/v1/farcaster/status",Fu="/api/v1/farcaster/unlink",Bu="/api/v1/passwordless/init",Hu="/api/v1/passwordless/authenticate",Gu="/api/v1/passwordless/link",Vu="/api/v1/passwordless/unlink",qu="/api/v1/passwordless/update",zu="/api/v1/passwordless_sms/init",$u="/api/v1/passwordless_sms/link",Ku="/api/v1/passwordless_sms/unlink",Yu="/api/v1/passwordless_sms/authenticate",ju="/api/v1/passwordless_sms/update",xs="/api/v1/oauth/init",Zu="/api/v1/oauth/authenticate",ks="/api/v1/oauth/link",Qu="/api/v1/oauth/unlink",Ju="/api/v1/recovery/oauth/init",Xu="/api/v1/recovery/oauth/init_icloud",em="/api/v1/recovery/oauth/authenticate",tm="/api/v1/passkeys/link/init",rm="/api/v1/passkeys/authenticate/init",om="/api/v1/passkeys/link",nm="/api/v1/passkeys/authenticate",im="/api/v1/passkeys/unlink",am="/api/v1/telegram/authenticate",sm="/api/v1/telegram/link",lm="/api/v1/telegram/unlink";var cm="/api/v1/mfa/passwordless_sms/init",dm="/api/v1/mfa/passkeys/init",pm="/api/v1/users/me/accept_terms",Rs="/api/v1/analytics_events",um="/api/v1/custom_jwt_account/authenticate",mm="/api/v1/guest/authenticate",fm="/api/v1/plugins/moonpay_on_ramp/sign",hm="/api/v1/funding/coinbase_on_ramp/init",ym="/api/v1/funding/coinbase_on_ramp/status";var si=class{constructor(t){this.meta={token:t}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");try{let t=await this.api.post(um,{token:this.meta.token});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){throw new Error("Unimplemented")}};var Lo=class{constructor(t,r){this.meta={email:t,captchaToken:r}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new w("Email and email code must be set prior to calling authenticate.");try{let t=await this.api.post(Hu,{email:this.meta.email,code:this.meta.emailCode});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new w("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(Gu,{email:this.meta.email,code:this.meta.emailCode})}catch(t){throw le(t)}}async sendCodeEmail(t,r){if(!this.api)throw new w("Auth flow has no API instance");if(t&&(this.meta.email=t),r&&(this.meta.captchaToken=r),!this.meta.email)throw new w("Email must be set when initialzing authentication.");try{return await this.api.post(Bu,{email:this.meta.email,token:this.meta.captchaToken})}catch(o){throw le(o)}}},Is=class extends Lo{constructor(r,o,n){super(o,n);this.meta={email:o,captchaToken:n,oldAddress:r}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new w("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(qu,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(r){throw le(r)}}};import{isMobile as jC,isIOS as ZC}from"react-device-detect";var gd=class{constructor(){this._cache={}}get(t){return this._cache[t]}put(t,r){r!==void 0?this._cache[t]=r:this.del(t)}del(t){delete this._cache[t]}getKeys(){return Object.keys(this._cache)}},Ms=class{get(t){let r=localStorage.getItem(t);return r===null?void 0:JSON.parse(r)}put(t,r){r!==void 0?localStorage.setItem(t,JSON.stringify(r)):this.del(t)}del(t){localStorage.removeItem(t)}getKeys(){return Object.entries(localStorage).map(([t])=>t)}};function la(){try{let e="privy:__session_storage__test",t="blobby",r=new Ms;return r.put(e,t),r.del(e),!0}catch{return!1}}function YC(){return typeof window<"u"&&window.localStorage?new Ms:new gd}var j=YC();import{StaticJsonRpcProvider as ca}from"@ethersproject/providers";function gm(){let e=window,t=e.ethereum;if(!t)return[];let r=[];if(t.providers?.length)for(let o of t.providers)o&&r.push(o);return r.push(e.ethereum),r}var Ws=e=>{if(e.isApexWallet)return"Apex Wallet";if(e.isAvalanche)return"Core Wallet";if(e.isBackpack)return"Backpack";if(e.isBifrost)return"Bifrost Wallet";if(e.isBitKeep)return"BitKeep";if(e.isBitski)return"Bitski";if(e.isBlockWallet)return"BlockWallet";if(e.isBraveWallet)return"Brave Wallet";if(e.isClover)return"Clover";if(e.isCoin98)return"Coin98 Wallet";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isDawn)return"Dawn Wallet";if(e.isDefiant)return"Defiant";if(e.isDesig)return"Desig Wallet";if(e.isEnkrypt)return"Enkrypt";if(e.isExodus)return"Exodus";if(e.isFordefi)return"Fordefi";if(e.isFrame)return"Frame";if(e.isFrontier)return"Frontier Wallet";if(e.isGamestop)return"GameStop Wallet";if(e.isHaqqWallet)return"HAQQ Wallet";if(e.isHyperPay)return"HyperPay Wallet";if(e.isImToken)return"ImToken";if(e.isHaloWallet)return"Halo Wallet";if(e.isKuCoinWallet)return"KuCoin Wallet";if(e.isMathWallet)return"MathWallet";if(e.isNovaWallet)return"Nova Wallet";if(e.isOkxWallet||e.isOKExWallet)return"OKX Wallet";if(e.isOneInchIOSWallet||e.isOneInchAndroidWallet)return"1inch Wallet";if(e.isOneKey)return"OneKey Wallet";if(e.isOpera)return"Opera";if(e.isPhantom)return"Phantom";if(e.isPortal)return"Ripio Portal";if(e.isRabby)return"Rabby Wallet";if(e.isRainbow)return"Rainbow";if(e.isSafePal)return"SafePal Wallet";if(e.isStatus)return"Status";if(e.isSubWallet)return"SubWallet";if(e.isTalisman)return"Talisman";if(e.isTally||e.isTaho)return"Taho";if(e.isTokenPocket)return"TokenPocket";if(e.isTokenary)return"Tokenary";if(e.isTrust||e.isTrustWallet)return"Trust Wallet";if(e.isTTWallet)return"TTWallet";if(e.isXDEFI)return"XDEFI Wallet";if(e.isZeal)return"Zeal";if(e.isZerion)return"Zerion";if(e.isMetaMask)return"MetaMask"};var vd=(e,t)=>{if(!e.isMetaMask)return!1;if(e.isMetaMask&&!t)return!0;if(e.isBraveWallet&&!e._events&&!e._state||Ws(e)!=="MetaMask")return!1;if(e.providers){for(let r of e.providers)if(!vd(r))return!1}return!0},No=()=>!!("phantom"in window&&window?.phantom?.ethereum?.isPhantom),Os=()=>{let e=window;if(!e.ethereum)return!1;if(e.ethereum.isCoinbaseWallet)return!0;if(e.ethereum.providers){for(let t of e.ethereum.providers)if(t&&t.isCoinbaseWallet)return!0}return!1};var vm=(e,t)=>{let r=[],o=[];for(let[n,i]of e.entries())n<t?r.push(i):o.push(i);return[r,o]},Ls=e=>!!String(e).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Cm=(e,t)=>{let r=e.slice(0),o=[];for(;r.length;)o.push(r.splice(0,t));return o},pt=(e,t=3,r=4)=>{if(!e)return"";let o=2,n=3;if(t+r+o+n>=e.length)return e;let i=e.slice(0,o+t),a=e.slice(e.length-r,e.length);return`${i}...${a}`},Cd=e=>new Promise(t=>setTimeout(t,e));function wm(e,{interval:t=100,timeout:r=5e3}={}){return new Promise((o,n)=>{let i=0,a,l=()=>{if(i>=r){n("Max attempts reached without result");return}if(a=e(),i+=t,a!=null){o(a);return}setTimeout(l,t)};l()})}var da=(e,t={})=>{let r=t.delayMs||150,o=t.maxAttempts||270;return new Promise(async(n,i)=>{let a=!1,l=0;for(;!a&&l<o;){if(t.abortSignal?.aborted)return;e().then(s=>{a=!0,n(s)},(...s)=>{a=!0,i(...s)}),l+=1,await Cd(r)}a||i(new Error("Exceeded max attempts before resolving function"))})},Ns=(e,t,r={},o={})=>{let n=new URL(t,e);for(let[a,l]of Object.entries(r))l!==void 0&&n.searchParams.set(a,l);let i=Object.entries(o);if(i.length>0){let a=new URLSearchParams;for(let[l,s]of i)a.append(l,s);n.hash=a.toString()}return n.href};var bm=e=>e.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g,""),wn=e=>typeof e=="string"?e:"0x"+e.toString(16);async function Em(e,t,r,o=3e3){let n=!1,i=window;return new Promise(a=>{i.ethereum?l():(window.addEventListener("ethereum#initialized",l,{once:!0}),setTimeout(()=>{l()},o));function l(){if(n)return;n=!0,window.removeEventListener("ethereum#initialized",l);let s=e.getProviders();console.debug("Detected injected providers:",s.map(m=>m.info));let c=[];for(let m of s)t.includes("coinbase_wallet")&&m.info.rdns==="com.coinbase.wallet"||c.push({type:m.info.name.toLowerCase().replace(/\s/g,"_"),eip6963InjectedProvider:m});for(let m of gm()){let f=Ws(m);if(!s.some(u=>u.info.name===f)){if(vd(m,!0)&&!c.find(u=>u.type==="metamask")){c.push({type:"metamask",legacyInjectedProvider:m});continue}if(f==="Phantom"&&!c.find(u=>u.type==="phantom")){c.push({type:"phantom",legacyInjectedProvider:m});continue}if(f==="Coinbase Wallet"&&!c.find(u=>u.type==="coinbase_wallet"&&r?.coinbaseWallet?.connectionOptions!=="smartWalletOnly")){c.push({type:"coinbase_wallet",legacyInjectedProvider:m});continue}c.find(u=>u.type==="unknown_browser_extension")||c.push({type:"unknown_browser_extension",legacyInjectedProvider:m})}}a(c)}})}function li(e){return`eip155:${String(Number(e))}`}var Tm=(e,t,r,o)=>{let n=Number(e),i=t.find(a=>a.id===n);if(!i)throw new pe(`Unsupported chainId ${e}`,4901);return wd(i,r,o)},wd=(e,t,r)=>{let o=e.id,n=Number(e.id),i;if(e.rpcUrls.privyWalletOverride&&e.rpcUrls.privyWalletOverride.http[0])i=e.rpcUrls.privyWalletOverride.http[0];else if(t.rpcUrls&&t.rpcUrls[n])i=t.rpcUrls[n];else if(e.rpcUrls.privy?.http[0]){let a=new URL(e.rpcUrls.privy.http[0]);a.searchParams.append("privyAppId",r),i=a.toString()}else e.rpcUrls.public?.http[0]?i=e.rpcUrls.public.http[0]:i=e.rpcUrls.default?.http[0];if(!i)throw new pe(`No RPC url found for ${o}`);return i},Sm=(e,t)=>{let r=Number(e),o=t.find(n=>n.id===r);if(!o)throw new pe(`Unsupported chainId ${e}`,4901);return o.blockExplorers?.default.url},qt=(e,t,r,o)=>{let n=Number(e),i=t.find(l=>l.id===n);if(!i)throw new pe(`Unsupported chainId ${e}`,4901);let a;if(i.rpcUrls.privyWalletOverride&&i.rpcUrls.privyWalletOverride.http[0]?a=new ca(i.rpcUrls.privyWalletOverride.http[0]):r.rpcUrls&&r.rpcUrls[n]?a=new ca(r.rpcUrls[n]):i.rpcUrls.privy?.http[0]?a=new ca({url:i.rpcUrls.privy.http[0],headers:{"privy-app-id":o.appId}}):i.rpcUrls.public?.http[0]?a=new ca(i.rpcUrls.public.http[0]):a=new ca(i.rpcUrls.default?.http[0]),!a)throw new pe(`No RPC url found for ${e}`);return a},pa=e=>{let t={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},r=e.types.EIP712Domain??Object.entries(e.domain).map(([o,n])=>{if(n!=null&&typeof o=="string"&&o in t)return{name:o,type:t[o]}}).filter(o=>o!==void 0);return{...e,types:{...e.types,EIP712Domain:r}}};function _m(e,{min:t,max:r}){return Math.min(Math.max(e,t),r)}var Ds=e=>{let t;try{t=new URL(e).hostname}catch{return}for(let[r,o]of Object.entries(Us))if(t.includes(o.hostname))return{walletClientType:r,entry:o}};var Us={metamask:{id:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",displayName:"MetaMask",hostname:"metamask.io",mobile:{native:"metamask://",universal:"https://metamask.app.link"}},trust:{id:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",displayName:"Trust",hostname:"trustwallet.com",mobile:{universal:"https://link.trustwallet.com"}},safe:{id:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",displayName:"Safe",hostname:"safe.global",mobile:{universal:"https://app.safe.global/"}},rainbow:{id:"1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369",displayName:"Rainbow",hostname:"rainbow.me",mobile:{native:"rainbow://",universal:"https://rnbwapp.com"}},uniswap:{id:"c03dfee351b6fcc421b4494ea33b9d4b92a984f87aa76d1663bb28705e95034a",displayName:"Uniswap",hostname:"uniswap.org",mobile:{universal:"https://uniswap.org/app",native:"uniswap://"}},zerion:{id:"ecc4036f814562b41a5268adc86270fba1365471402006302e70169465b7ac18",displayName:"Zerion",hostname:"zerion.io",mobile:{native:"zerion://",universal:"https://wallet.zerion.io"}},argent:{id:"bc949c5d968ae81310268bf9193f9c9fb7bb4e1283e1284af8f2bd4992535fd6",displayName:"Argent",hostname:"www.argent.xyz",mobile:{universal:"https://www.argent.xyz/app"}},spot:{id:"74f8092562bd79675e276d8b2062a83601a4106d30202f2d509195e30e19673d",displayName:"Spot",hostname:"www.spot-wallet.com",mobile:{universal:"https://spot.so"}},omni:{id:"afbd95522f4041c71dd4f1a065f971fd32372865b416f95a0b1db759ae33f2a7",displayName:"Omni",hostname:"omni.app",mobile:{universal:"https://links.omni.app"}},cryptocom:{id:"f2436c67184f158d1beda5df53298ee84abfc367581e4505134b5bcf5f46697d",displayName:"Crypto.com",hostname:"crypto.com",mobile:{universal:"https://wallet.crypto.com",native:"dfw://"}},blockchain:{id:"84b43e8ddfcd18e5fcb5d21e7277733f9cccef76f7d92c836d0e481db0c70c04",displayName:"Blockchain",hostname:"www.blockchain.com",mobile:{universal:"https://www.blockchain.com"}},safepal:{id:"0b415a746fb9ee99cce155c2ceca0c6f6061b1dbca2d722b3ba16381d0562150",displayName:"SafePal",hostname:"safepal.com",mobile:{universal:"https://link.safepal.io"}},bitkeep:{id:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",displayName:"BitKeep",hostname:"bitkeep.com",mobile:{universal:"https://bkapp.vip"}},zengo:{id:"9414d5a85c8f4eabc1b5b15ebe0cd399e1a2a9d35643ab0ad22a6e4a32f596f0",displayName:"ZenGo",hostname:"zengo.com",mobile:{universal:"https://get.zengo.com/"}},"1inch":{id:"c286eebc742a537cd1d6818363e9dc53b21759a1e8e5d9b263d0c03ec7703576",displayName:"1inch",hostname:"wallet.1inch.io",mobile:{universal:"https://wallet.1inch.io/wc/"}},binance:{id:"8a0ee50d1f22f6651afcae7eb4253e52a3310b90af5daef78a8c4929a9bb99d4",displayName:"Binance",hostname:"www.binance.com",mobile:{universal:"https://app.binance.com/cedefi"}},exodus:{id:"e9ff15be73584489ca4a66f64d32c4537711797e30b6660dbcb71ea72a42b1f4",displayName:"Exodus",hostname:"exodus.com",mobile:{universal:"https://exodus.com/m"}},mew_wallet:{id:"f5b4eeb6015d66be3f5940a895cbaa49ef3439e518cd771270e6b553b48f31d2",displayName:"MEW wallet",hostname:"mewwallet.com",mobile:{universal:"https://mewwallet.com"}},alphawallet:{id:"138f51c8d00ac7b9ac9d8dc75344d096a7dfe370a568aa167eabc0a21830ed98",displayName:"AlphaWallet",hostname:"alphawallet.com",mobile:{universal:"https://aw.app"}},keyring_pro:{id:"47bb07617af518642f3413a201ec5859faa63acb1dd175ca95085d35d38afb83",displayName:"KEYRING PRO",hostname:"keyring.app",mobile:{universal:"https://keyring.app/"}},mathwallet:{id:"7674bb4e353bf52886768a3ddc2a4562ce2f4191c80831291218ebd90f5f5e26",displayName:"MathWallet",hostname:"mathwallet.org",mobile:{universal:"https://www.mathwallet.org"}},unstoppable:{id:"8308656f4548bb81b3508afe355cfbb7f0cb6253d1cc7f998080601f838ecee3",displayName:"Unstoppable",hostname:"unstoppabledomains.com",mobile:{universal:"https://unstoppabledomains.com/mobile"}},obvious:{id:"031f0187049b7f96c6f039d1c9c8138ff7a17fd75d38b34350c7182232cc29aa",displayName:"Obvious",hostname:"obvious.technology",mobile:{universal:"https://wallet.obvious.technology"}},ambire:{id:"2c81da3add65899baeac53758a07e652eea46dbb5195b8074772c62a77bbf568",displayName:"Ambire",hostname:"www.ambire.com",mobile:{universal:"https://mobile.ambire.com"}},internet_money_wallet:{id:"dd43441a6368ec9046540c46c5fdc58f79926d17ce61a176444568ca7c970dcd",displayName:"Internet Money Wallet",hostname:"internetmoney.io",mobile:{universal:"https://internetmoney.io"}},coin98:{id:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",displayName:"Coin98",hostname:"coin98.com",mobile:{universal:"https://coin98.services"}},abc_wallet:{id:"b956da9052132e3dabdcd78feb596d5194c99b7345d8c4bd7a47cabdcb69a25f",displayName:"ABC Wallet",hostname:"myabcwallet.io",mobile:{universal:"https://abcwalletconnect.page.link"}},arculus_wallet:{id:"0e4915107da5b3408b38e248f7a710f4529d54cd30e9d12ff0eb886d45c18e92",displayName:"Arculus Wallet",hostname:"www.getarculus.com",mobile:{universal:"https://gw.arculus.co/app"}},haha:{id:"719bd888109f5e8dd23419b20e749900ce4d2fc6858cf588395f19c82fd036b3",displayName:"HaHa",hostname:"www.haha.me",mobile:{universal:"https://haha.me"}},cling_wallet:{id:"942d0e22a7e6b520b0a03abcafc4dbe156a1fc151876e3c4a842f914277278ef",displayName:"Cling Wallet",hostname:"clingon.io",mobile:{universal:"https://cling.carrieverse.com/apple-app-site-association"}},broearn:{id:"8ff6eccefefa7506339201bc33346f92a43118d6ff7d6e71d499d8187a1c56a2",displayName:"Broearn",hostname:"www.broearn.com",mobile:{universal:"https://www.broearn.com/link/wallet/"}},copiosa:{id:"07f99a5d9849bb049d74830012b286f8b238e72b0337933ef22b84947409db80",displayName:"Copiosa",hostname:"copiosa.io",mobile:{universal:"https://copiosa.io/action/"}},burrito_wallet:{id:"8821748c25de9dbc4f72a691b25a6ddad9d7df12fa23333fd9c8b5fdc14cc819",displayName:"Burrito Wallet",hostname:"burritowallet.com",mobile:{universal:"https://burritowallet.com/wc?uri="}},enjin_wallet:{id:"bdc9433ffdaee55d31737d83b931caa1f17e30666f5b8e03eea794bac960eb4a",displayName:"Enjin Wallet",hostname:"enjin.io",mobile:{universal:"https://deeplink.wallet.enjin.io/"}},plasma_wallet:{id:"cbe13eb482c76f1fa401ff4c84d9acd0b8bc9af311ca0620a0b192fb28359b4e",displayName:"Plasma Wallet",hostname:"plasma-wallet.com",mobile:{universal:"https://plasma-wallet.com"}},avacus:{id:"94f785c0c8fb8c4f38cd9cd704416430bcaa2137f27e1468782d624bcd155a43",displayName:"Avacus",hostname:"avacus.cc",mobile:{universal:"https://avacus.app.link"}},bee:{id:"2cca8c1b0bea04ba37dee4017991d348cdb7b826804ab2bd31073254f345b715",displayName:"Bee",hostname:"www.beewallet.app",mobile:{universal:"https://beewallet.app/wc"}},pitaka:{id:"14e5d957c6eb62d3ee8fc6239703ac2d537d7e3552154836ca0beef775f630bc",displayName:"Pitaka",hostname:"pitaka.io",mobile:{universal:"https://app.pitaka.io"}},pltwallet:{id:"576c90ceaea34f29ff0104837cf2b2e23d201be43be1433feeb18d375430e1fd",displayName:"PLTwallet",hostname:"pltwallet.io",mobile:{universal:"https://pltwallet.io/"}},minerva:{id:"49bb9d698dbdf2c3d4627d66f99dd9fe90bba1eec84b143f56c64a51473c60bd",displayName:"Minerva",hostname:"minerva.digital",mobile:{universal:"https://minerva.digital"}},kryptogo:{id:"19418ecfd44963883e4d6abca1adeb2036f3b5ffb9bee0ec61f267a9641f878b",displayName:"KryptoGO",hostname:"kryptogo.com",mobile:{universal:"https://kryptogo.page.link"}},prema:{id:"5b8e33346dfb2a532748c247876db8d596734da8977905a27b947ba1e2cf465b",displayName:"PREMA",hostname:"premanft.com",mobile:{universal:"https://premanft.com"}},slingshot:{id:"d23de318f0f56038c5edb730a083216ff0cce00c1514e619ab32231cc9ec484b",displayName:"Slingshot",hostname:"slingshot.finance",mobile:{universal:"https://app.slingshot.finance"}},kriptonio:{id:"50df7da345f84e5a79aaf617df5167335a4b6751626df2e8a38f07029b3dde7b",displayName:"Kriptonio",hostname:"kriptonio.com",mobile:{universal:"https://app.kriptonio.com/mobile"}},timeless:{id:"9751385960bca290c13b443155288f892f62ee920337eda8c5a8874135daaea8",displayName:"Timeless",hostname:"timelesswallet.xyz",mobile:{universal:"https://timelesswallet.xyz"}},secux:{id:"6464873279d46030c0b6b005b33da6be5ed57a752be3ef1f857dc10eaf8028aa",displayName:"SecuX",hostname:"secuxtech.com",mobile:{universal:"https://wsweb.secuxtech.com"}},bitizen:{id:"41f20106359ff63cf732adf1f7dc1a157176c9b02fd266b50da6dcc1e9b86071",displayName:"Bitizen",hostname:"bitizen.org",mobile:{universal:"https://bitizen.org/wallet"}},blocto:{id:"14e7176536cb3706e221daaa3cfd7b88b7da8c7dfb64d1d241044164802c6bdd",displayName:"Blocto",hostname:"blocto.io",mobile:{universal:"https://blocto.app"}},safemoon:{id:"a0e04f1086aac204d4ebdd5f985c12ed226cd0006323fd8143715f9324da58d1",displayName:"SafeMoon",hostname:"safemoon.com",mobile:{universal:"https://safemoon.com/wc"}},okx_wallet:{id:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",displayName:"OKX Wallet",hostname:"okx.com",mobile:{native:"okex://main"}},rabby_wallet:{id:"18388be9ac2d02726dbac9777c96efaac06d744b2f6d580fccdd4127a6d01fd1",displayName:"Rabby Wallet",hostname:"rabby.io",mobile:{}}};function Pm(e){return{name:e.displayName||"",universalLink:e.mobile.universal,deepLink:e.mobile.native}}function Am(e,t){let r=Pm(t);if(r.deepLink)return Wm(r.deepLink,e);if(r.universalLink)return bd(r.universalLink,e);throw new w(`Unsupported wallet ${t.id}`)}function xm(e,t){let r=Pm(t);if(r.universalLink)return bd(r.universalLink,e)}var km="WALLETCONNECT_DEEPLINK_CHOICE";function Rm(){try{localStorage.removeItem(km)}catch{}}function Im({href:e,name:t}){try{localStorage.setItem(km,JSON.stringify({href:e,name:t}))}catch{}}function Mm(e){return e.startsWith("http://")||e.startsWith("https://")}function Wm(e,t){if(Mm(e))return bd(e,t);let r=e;r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`);let o=encodeURIComponent(t);return{redirect:`${r}wc?uri=${o}`,href:r}}function bd(e,t){if(!Mm(e))return Wm(e,t);let r=e;r.endsWith("/")||(r=`${r}/`);let o=encodeURIComponent(t);return{redirect:`${r}wc?uri=${o}`,href:r}}function Fs(e,t){window.open(e,t,"noreferrer noopener")}var Le=class{constructor(t){this.promise=null;this.fn=t}execute(t){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(t)}finally{this.promise=null}})()),this.promise}};var ua=class{constructor(t){this._meta={};this.captchaToken=t,this.startChannelOnce=new Le(this._startChannelOnce.bind(this)),this.pollForReady=new Le(this._pollForReady.bind(this))}get meta(){return this._meta}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.channelToken)throw new w("Auth flow must be initialized first");try{let t=await this.api.post(Nu,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid});if(!t)throw new w("No response from authentication");return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");try{return await this.api.post(Du,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(t){throw le(t)}}async _startChannelOnce(){if(!this.api)throw new w("Auth flow has no API instance");let t=await this.api.post(Lu,{token:this.captchaToken});jC&&!ZC&&t.connect_uri&&Fs(t.connect_uri,"_blank"),this._meta={connectUri:t.connect_uri,channelToken:t.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new w("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.channelToken)throw new w("Auth flow must be initialized first");let t=await this.api.get(Uu,{headers:{"farcaster-channel-token":this.meta.channelToken}});return t.state==="completed"?(this.message=t.message,this.signature=t.signature,this.fid=t.fid,!0):!1}};import{base64url as qm}from"jose";var Om="1.78.2-beta-20240812183115";var Lm="34357d3c125c2bcf2ce2bc3309d98715",Bs="https://auth.privy.io",Nm=2e4,Re=1400,Hs=2500,Ed=Om;var bn="privy:token",Td="privy-token",Gs="privy:refresh_token",Dm="privy-refresh-token",Sd="privy:id_token",_d="privy-id-token",Vs="privy-session",ma="privy:session_transfer_token",JC="privy:wallet",fa="privy:caid",qs=e=>`privy:guest:${e}`,ha=e=>`privy:cross-app:${e}`,En="privy:state_code",Tn="privy:code_verifier",Sn="privy:headless_oauth",zs=e=>`${JC}:${e}`,Pd="privy:connectors",Ad="privy:connections";var _n=12e4,To=1,xd="0x1",ci=3e4,Um="https://api.moonpay.com/v1",Fm="https://api.moonpay.com/v1",Bm="pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL",Hm="pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI";var Gm="deprecated";async function Vm(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return new Uint8Array(r)}function ya(e){return crypto.getRandomValues(new Uint8Array(e))}var di=class{constructor(t){this.meta={guestCredential:this.getOrCreateGuestCredential(t)}}getOrCreateGuestCredential(t){let r=qs(t);if(la()){if(j.get(r))return j.get(r);{let o=qm.encode(ya(32));return j.put(r,o),o}}return qm.encode(ya(32))}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");try{let t=await this.api.post(mm,{guest_credential:this.meta.guestCredential});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){throw new Error("Linking is not supported for the guest flow")}};import{base64url as zm}from"jose";var XC="S256",e3="S256";function Pn(){return zm.encode(ya(36))}function pi(){return Pn()}async function ui(e,t=XC){if(t==e3){let r=await Vm(e);return zm.encode(r)}else return e}function $m(){let e=j.get(Tn);if(!e)throw new w("Authentication error.");return e}function $s(){return!!j.get(Sn)}var Xr=class{constructor(t){let r=typeof t.headless=="boolean"?t.headless:$s();this.meta={...t,headless:r}}addCaptchaToken(t){this.meta.captchaToken=t}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new w("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new w("User denied confirmation during OAuth flow");let t=$m();try{let r=await this.api.post(Zu,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:t});return j.del(Tn),this.meta.headless&&j.del(Sn),{user:r.user,token:r.token,refresh_token:r.refresh_token,identity_token:r.identity_token,is_new_user:r.is_new_user,oauth_tokens:r.oauth_tokens}}catch(r){let o=le(r);throw o.privyErrorCode?new w(o.message||"Invalid code during OAuth flow.",void 0,o.privyErrorCode):o.message==="User denied confirmation during OAuth flow"?new w("Invalid code during oauth flow.",void 0,"oauth_user_denied"):new w("Invalid code during OAuth flow.",void 0,"unknown_auth_error")}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new w("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new w("User denied confirmation during OAuth flow");let t=j.get(Tn);if(!t)throw new w("Authentication error.");try{let r=await this.api.post(ks,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:t});return j.del(Tn),r}catch(r){throw le(r)}}async getAuthorizationUrl(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.provider)throw new w("Provider must be set when initializing OAuth authentication.");let t=Pn();j.put(Tn,t);let r=pi();j.put(En,r);let o=await ui(t);this.meta.headless&&j.put(Sn,!0);try{return await this.api.post(xs,{provider:this.meta.provider,redirect_to:window.location.href,token:this.meta.captchaToken,code_challenge:o,state_code:r})}catch(n){throw le(n)}}};function kd(e){return e.charAt(0).toUpperCase()+e.slice(1)}import{jsx as Km,jsxs as t3}from"react/jsx-runtime";var Ks=({style:e,...t})=>t3("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 24 24",style:{height:"24px",...e},...t,children:[Km("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"}),Km("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"})]});import{jsx as ga,jsxs as r3}from"react/jsx-runtime";var Ys=({style:e,...t})=>r3("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 71 55",style:{height:"24px",...e},...t,children:[ga("g",{clipPath:"url(#clip0)",children:ga("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"})}),ga("defs",{children:ga("clipPath",{id:"clip0",children:ga("rect",{width:"71",height:"55",fill:"white"})})})]});import{jsx as Ym}from"react/jsx-runtime";var js=({style:e,...t})=>Ym("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"24",y:"24",viewBox:"0 0 98 96",style:{height:"24px",...e},...t,children:Ym("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"})});import o3 from"@heroicons/react/24/outline/GlobeAltIcon";import{jsx as n3}from"react/jsx-runtime";var jm=({style:e})=>n3(o3,{style:{color:"var(--privy-color-error)",...e}});import{jsx as Zs,jsxs as i3}from"react/jsx-runtime";var Qs=({style:e,...t})=>i3("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"26px",width:"26px",...e},...t,children:[Zs("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"}),Zs("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"}),Zs("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"}),Zs("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"})]});import{jsx as _r,jsxs as Js}from"react/jsx-runtime";function Xs(e){return Js("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",...e,children:[Js("defs",{children:[Js("linearGradient",{id:"b",children:[_r("stop",{offset:"0",stopColor:"#3771c8"}),_r("stop",{stopColor:"#3771c8",offset:".128"}),_r("stop",{offset:"1",stopColor:"#60f",stopOpacity:"0"})]}),Js("linearGradient",{id:"a",children:[_r("stop",{offset:"0",stopColor:"#fd5"}),_r("stop",{offset:".1",stopColor:"#fd5"}),_r("stop",{offset:".5",stopColor:"#ff543e"}),_r("stop",{offset:"1",stopColor:"#c837ab"})]}),_r("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"}),_r("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"})]}),_r("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)"}),_r("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)"}),_r("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"})]})}import{jsx as el}from"react/jsx-runtime";function tl({style:e,...t}){return el("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",...e},...t,children:el("g",{fill:"#0077b5",strokeWidth:"1",strokeLinecap:"butt",strokeLinejoin:"miter",strokeMiterlimit:"10",style:{mixBlendMode:"normal"},children:el("g",{transform:"scale(5.12,5.12)",children:el("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"})})})})}import{jsx as Zm,jsxs as a3}from"react/jsx-runtime";function rl(e){return a3("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 496 512",...e,children:[Zm("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"}),Zm("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"})]})}import{jsx as Rd,jsxs as s3}from"react/jsx-runtime";function ol(e){return s3("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,...e,children:[Rd("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"}),Rd("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"}),Rd("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"})]})}import{jsx as Qm}from"react/jsx-runtime";var nl=({style:e,...t})=>Qm("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"24px",width:"24px",...e},...t,children:Qm("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"})});var Jm={google:{name:"Google",component:Qs},discord:{name:"Discord",component:Ys},github:{name:"Github",component:js},linkedin:{name:"LinkedIn",component:tl},twitter:{name:"Twitter",component:nl},spotify:{name:"Spotify",component:rl},instagram:{name:"Instagram",component:Xs},tiktok:{name:"Tiktok",component:ol},apple:{name:"Apple",component:Ks}},va=e=>e in Jm?Jm[e]:{name:"Unknown",component:jm};function Xm(e,t){let r={detail:"",retryable:!1},o=kd(t);if(e?.privyErrorCode==="linked_to_another_user"&&(r.detail="This account has already been linked to another user."),e?.privyErrorCode==="invalid_credentials"&&(r.retryable=!0,r.detail="Something went wrong. Try again."),e.privyErrorCode==="oauth_user_denied"&&(r.detail=`Retry and check ${o} to finish connecting your account.`,r.retryable=!0),e?.privyErrorCode==="too_many_requests"&&(r.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode==="too_many_requests"&&e.message.includes("provider rate limit")){let n=va(t).name;r.detail=`Request limit reached for ${n}. Please wait a moment and try again.`}if(e?.privyErrorCode==="oauth_account_suspended"){let n=va(t).name;r.detail=`Your ${n} account is suspended. Please try another login method.`}return e?.privyErrorCode==="cannot_link_more_of_type"&&(r.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode==="oauth_unexpected"&&t.startsWith("privy:")&&(r.detail="Something went wrong. Please try again."),r}function Ca(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),o=e.get("privy_oauth_provider");if(!t||!r||!o)return{inProgress:!1};let n=!1;try{n=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:o,headless:$s(),popupFlow:window.opener!==null&&n}}function An(){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"),j.del(En),window.history.replaceState({},"",e)}var xn=class{constructor(t){this.initAuthenticateOnce=new Le(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new Le(this._initLinkOnce.bind(this)),this.meta={captchaToken:t}}async initAuthenticationFlow(){if(!this.api)throw new w("Auth flow has no API instance");this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute()}async initLinkFlow(){if(!this.api)throw new w("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async authenticate(){let t=await import("@simplewebauthn/browser");if(!this.api)throw new w("Auth flow has no API instance");if(!t.browserSupportsWebAuthn())throw new w("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());try{let r=await t.startAuthentication(this._transformInitAuthenticateOptionsToCamelCase(this.meta.initAuthenticateResponse.options)),o=await this.api.post(nm,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)});return{user:o.user,token:o.token,refresh_token:o.refresh_token,is_new_user:o.is_new_user}}catch(r){throw r.name==="NotAllowedError"?new w("Passkey request timed out or rejected by user.",void 0,"passkey_not_allowed"):le(r)}}async link(){let t=await import("@simplewebauthn/browser");if(!this.api)throw new w("Auth flow has no API instance");if(!t.browserSupportsWebAuthn())throw new w("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let r=this.meta.initLinkResponse.options,o=await t.startRegistration(this._transformInitLinkOptionsToCamelCase(r));return await this.api.post(om,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(o)})}catch(r){throw r.name==="NotAllowedError"?new w("Passkey request timed out or rejected by user.",void 0,"passkey_not_allowed"):le(r)}}async _initAuthenticateOnce(){if(!this.api)throw new w("Auth flow has no API instance");return await this.api.post(rm,{token:this.meta.captchaToken})}async _initLinkOnce(){if(!this.api)throw new w("Auth flow has no API instance");return await this.api.post(tm,{})}_transformInitLinkOptionsToCamelCase(t){return{rp:t.rp,user:{id:t.user.id,name:t.user.name,displayName:t.user.display_name},challenge:t.challenge,pubKeyCredParams:t.pub_key_cred_params.map(r=>({type:r.type,alg:r.alg})),timeout:t.timeout,excludeCredentials:t.exclude_credentials?.map(r=>({id:r.id,type:r.type,transports:r.transports})),authenticatorSelection:{authenticatorAttachment:t.authenticator_selection?.authenticator_attachment,requireResidentKey:t.authenticator_selection?.require_resident_key,residentKey:t.authenticator_selection?.resident_key,userVerification:t.authenticator_selection?.user_verification},attestation:t.attestation,extensions:{appid:t.extensions?.app_id,credProps:t.extensions?.cred_props?.rk,hmacCreateSecret:t.extensions?.hmac_create_secret}}}_transformRegistrationResponseToSnakeCase(t){return{id:t.id,raw_id:t.rawId,response:{client_data_json:t.response.clientDataJSON,attestation_object:t.response.attestationObject,authenticator_data:t.response.authenticatorData},authenticator_attachment:t.authenticatorAttachment,client_extension_results:{app_id:t.clientExtensionResults.appid,cred_props:t.clientExtensionResults.credProps,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret},type:t.type}}_transformInitAuthenticateOptionsToCamelCase(t){return{challenge:t.challenge,allowCredentials:t.allow_credentials?.map(r=>({id:r.id,type:r.type,transports:r.transports}))||[],timeout:t.timeout,extensions:{appid:t.extensions?.app_id,credProps:t.extensions?.cred_props,hmacCreateSecret:t.extensions?.hmac_create_secret},userVerification:t.user_verification}}_transformAuthenticationResponseToSnakeCase(t){return{id:t.id,raw_id:t.rawId,response:{client_data_json:t.response.clientDataJSON,authenticator_data:t.response.authenticatorData,signature:t.response.signature,user_handle:t.response.userHandle},authenticator_attachment:t.authenticatorAttachment,client_extension_results:{app_id:t.clientExtensionResults.appid,cred_props:t.clientExtensionResults.credProps,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret},type:t.type}}};var il=({address:e,chainId:t,nonce:r})=>{let o=window.location.host,n=window.location.origin,i="By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",a=new Date().toISOString();return`${o} wants you to sign in with your Ethereum account:
1
+ var hd=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var xu=(e,t,r)=>(hd(e,t,"read from private field"),r?r.call(e):t.get(e)),Es=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},yd=(e,t,r,o)=>(hd(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);var ku=(e,t,r)=>(hd(e,t,"access private method"),r);import{getAddress as Oo}from"@ethersproject/address";import{Web3Provider as Cu}from"@ethersproject/providers";import{createStore as k_}from"mipd";import{useEffect as Zr,useMemo as R_,useRef as aa,useState as ct}from"react";import{isAndroid as I_}from"react-device-detect";import{ProviderErrors as M_,calculateTotalGasEstimate as W_,populateTransactionRequest as O_}from"@privy-io/js-sdk-core";import{FetchError as KC}from"ofetch";var tt=class extends Error{constructor(r,o,n){super(r);o instanceof Error&&(this.cause=o),this.privyErrorCode=n}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},Wt=class extends tt{constructor(r,o,n,i,a){super(n,i,a);this.type=r;this.status=o}},w=class extends tt{constructor(r,o,n){super(r,o,n);this.type="client_error"}},Ts=class extends w{constructor(){super("Request timed out",void 0,"client_request_timeout")}};var pe=class extends tt{constructor(r,o,n){super(r,o,n);this.type="connector_error"}},le=e=>{if(e instanceof tt)return e;if(!(e instanceof KC))return rt(e);if(!e.response)return new Wt("api_error",null,e.message,e);let{type:t,message:r,error:o,code:n}=e.data;return new Wt(t||"ApiError",e.response.status,r||o,e,n)},rt=e=>e instanceof tt?e:e instanceof Error?new w(e.message,e):new w(`Internal error: ${e}`);var Eo=class extends w{constructor(){super("Method called before `ready`. Ensure you wait until `ready` is true before calling.")}},Ot=class extends w{constructor(t="Embedded wallet error",r){super(t,r,"unknown_embedded_wallet_error")}},Ss=class extends w{constructor(t="User must be authenticated"){super(t,void 0,"must_be_authenticated")}};var Sr=class extends w{constructor(t){super("This application is in development mode and must be upgraded to production to log in new users.",t,"max_accounts_reached")}};var _s="/api/v1/sessions",Ps="/api/v1/sessions/logout",Ru="/api/v1/sessions/fork",As="/api/v1/sessions/fork/recover",Iu="/api/v1/siwe/init",Mu="/api/v1/siwe/authenticate",Wu="/api/v1/siwe/link",Ou="/api/v1/siwe/unlink",Lu="/api/v1/farcaster/init",Nu="/api/v1/farcaster/authenticate",Du="/api/v1/farcaster/link",Uu="/api/v1/farcaster/status",Fu="/api/v1/farcaster/unlink",Bu="/api/v1/passwordless/init",Hu="/api/v1/passwordless/authenticate",Gu="/api/v1/passwordless/link",Vu="/api/v1/passwordless/unlink",qu="/api/v1/passwordless/update",zu="/api/v1/passwordless_sms/init",$u="/api/v1/passwordless_sms/link",Ku="/api/v1/passwordless_sms/unlink",Yu="/api/v1/passwordless_sms/authenticate",ju="/api/v1/passwordless_sms/update",xs="/api/v1/oauth/init",Zu="/api/v1/oauth/authenticate",ks="/api/v1/oauth/link",Qu="/api/v1/oauth/unlink",Ju="/api/v1/recovery/oauth/init",Xu="/api/v1/recovery/oauth/init_icloud",em="/api/v1/recovery/oauth/authenticate",tm="/api/v1/passkeys/link/init",rm="/api/v1/passkeys/authenticate/init",om="/api/v1/passkeys/link",nm="/api/v1/passkeys/authenticate",im="/api/v1/passkeys/unlink",am="/api/v1/telegram/authenticate",sm="/api/v1/telegram/link",lm="/api/v1/telegram/unlink";var cm="/api/v1/mfa/passwordless_sms/init",dm="/api/v1/mfa/passkeys/init",pm="/api/v1/users/me/accept_terms",Rs="/api/v1/analytics_events",um="/api/v1/custom_jwt_account/authenticate",mm="/api/v1/guest/authenticate",fm="/api/v1/plugins/moonpay_on_ramp/sign",hm="/api/v1/funding/coinbase_on_ramp/init",ym="/api/v1/funding/coinbase_on_ramp/status";var si=class{constructor(t){this.meta={token:t}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");try{let t=await this.api.post(um,{token:this.meta.token});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){throw new Error("Unimplemented")}};var Lo=class{constructor(t,r){this.meta={email:t,captchaToken:r}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new w("Email and email code must be set prior to calling authenticate.");try{let t=await this.api.post(Hu,{email:this.meta.email,code:this.meta.emailCode});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new w("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(Gu,{email:this.meta.email,code:this.meta.emailCode})}catch(t){throw le(t)}}async sendCodeEmail(t,r){if(!this.api)throw new w("Auth flow has no API instance");if(t&&(this.meta.email=t),r&&(this.meta.captchaToken=r),!this.meta.email)throw new w("Email must be set when initialzing authentication.");try{return await this.api.post(Bu,{email:this.meta.email,token:this.meta.captchaToken})}catch(o){throw le(o)}}},Is=class extends Lo{constructor(r,o,n){super(o,n);this.meta={email:o,captchaToken:n,oldAddress:r}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new w("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(qu,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(r){throw le(r)}}};import{isMobile as jC,isIOS as ZC}from"react-device-detect";var gd=class{constructor(){this._cache={}}get(t){return this._cache[t]}put(t,r){r!==void 0?this._cache[t]=r:this.del(t)}del(t){delete this._cache[t]}getKeys(){return Object.keys(this._cache)}},Ms=class{get(t){let r=localStorage.getItem(t);return r===null?void 0:JSON.parse(r)}put(t,r){r!==void 0?localStorage.setItem(t,JSON.stringify(r)):this.del(t)}del(t){localStorage.removeItem(t)}getKeys(){return Object.entries(localStorage).map(([t])=>t)}};function la(){try{let e="privy:__session_storage__test",t="blobby",r=new Ms;return r.put(e,t),r.del(e),!0}catch{return!1}}function YC(){return typeof window<"u"&&window.localStorage?new Ms:new gd}var j=YC();import{StaticJsonRpcProvider as ca}from"@ethersproject/providers";function gm(){let e=window,t=e.ethereum;if(!t)return[];let r=[];if(t.providers?.length)for(let o of t.providers)o&&r.push(o);return r.push(e.ethereum),r}var Ws=e=>{if(e.isApexWallet)return"Apex Wallet";if(e.isAvalanche)return"Core Wallet";if(e.isBackpack)return"Backpack";if(e.isBifrost)return"Bifrost Wallet";if(e.isBitKeep)return"BitKeep";if(e.isBitski)return"Bitski";if(e.isBlockWallet)return"BlockWallet";if(e.isBraveWallet)return"Brave Wallet";if(e.isClover)return"Clover";if(e.isCoin98)return"Coin98 Wallet";if(e.isCoinbaseWallet)return"Coinbase Wallet";if(e.isDawn)return"Dawn Wallet";if(e.isDefiant)return"Defiant";if(e.isDesig)return"Desig Wallet";if(e.isEnkrypt)return"Enkrypt";if(e.isExodus)return"Exodus";if(e.isFordefi)return"Fordefi";if(e.isFrame)return"Frame";if(e.isFrontier)return"Frontier Wallet";if(e.isGamestop)return"GameStop Wallet";if(e.isHaqqWallet)return"HAQQ Wallet";if(e.isHyperPay)return"HyperPay Wallet";if(e.isImToken)return"ImToken";if(e.isHaloWallet)return"Halo Wallet";if(e.isKuCoinWallet)return"KuCoin Wallet";if(e.isMathWallet)return"MathWallet";if(e.isNovaWallet)return"Nova Wallet";if(e.isOkxWallet||e.isOKExWallet)return"OKX Wallet";if(e.isOneInchIOSWallet||e.isOneInchAndroidWallet)return"1inch Wallet";if(e.isOneKey)return"OneKey Wallet";if(e.isOpera)return"Opera";if(e.isPhantom)return"Phantom";if(e.isPortal)return"Ripio Portal";if(e.isRabby)return"Rabby Wallet";if(e.isRainbow)return"Rainbow";if(e.isSafePal)return"SafePal Wallet";if(e.isStatus)return"Status";if(e.isSubWallet)return"SubWallet";if(e.isTalisman)return"Talisman";if(e.isTally||e.isTaho)return"Taho";if(e.isTokenPocket)return"TokenPocket";if(e.isTokenary)return"Tokenary";if(e.isTrust||e.isTrustWallet)return"Trust Wallet";if(e.isTTWallet)return"TTWallet";if(e.isXDEFI)return"XDEFI Wallet";if(e.isZeal)return"Zeal";if(e.isZerion)return"Zerion";if(e.isMetaMask)return"MetaMask"};var vd=(e,t)=>{if(!e.isMetaMask)return!1;if(e.isMetaMask&&!t)return!0;if(e.isBraveWallet&&!e._events&&!e._state||Ws(e)!=="MetaMask")return!1;if(e.providers){for(let r of e.providers)if(!vd(r))return!1}return!0},No=()=>!!("phantom"in window&&window?.phantom?.ethereum?.isPhantom),Os=()=>{let e=window;if(!e.ethereum)return!1;if(e.ethereum.isCoinbaseWallet)return!0;if(e.ethereum.providers){for(let t of e.ethereum.providers)if(t&&t.isCoinbaseWallet)return!0}return!1};var vm=(e,t)=>{let r=[],o=[];for(let[n,i]of e.entries())n<t?r.push(i):o.push(i);return[r,o]},Ls=e=>!!String(e).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Cm=(e,t)=>{let r=e.slice(0),o=[];for(;r.length;)o.push(r.splice(0,t));return o},pt=(e,t=3,r=4)=>{if(!e)return"";let o=2,n=3;if(t+r+o+n>=e.length)return e;let i=e.slice(0,o+t),a=e.slice(e.length-r,e.length);return`${i}...${a}`},Cd=e=>new Promise(t=>setTimeout(t,e));function wm(e,{interval:t=100,timeout:r=5e3}={}){return new Promise((o,n)=>{let i=0,a,l=()=>{if(i>=r){n("Max attempts reached without result");return}if(a=e(),i+=t,a!=null){o(a);return}setTimeout(l,t)};l()})}var da=(e,t={})=>{let r=t.delayMs||150,o=t.maxAttempts||270;return new Promise(async(n,i)=>{let a=!1,l=0;for(;!a&&l<o;){if(t.abortSignal?.aborted)return;e().then(s=>{a=!0,n(s)},(...s)=>{a=!0,i(...s)}),l+=1,await Cd(r)}a||i(new Error("Exceeded max attempts before resolving function"))})},Ns=(e,t,r={},o={})=>{let n=new URL(t,e);for(let[a,l]of Object.entries(r))l!==void 0&&n.searchParams.set(a,l);let i=Object.entries(o);if(i.length>0){let a=new URLSearchParams;for(let[l,s]of i)a.append(l,s);n.hash=a.toString()}return n.href};var bm=e=>e.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g,""),wn=e=>typeof e=="string"?e:"0x"+e.toString(16);async function Em(e,t,r,o=3e3){let n=!1,i=window;return new Promise(a=>{i.ethereum?l():(window.addEventListener("ethereum#initialized",l,{once:!0}),setTimeout(()=>{l()},o));function l(){if(n)return;n=!0,window.removeEventListener("ethereum#initialized",l);let s=e.getProviders();console.debug("Detected injected providers:",s.map(m=>m.info));let c=[];for(let m of s)t.includes("coinbase_wallet")&&m.info.rdns==="com.coinbase.wallet"||c.push({type:m.info.name.toLowerCase().replace(/\s/g,"_"),eip6963InjectedProvider:m});for(let m of gm()){let f=Ws(m);if(!s.some(u=>u.info.name===f)){if(vd(m,!0)&&!c.find(u=>u.type==="metamask")){c.push({type:"metamask",legacyInjectedProvider:m});continue}if(f==="Phantom"&&!c.find(u=>u.type==="phantom")){c.push({type:"phantom",legacyInjectedProvider:m});continue}if(f==="Coinbase Wallet"&&!c.find(u=>u.type==="coinbase_wallet"&&r?.coinbaseWallet?.connectionOptions!=="smartWalletOnly")){c.push({type:"coinbase_wallet",legacyInjectedProvider:m});continue}c.find(u=>u.type==="unknown_browser_extension")||c.push({type:"unknown_browser_extension",legacyInjectedProvider:m})}}a(c)}})}function li(e){return`eip155:${String(Number(e))}`}var Tm=(e,t,r,o)=>{let n=Number(e),i=t.find(a=>a.id===n);if(!i)throw new pe(`Unsupported chainId ${e}`,4901);return wd(i,r,o)},wd=(e,t,r)=>{let o=e.id,n=Number(e.id),i;if(e.rpcUrls.privyWalletOverride&&e.rpcUrls.privyWalletOverride.http[0])i=e.rpcUrls.privyWalletOverride.http[0];else if(t.rpcUrls&&t.rpcUrls[n])i=t.rpcUrls[n];else if(e.rpcUrls.privy?.http[0]){let a=new URL(e.rpcUrls.privy.http[0]);a.searchParams.append("privyAppId",r),i=a.toString()}else e.rpcUrls.public?.http[0]?i=e.rpcUrls.public.http[0]:i=e.rpcUrls.default?.http[0];if(!i)throw new pe(`No RPC url found for ${o}`);return i},Sm=(e,t)=>{let r=Number(e),o=t.find(n=>n.id===r);if(!o)throw new pe(`Unsupported chainId ${e}`,4901);return o.blockExplorers?.default.url},qt=(e,t,r,o)=>{let n=Number(e),i=t.find(l=>l.id===n);if(!i)throw new pe(`Unsupported chainId ${e}`,4901);let a;if(i.rpcUrls.privyWalletOverride&&i.rpcUrls.privyWalletOverride.http[0]?a=new ca(i.rpcUrls.privyWalletOverride.http[0]):r.rpcUrls&&r.rpcUrls[n]?a=new ca(r.rpcUrls[n]):i.rpcUrls.privy?.http[0]?a=new ca({url:i.rpcUrls.privy.http[0],headers:{"privy-app-id":o.appId}}):i.rpcUrls.public?.http[0]?a=new ca(i.rpcUrls.public.http[0]):a=new ca(i.rpcUrls.default?.http[0]),!a)throw new pe(`No RPC url found for ${e}`);return a},pa=e=>{let t={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},r=e.types.EIP712Domain??Object.entries(e.domain).map(([o,n])=>{if(n!=null&&typeof o=="string"&&o in t)return{name:o,type:t[o]}}).filter(o=>o!==void 0);return{...e,types:{...e.types,EIP712Domain:r}}};function _m(e,{min:t,max:r}){return Math.min(Math.max(e,t),r)}var Ds=e=>{let t;try{t=new URL(e).hostname}catch{return}for(let[r,o]of Object.entries(Us))if(t.includes(o.hostname))return{walletClientType:r,entry:o}};var Us={metamask:{id:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",displayName:"MetaMask",hostname:"metamask.io",mobile:{native:"metamask://",universal:"https://metamask.app.link"}},trust:{id:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",displayName:"Trust",hostname:"trustwallet.com",mobile:{universal:"https://link.trustwallet.com"}},safe:{id:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",displayName:"Safe",hostname:"safe.global",mobile:{universal:"https://app.safe.global/"}},rainbow:{id:"1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369",displayName:"Rainbow",hostname:"rainbow.me",mobile:{native:"rainbow://",universal:"https://rnbwapp.com"}},uniswap:{id:"c03dfee351b6fcc421b4494ea33b9d4b92a984f87aa76d1663bb28705e95034a",displayName:"Uniswap",hostname:"uniswap.org",mobile:{universal:"https://uniswap.org/app",native:"uniswap://"}},zerion:{id:"ecc4036f814562b41a5268adc86270fba1365471402006302e70169465b7ac18",displayName:"Zerion",hostname:"zerion.io",mobile:{native:"zerion://",universal:"https://wallet.zerion.io"}},argent:{id:"bc949c5d968ae81310268bf9193f9c9fb7bb4e1283e1284af8f2bd4992535fd6",displayName:"Argent",hostname:"www.argent.xyz",mobile:{universal:"https://www.argent.xyz/app"}},spot:{id:"74f8092562bd79675e276d8b2062a83601a4106d30202f2d509195e30e19673d",displayName:"Spot",hostname:"www.spot-wallet.com",mobile:{universal:"https://spot.so"}},omni:{id:"afbd95522f4041c71dd4f1a065f971fd32372865b416f95a0b1db759ae33f2a7",displayName:"Omni",hostname:"omni.app",mobile:{universal:"https://links.omni.app"}},cryptocom:{id:"f2436c67184f158d1beda5df53298ee84abfc367581e4505134b5bcf5f46697d",displayName:"Crypto.com",hostname:"crypto.com",mobile:{universal:"https://wallet.crypto.com",native:"dfw://"}},blockchain:{id:"84b43e8ddfcd18e5fcb5d21e7277733f9cccef76f7d92c836d0e481db0c70c04",displayName:"Blockchain",hostname:"www.blockchain.com",mobile:{universal:"https://www.blockchain.com"}},safepal:{id:"0b415a746fb9ee99cce155c2ceca0c6f6061b1dbca2d722b3ba16381d0562150",displayName:"SafePal",hostname:"safepal.com",mobile:{universal:"https://link.safepal.io"}},bitkeep:{id:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",displayName:"BitKeep",hostname:"bitkeep.com",mobile:{universal:"https://bkapp.vip"}},zengo:{id:"9414d5a85c8f4eabc1b5b15ebe0cd399e1a2a9d35643ab0ad22a6e4a32f596f0",displayName:"ZenGo",hostname:"zengo.com",mobile:{universal:"https://get.zengo.com/"}},"1inch":{id:"c286eebc742a537cd1d6818363e9dc53b21759a1e8e5d9b263d0c03ec7703576",displayName:"1inch",hostname:"wallet.1inch.io",mobile:{universal:"https://wallet.1inch.io/wc/"}},binance:{id:"8a0ee50d1f22f6651afcae7eb4253e52a3310b90af5daef78a8c4929a9bb99d4",displayName:"Binance",hostname:"www.binance.com",mobile:{universal:"https://app.binance.com/cedefi"}},exodus:{id:"e9ff15be73584489ca4a66f64d32c4537711797e30b6660dbcb71ea72a42b1f4",displayName:"Exodus",hostname:"exodus.com",mobile:{universal:"https://exodus.com/m"}},mew_wallet:{id:"f5b4eeb6015d66be3f5940a895cbaa49ef3439e518cd771270e6b553b48f31d2",displayName:"MEW wallet",hostname:"mewwallet.com",mobile:{universal:"https://mewwallet.com"}},alphawallet:{id:"138f51c8d00ac7b9ac9d8dc75344d096a7dfe370a568aa167eabc0a21830ed98",displayName:"AlphaWallet",hostname:"alphawallet.com",mobile:{universal:"https://aw.app"}},keyring_pro:{id:"47bb07617af518642f3413a201ec5859faa63acb1dd175ca95085d35d38afb83",displayName:"KEYRING PRO",hostname:"keyring.app",mobile:{universal:"https://keyring.app/"}},mathwallet:{id:"7674bb4e353bf52886768a3ddc2a4562ce2f4191c80831291218ebd90f5f5e26",displayName:"MathWallet",hostname:"mathwallet.org",mobile:{universal:"https://www.mathwallet.org"}},unstoppable:{id:"8308656f4548bb81b3508afe355cfbb7f0cb6253d1cc7f998080601f838ecee3",displayName:"Unstoppable",hostname:"unstoppabledomains.com",mobile:{universal:"https://unstoppabledomains.com/mobile"}},obvious:{id:"031f0187049b7f96c6f039d1c9c8138ff7a17fd75d38b34350c7182232cc29aa",displayName:"Obvious",hostname:"obvious.technology",mobile:{universal:"https://wallet.obvious.technology"}},ambire:{id:"2c81da3add65899baeac53758a07e652eea46dbb5195b8074772c62a77bbf568",displayName:"Ambire",hostname:"www.ambire.com",mobile:{universal:"https://mobile.ambire.com"}},internet_money_wallet:{id:"dd43441a6368ec9046540c46c5fdc58f79926d17ce61a176444568ca7c970dcd",displayName:"Internet Money Wallet",hostname:"internetmoney.io",mobile:{universal:"https://internetmoney.io"}},coin98:{id:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",displayName:"Coin98",hostname:"coin98.com",mobile:{universal:"https://coin98.services"}},abc_wallet:{id:"b956da9052132e3dabdcd78feb596d5194c99b7345d8c4bd7a47cabdcb69a25f",displayName:"ABC Wallet",hostname:"myabcwallet.io",mobile:{universal:"https://abcwalletconnect.page.link"}},arculus_wallet:{id:"0e4915107da5b3408b38e248f7a710f4529d54cd30e9d12ff0eb886d45c18e92",displayName:"Arculus Wallet",hostname:"www.getarculus.com",mobile:{universal:"https://gw.arculus.co/app"}},haha:{id:"719bd888109f5e8dd23419b20e749900ce4d2fc6858cf588395f19c82fd036b3",displayName:"HaHa",hostname:"www.haha.me",mobile:{universal:"https://haha.me"}},cling_wallet:{id:"942d0e22a7e6b520b0a03abcafc4dbe156a1fc151876e3c4a842f914277278ef",displayName:"Cling Wallet",hostname:"clingon.io",mobile:{universal:"https://cling.carrieverse.com/apple-app-site-association"}},broearn:{id:"8ff6eccefefa7506339201bc33346f92a43118d6ff7d6e71d499d8187a1c56a2",displayName:"Broearn",hostname:"www.broearn.com",mobile:{universal:"https://www.broearn.com/link/wallet/"}},copiosa:{id:"07f99a5d9849bb049d74830012b286f8b238e72b0337933ef22b84947409db80",displayName:"Copiosa",hostname:"copiosa.io",mobile:{universal:"https://copiosa.io/action/"}},burrito_wallet:{id:"8821748c25de9dbc4f72a691b25a6ddad9d7df12fa23333fd9c8b5fdc14cc819",displayName:"Burrito Wallet",hostname:"burritowallet.com",mobile:{universal:"https://burritowallet.com/wc?uri="}},enjin_wallet:{id:"bdc9433ffdaee55d31737d83b931caa1f17e30666f5b8e03eea794bac960eb4a",displayName:"Enjin Wallet",hostname:"enjin.io",mobile:{universal:"https://deeplink.wallet.enjin.io/"}},plasma_wallet:{id:"cbe13eb482c76f1fa401ff4c84d9acd0b8bc9af311ca0620a0b192fb28359b4e",displayName:"Plasma Wallet",hostname:"plasma-wallet.com",mobile:{universal:"https://plasma-wallet.com"}},avacus:{id:"94f785c0c8fb8c4f38cd9cd704416430bcaa2137f27e1468782d624bcd155a43",displayName:"Avacus",hostname:"avacus.cc",mobile:{universal:"https://avacus.app.link"}},bee:{id:"2cca8c1b0bea04ba37dee4017991d348cdb7b826804ab2bd31073254f345b715",displayName:"Bee",hostname:"www.beewallet.app",mobile:{universal:"https://beewallet.app/wc"}},pitaka:{id:"14e5d957c6eb62d3ee8fc6239703ac2d537d7e3552154836ca0beef775f630bc",displayName:"Pitaka",hostname:"pitaka.io",mobile:{universal:"https://app.pitaka.io"}},pltwallet:{id:"576c90ceaea34f29ff0104837cf2b2e23d201be43be1433feeb18d375430e1fd",displayName:"PLTwallet",hostname:"pltwallet.io",mobile:{universal:"https://pltwallet.io/"}},minerva:{id:"49bb9d698dbdf2c3d4627d66f99dd9fe90bba1eec84b143f56c64a51473c60bd",displayName:"Minerva",hostname:"minerva.digital",mobile:{universal:"https://minerva.digital"}},kryptogo:{id:"19418ecfd44963883e4d6abca1adeb2036f3b5ffb9bee0ec61f267a9641f878b",displayName:"KryptoGO",hostname:"kryptogo.com",mobile:{universal:"https://kryptogo.page.link"}},prema:{id:"5b8e33346dfb2a532748c247876db8d596734da8977905a27b947ba1e2cf465b",displayName:"PREMA",hostname:"premanft.com",mobile:{universal:"https://premanft.com"}},slingshot:{id:"d23de318f0f56038c5edb730a083216ff0cce00c1514e619ab32231cc9ec484b",displayName:"Slingshot",hostname:"slingshot.finance",mobile:{universal:"https://app.slingshot.finance"}},kriptonio:{id:"50df7da345f84e5a79aaf617df5167335a4b6751626df2e8a38f07029b3dde7b",displayName:"Kriptonio",hostname:"kriptonio.com",mobile:{universal:"https://app.kriptonio.com/mobile"}},timeless:{id:"9751385960bca290c13b443155288f892f62ee920337eda8c5a8874135daaea8",displayName:"Timeless",hostname:"timelesswallet.xyz",mobile:{universal:"https://timelesswallet.xyz"}},secux:{id:"6464873279d46030c0b6b005b33da6be5ed57a752be3ef1f857dc10eaf8028aa",displayName:"SecuX",hostname:"secuxtech.com",mobile:{universal:"https://wsweb.secuxtech.com"}},bitizen:{id:"41f20106359ff63cf732adf1f7dc1a157176c9b02fd266b50da6dcc1e9b86071",displayName:"Bitizen",hostname:"bitizen.org",mobile:{universal:"https://bitizen.org/wallet"}},blocto:{id:"14e7176536cb3706e221daaa3cfd7b88b7da8c7dfb64d1d241044164802c6bdd",displayName:"Blocto",hostname:"blocto.io",mobile:{universal:"https://blocto.app"}},safemoon:{id:"a0e04f1086aac204d4ebdd5f985c12ed226cd0006323fd8143715f9324da58d1",displayName:"SafeMoon",hostname:"safemoon.com",mobile:{universal:"https://safemoon.com/wc"}},okx_wallet:{id:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",displayName:"OKX Wallet",hostname:"okx.com",mobile:{native:"okex://main"}},rabby_wallet:{id:"18388be9ac2d02726dbac9777c96efaac06d744b2f6d580fccdd4127a6d01fd1",displayName:"Rabby Wallet",hostname:"rabby.io",mobile:{}}};function Pm(e){return{name:e.displayName||"",universalLink:e.mobile.universal,deepLink:e.mobile.native}}function Am(e,t){let r=Pm(t);if(r.deepLink)return Wm(r.deepLink,e);if(r.universalLink)return bd(r.universalLink,e);throw new w(`Unsupported wallet ${t.id}`)}function xm(e,t){let r=Pm(t);if(r.universalLink)return bd(r.universalLink,e)}var km="WALLETCONNECT_DEEPLINK_CHOICE";function Rm(){try{localStorage.removeItem(km)}catch{}}function Im({href:e,name:t}){try{localStorage.setItem(km,JSON.stringify({href:e,name:t}))}catch{}}function Mm(e){return e.startsWith("http://")||e.startsWith("https://")}function Wm(e,t){if(Mm(e))return bd(e,t);let r=e;r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`);let o=encodeURIComponent(t);return{redirect:`${r}wc?uri=${o}`,href:r}}function bd(e,t){if(!Mm(e))return Wm(e,t);let r=e;r.endsWith("/")||(r=`${r}/`);let o=encodeURIComponent(t);return{redirect:`${r}wc?uri=${o}`,href:r}}function Fs(e,t){window.open(e,t,"noreferrer noopener")}var Le=class{constructor(t){this.promise=null;this.fn=t}execute(t){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(t)}finally{this.promise=null}})()),this.promise}};var ua=class{constructor(t){this._meta={};this.captchaToken=t,this.startChannelOnce=new Le(this._startChannelOnce.bind(this)),this.pollForReady=new Le(this._pollForReady.bind(this))}get meta(){return this._meta}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.channelToken)throw new w("Auth flow must be initialized first");try{let t=await this.api.post(Nu,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid});if(!t)throw new w("No response from authentication");return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");try{return await this.api.post(Du,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(t){throw le(t)}}async _startChannelOnce(){if(!this.api)throw new w("Auth flow has no API instance");let t=await this.api.post(Lu,{token:this.captchaToken});jC&&!ZC&&t.connect_uri&&Fs(t.connect_uri,"_blank"),this._meta={connectUri:t.connect_uri,channelToken:t.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new w("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.channelToken)throw new w("Auth flow must be initialized first");let t=await this.api.get(Uu,{headers:{"farcaster-channel-token":this.meta.channelToken}});return t.state==="completed"?(this.message=t.message,this.signature=t.signature,this.fid=t.fid,!0):!1}};import{base64url as qm}from"jose";var Om="1.78.2-beta-20240813141643";var Lm="34357d3c125c2bcf2ce2bc3309d98715",Bs="https://auth.privy.io",Nm=2e4,Re=1400,Hs=2500,Ed=Om;var bn="privy:token",Td="privy-token",Gs="privy:refresh_token",Dm="privy-refresh-token",Sd="privy:id_token",_d="privy-id-token",Vs="privy-session",ma="privy:session_transfer_token",JC="privy:wallet",fa="privy:caid",qs=e=>`privy:guest:${e}`,ha=e=>`privy:cross-app:${e}`,En="privy:state_code",Tn="privy:code_verifier",Sn="privy:headless_oauth",zs=e=>`${JC}:${e}`,Pd="privy:connectors",Ad="privy:connections";var _n=12e4,To=1,xd="0x1",ci=3e4,Um="https://api.moonpay.com/v1",Fm="https://api.moonpay.com/v1",Bm="pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL",Hm="pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI";var Gm="deprecated";async function Vm(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return new Uint8Array(r)}function ya(e){return crypto.getRandomValues(new Uint8Array(e))}var di=class{constructor(t){this.meta={guestCredential:this.getOrCreateGuestCredential(t)}}getOrCreateGuestCredential(t){let r=qs(t);if(la()){if(j.get(r))return j.get(r);{let o=qm.encode(ya(32));return j.put(r,o),o}}return qm.encode(ya(32))}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");try{let t=await this.api.post(mm,{guest_credential:this.meta.guestCredential});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){throw new Error("Linking is not supported for the guest flow")}};import{base64url as zm}from"jose";var XC="S256",e3="S256";function Pn(){return zm.encode(ya(36))}function pi(){return Pn()}async function ui(e,t=XC){if(t==e3){let r=await Vm(e);return zm.encode(r)}else return e}function $m(){let e=j.get(Tn);if(!e)throw new w("Authentication error.");return e}function $s(){return!!j.get(Sn)}var Xr=class{constructor(t){let r=typeof t.headless=="boolean"?t.headless:$s();this.meta={...t,headless:r}}addCaptchaToken(t){this.meta.captchaToken=t}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new w("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new w("User denied confirmation during OAuth flow");let t=$m();try{let r=await this.api.post(Zu,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:t});return j.del(Tn),this.meta.headless&&j.del(Sn),{user:r.user,token:r.token,refresh_token:r.refresh_token,identity_token:r.identity_token,is_new_user:r.is_new_user,oauth_tokens:r.oauth_tokens}}catch(r){let o=le(r);throw o.privyErrorCode?new w(o.message||"Invalid code during OAuth flow.",void 0,o.privyErrorCode):o.message==="User denied confirmation during OAuth flow"?new w("Invalid code during oauth flow.",void 0,"oauth_user_denied"):new w("Invalid code during OAuth flow.",void 0,"unknown_auth_error")}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new w("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new w("User denied confirmation during OAuth flow");let t=j.get(Tn);if(!t)throw new w("Authentication error.");try{let r=await this.api.post(ks,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:t});return j.del(Tn),r}catch(r){throw le(r)}}async getAuthorizationUrl(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.provider)throw new w("Provider must be set when initializing OAuth authentication.");let t=Pn();j.put(Tn,t);let r=pi();j.put(En,r);let o=await ui(t);this.meta.headless&&j.put(Sn,!0);try{return await this.api.post(xs,{provider:this.meta.provider,redirect_to:window.location.href,token:this.meta.captchaToken,code_challenge:o,state_code:r})}catch(n){throw le(n)}}};function kd(e){return e.charAt(0).toUpperCase()+e.slice(1)}import{jsx as Km,jsxs as t3}from"react/jsx-runtime";var Ks=({style:e,...t})=>t3("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 24 24",style:{height:"24px",...e},...t,children:[Km("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"}),Km("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"})]});import{jsx as ga,jsxs as r3}from"react/jsx-runtime";var Ys=({style:e,...t})=>r3("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 71 55",style:{height:"24px",...e},...t,children:[ga("g",{clipPath:"url(#clip0)",children:ga("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"})}),ga("defs",{children:ga("clipPath",{id:"clip0",children:ga("rect",{width:"71",height:"55",fill:"white"})})})]});import{jsx as Ym}from"react/jsx-runtime";var js=({style:e,...t})=>Ym("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"24",y:"24",viewBox:"0 0 98 96",style:{height:"24px",...e},...t,children:Ym("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"})});import o3 from"@heroicons/react/24/outline/GlobeAltIcon";import{jsx as n3}from"react/jsx-runtime";var jm=({style:e})=>n3(o3,{style:{color:"var(--privy-color-error)",...e}});import{jsx as Zs,jsxs as i3}from"react/jsx-runtime";var Qs=({style:e,...t})=>i3("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"26px",width:"26px",...e},...t,children:[Zs("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"}),Zs("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"}),Zs("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"}),Zs("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"})]});import{jsx as _r,jsxs as Js}from"react/jsx-runtime";function Xs(e){return Js("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",...e,children:[Js("defs",{children:[Js("linearGradient",{id:"b",children:[_r("stop",{offset:"0",stopColor:"#3771c8"}),_r("stop",{stopColor:"#3771c8",offset:".128"}),_r("stop",{offset:"1",stopColor:"#60f",stopOpacity:"0"})]}),Js("linearGradient",{id:"a",children:[_r("stop",{offset:"0",stopColor:"#fd5"}),_r("stop",{offset:".1",stopColor:"#fd5"}),_r("stop",{offset:".5",stopColor:"#ff543e"}),_r("stop",{offset:"1",stopColor:"#c837ab"})]}),_r("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"}),_r("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"})]}),_r("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)"}),_r("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)"}),_r("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"})]})}import{jsx as el}from"react/jsx-runtime";function tl({style:e,...t}){return el("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",...e},...t,children:el("g",{fill:"#0077b5",strokeWidth:"1",strokeLinecap:"butt",strokeLinejoin:"miter",strokeMiterlimit:"10",style:{mixBlendMode:"normal"},children:el("g",{transform:"scale(5.12,5.12)",children:el("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"})})})})}import{jsx as Zm,jsxs as a3}from"react/jsx-runtime";function rl(e){return a3("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 496 512",...e,children:[Zm("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"}),Zm("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"})]})}import{jsx as Rd,jsxs as s3}from"react/jsx-runtime";function ol(e){return s3("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,...e,children:[Rd("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"}),Rd("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"}),Rd("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"})]})}import{jsx as Qm}from"react/jsx-runtime";var nl=({style:e,...t})=>Qm("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"24px",width:"24px",...e},...t,children:Qm("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"})});var Jm={google:{name:"Google",component:Qs},discord:{name:"Discord",component:Ys},github:{name:"Github",component:js},linkedin:{name:"LinkedIn",component:tl},twitter:{name:"Twitter",component:nl},spotify:{name:"Spotify",component:rl},instagram:{name:"Instagram",component:Xs},tiktok:{name:"Tiktok",component:ol},apple:{name:"Apple",component:Ks}},va=e=>e in Jm?Jm[e]:{name:"Unknown",component:jm};function Xm(e,t){let r={detail:"",retryable:!1},o=kd(t);if(e?.privyErrorCode==="linked_to_another_user"&&(r.detail="This account has already been linked to another user."),e?.privyErrorCode==="invalid_credentials"&&(r.retryable=!0,r.detail="Something went wrong. Try again."),e.privyErrorCode==="oauth_user_denied"&&(r.detail=`Retry and check ${o} to finish connecting your account.`,r.retryable=!0),e?.privyErrorCode==="too_many_requests"&&(r.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode==="too_many_requests"&&e.message.includes("provider rate limit")){let n=va(t).name;r.detail=`Request limit reached for ${n}. Please wait a moment and try again.`}if(e?.privyErrorCode==="oauth_account_suspended"){let n=va(t).name;r.detail=`Your ${n} account is suspended. Please try another login method.`}return e?.privyErrorCode==="cannot_link_more_of_type"&&(r.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode==="oauth_unexpected"&&t.startsWith("privy:")&&(r.detail="Something went wrong. Please try again."),r}function Ca(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),o=e.get("privy_oauth_provider");if(!t||!r||!o)return{inProgress:!1};let n=!1;try{n=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:o,headless:$s(),popupFlow:window.opener!==null&&n}}function An(){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"),j.del(En),window.history.replaceState({},"",e)}var xn=class{constructor(t){this.initAuthenticateOnce=new Le(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new Le(this._initLinkOnce.bind(this)),this.meta={captchaToken:t}}async initAuthenticationFlow(){if(!this.api)throw new w("Auth flow has no API instance");this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute()}async initLinkFlow(){if(!this.api)throw new w("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async authenticate(){let t=await import("@simplewebauthn/browser");if(!this.api)throw new w("Auth flow has no API instance");if(!t.browserSupportsWebAuthn())throw new w("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());try{let r=await t.startAuthentication(this._transformInitAuthenticateOptionsToCamelCase(this.meta.initAuthenticateResponse.options)),o=await this.api.post(nm,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)});return{user:o.user,token:o.token,refresh_token:o.refresh_token,is_new_user:o.is_new_user}}catch(r){throw r.name==="NotAllowedError"?new w("Passkey request timed out or rejected by user.",void 0,"passkey_not_allowed"):le(r)}}async link(){let t=await import("@simplewebauthn/browser");if(!this.api)throw new w("Auth flow has no API instance");if(!t.browserSupportsWebAuthn())throw new w("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let r=this.meta.initLinkResponse.options,o=await t.startRegistration(this._transformInitLinkOptionsToCamelCase(r));return await this.api.post(om,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(o)})}catch(r){throw r.name==="NotAllowedError"?new w("Passkey request timed out or rejected by user.",void 0,"passkey_not_allowed"):le(r)}}async _initAuthenticateOnce(){if(!this.api)throw new w("Auth flow has no API instance");return await this.api.post(rm,{token:this.meta.captchaToken})}async _initLinkOnce(){if(!this.api)throw new w("Auth flow has no API instance");return await this.api.post(tm,{})}_transformInitLinkOptionsToCamelCase(t){return{rp:t.rp,user:{id:t.user.id,name:t.user.name,displayName:t.user.display_name},challenge:t.challenge,pubKeyCredParams:t.pub_key_cred_params.map(r=>({type:r.type,alg:r.alg})),timeout:t.timeout,excludeCredentials:t.exclude_credentials?.map(r=>({id:r.id,type:r.type,transports:r.transports})),authenticatorSelection:{authenticatorAttachment:t.authenticator_selection?.authenticator_attachment,requireResidentKey:t.authenticator_selection?.require_resident_key,residentKey:t.authenticator_selection?.resident_key,userVerification:t.authenticator_selection?.user_verification},attestation:t.attestation,extensions:{appid:t.extensions?.app_id,credProps:t.extensions?.cred_props?.rk,hmacCreateSecret:t.extensions?.hmac_create_secret}}}_transformRegistrationResponseToSnakeCase(t){return{id:t.id,raw_id:t.rawId,response:{client_data_json:t.response.clientDataJSON,attestation_object:t.response.attestationObject,authenticator_data:t.response.authenticatorData},authenticator_attachment:t.authenticatorAttachment,client_extension_results:{app_id:t.clientExtensionResults.appid,cred_props:t.clientExtensionResults.credProps,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret},type:t.type}}_transformInitAuthenticateOptionsToCamelCase(t){return{challenge:t.challenge,allowCredentials:t.allow_credentials?.map(r=>({id:r.id,type:r.type,transports:r.transports}))||[],timeout:t.timeout,extensions:{appid:t.extensions?.app_id,credProps:t.extensions?.cred_props,hmacCreateSecret:t.extensions?.hmac_create_secret},userVerification:t.user_verification}}_transformAuthenticationResponseToSnakeCase(t){return{id:t.id,raw_id:t.rawId,response:{client_data_json:t.response.clientDataJSON,authenticator_data:t.response.authenticatorData,signature:t.response.signature,user_handle:t.response.userHandle},authenticator_attachment:t.authenticatorAttachment,client_extension_results:{app_id:t.clientExtensionResults.appid,cred_props:t.clientExtensionResults.credProps,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret},type:t.type}}};var il=({address:e,chainId:t,nonce:r})=>{let o=window.location.host,n=window.location.origin,i="By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",a=new Date().toISOString();return`${o} wants you to sign in with your Ethereum account:
2
2
  ${e}
3
3
 
4
4
  ${i}
@@ -9,7 +9,7 @@ Chain ID: ${t}
9
9
  Nonce: ${r}
10
10
  Issued At: ${a}
11
11
  Resources:
12
- - https://privy.io`};var So=class{constructor(t,r,o){this.getNonceOnce=new Le(this._getNonceOnce.bind(this)),this.wallet=t,this.captchaToken=o,this.client=r}get meta(){return{connectorType:this.wallet.connectorType,walletClientType:this.wallet.walletClientType}}async authenticate(){if(!this.client)throw new w("SiweFlow has no client instance");try{let{message:t,signature:r}=await this.sign(),o=await this.client.authenticateWithSiweInternal({message:t,signature:r,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType});return{user:o.user,token:o.token,refresh_token:o.refresh_token,identity_token:o.identity_token,is_new_user:o.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.client)throw new w("SiweFlow has no client instance");try{let{message:t,signature:r}=await this.sign();return await this.client.linkWithSiweInternal({message:t,signature:r,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType})}catch(t){throw le(t)}}async sign(){if(!this.client)throw new w("SiweFlow has no client instance");if(await this.buildSiweMessage(),!this.preparedMessage)throw new w("Could not prepare SIWE message");let t=await this.wallet.sign(this.preparedMessage);return{message:this.preparedMessage,signature:t}}async _getNonceOnce(){if(!this.client)throw new w("SiweFlow has no client instance");return await this.client.generateSiweNonce({address:this.wallet.address,captchaToken:this.captchaToken})}async buildSiweMessage(){if(!this.client)throw new w("SiweFlow has no client instance");let t=this.wallet.address,r=this.wallet.chainId.replace("eip155:","");return this.nonce||(this.nonce=await this.getNonceOnce.execute()),this.preparedMessage=il({address:t,chainId:r,nonce:this.nonce}),this.preparedMessage}};var Do=class{constructor(t,r){this.meta={phoneNumber:t,captchaToken:r}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new w("phone number and sms code must be set prior to calling authenticate.");try{let t=await this.api.post(Yu,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new w("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post($u,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(t){throw le(t)}}async sendSmsCode(t,r){if(!this.api)throw new w("Auth flow has no API instance");if(t&&(this.meta.phoneNumber=t),r&&(this.meta.captchaToken=r),!this.meta.phoneNumber)throw new w("phone nNumber must be set when initialzing authentication.");try{return await this.api.post(zu,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken})}catch(o){throw le(o)}}},al=class extends Do{constructor(r,o,n){super(o,n);this.meta={phoneNumber:o,captchaToken:n,oldPhoneNumber:r}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new w("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(ju,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(r){throw le(r)}}};var mi=class{constructor(t){this.meta={captchaToken:t}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");try{let t=await this.api.post(am,{captcha_token:this.meta.captchaToken,telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");try{return await this.api.post(sm,{telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData})}catch(t){throw le(t)}}};function Id(e){let t={detail:"",retryable:!1};return e?.privyErrorCode==="linked_to_another_user"&&(t.detail="This account has already been linked to another user."),e?.privyErrorCode==="disallowed_login_method"&&(t.detail="Login with Telegram not allowed."),e?.privyErrorCode==="invalid_data"&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode==="cannot_link_more_of_type"&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode==="invalid_credentials"&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode==="too_many_requests"&&(t.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode==="too_many_requests"&&e.message.includes("rate limit")&&(t.detail="Request limit reached for Telegram. Please wait a moment and try again."),t}function tf(){let e;if(e=l3(),e)return ef(),{...e,flowType:"login-url"};if(e=c3(),e)return ef(),{...e,flowType:"web-app"}}function l3(){let e=new URLSearchParams(window.location.search),t=Number(e.get("id")||""),r=e.get("hash"),o=Number(e.get("auth_date")||""),n=e.get("first_name"),i=e.get("last_name")||void 0,a=e.get("username")||void 0,l=e.get("photo_url")||void 0;if(!(!t||!n||!o||!r))return{id:t,first_name:n,last_name:i,username:a,photo_url:l,auth_date:o,hash:r}}function c3(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=new URLSearchParams(decodeURIComponent(e.replace("#tgWebAppData=",""))),r=t.get("query_id"),o=t.get("user"),n=Number(t.get("auth_date")||""),i=t.get("hash");if(!(!r||!o||!n||!i))return{query_id:r,user:o,auth_date:n,hash:i}}function ef(){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"),window.history.replaceState({},"",e)}import{v4 as n0}from"uuid";function J(e){return e?new Date(e*1e3):null}function d3(e){let t=[];for(let r of e){let o=r.type;switch(r.type){case"wallet":let n={address:r.address,type:r.type,imported:r.imported,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at),chainType:r.chain_type,chainId:r.chain_id,walletClient:r.wallet_client_type==="privy"?"privy":"unknown",walletClientType:r.wallet_client_type,connectorType:r.connector_type,recoveryMethod:r.recovery_method};t.push(n);break;case"cross_app":let i={type:r.type,subject:r.subject,embeddedWallets:r.embedded_wallets,smartWallets:r.smart_wallets,providerApp:{id:r.provider_app_id},verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(i);break;case"email":let a={address:r.address,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(a);break;case"phone":let l={number:r.phoneNumber,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(l);break;case"google_oauth":let s={subject:r.subject,email:r.email,name:r.name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(s);break;case"spotify_oauth":let c={subject:r.subject,email:r.email,name:r.name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(c);break;case"instagram_oauth":let m={subject:r.subject,username:r.username,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(m);break;case"twitter_oauth":let f={subject:r.subject,username:r.username,name:r.name,type:r.type,profilePictureUrl:r.profile_picture_url,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(f);break;case"discord_oauth":let u={subject:r.subject,username:r.username,email:r.email,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(u);break;case"github_oauth":let C={subject:r.subject,username:r.username,name:r.name,email:r.email,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(C);break;case"tiktok_oauth":let v={subject:r.subject,username:r.username,name:r.name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(v);break;case"linkedin_oauth":let g={subject:r.subject,name:r.name,email:r.email,vanityName:r.vanity_name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(g);break;case"apple_oauth":let b={subject:r.subject,email:r.email,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(b);break;case"custom_auth":t.push({type:r.type,customUserId:r.custom_user_id,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)});break;case"farcaster":let E={type:r.type,fid:r.fid,ownerAddress:r.owner_address,displayName:r.display_name,username:r.username,bio:r.bio,pfp:r.profile_picture_url,url:r.homepage_url,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at),signerPublicKey:r.signer_public_key};t.push(E);break;case"passkey":let k={type:r.type,enrolledInMfa:r.enrolled_in_mfa,credentialId:r.credential_id,authenticatorName:r.authenticator_name,createdWithDevice:r.created_with_device,createdWithOs:r.created_with_os,createdWithBrowser:r.created_with_browser,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(k);break;case"telegram":let _={type:r.type,telegramUserId:r.telegram_user_id,firstName:r.first_name,lastName:r.last_name,username:r.username,photoUrl:r.photo_url,verifiedAt:J(r.first_verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(_);break;default:console.warn(`Unrecognized account type: ${o}. Please consider upgrading the Privy SDK.`)}}return t}function zt(e,t){return e.slice().sort((r,o)=>(o.firstVerifiedAt??o.verifiedAt).getTime()-(r.firstVerifiedAt??r.verifiedAt).getTime()).find(r=>r.type===t)}var ye=e=>e?.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClientType==="privy"&&!t.imported&&t.chainType==="ethereum")||null,kn=e=>e?.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClientType==="privy"&&!t.imported&&t.chainType==="solana")||null,sl=e=>e?.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClientType==="privy"&&t.imported&&t.chainType==="ethereum")||null,p3=e=>e.linkedAccounts.filter(t=>t.type==="wallet"),Lt=(e,t)=>ye(e)||kn(e)?!1:t==="all-users"||t==="users-without-wallets"&&!p3(e)?.length;function $t(e){if(!e)return null;let t=d3(e.linked_accounts),r=zt(t,"wallet"),o=zt(t,"email"),n=zt(t,"phone"),i=zt(t,"google_oauth"),a=zt(t,"twitter_oauth"),l=zt(t,"discord_oauth"),s=zt(t,"github_oauth"),c=zt(t,"spotify_oauth"),m=zt(t,"instagram_oauth"),f=zt(t,"tiktok_oauth"),u=zt(t,"linkedin_oauth"),C=zt(t,"apple_oauth"),v=zt(t,"farcaster"),g=zt(t,"telegram"),b=e.mfa_methods.map(({type:k,verified_at:_})=>({type:k,verifiedAt:J(_)}));return{id:e.id,createdAt:J(e.created_at),linkedAccounts:t,email:o&&{address:o?.address},phone:n&&{number:n?.number},wallet:r&&{address:r.address,chainType:r.chainType,chainId:r.chainId,walletClient:r.walletClient,walletClientType:r.walletClientType,connectorType:r.connectorType,recoveryMethod:r.recoveryMethod,imported:r.imported},google:i&&{subject:i.subject,email:i.email,name:i.name},twitter:a&&{subject:a.subject,username:a.username,name:a.name,profilePictureUrl:a.profilePictureUrl},discord:l&&{subject:l.subject,username:l.username,email:l.email},github:s&&{subject:s.subject,username:s.username,name:s.name,email:s.email},spotify:c&&{subject:c.subject,email:c.email,name:c.name},instagram:m&&{subject:m.subject,username:m.username},tiktok:f&&{subject:f.subject,username:f.username,name:f.name},linkedin:u&&{subject:u.subject,name:u.name,email:u.email,vanityName:u.vanityName},apple:C&&{subject:C.subject,email:C.email},farcaster:v&&{fid:v.fid,ownerAddress:v.ownerAddress,displayName:v.displayName,username:v.username,bio:v.bio,pfp:v.pfp,url:v.url,signerPublicKey:v.signerPublicKey},telegram:g&&{telegramUserId:g.telegramUserId,firstName:g.firstName,lastName:g.lastName,username:g.username,photoUrl:g.photoUrl},mfaMethods:b.map(k=>k.type),hasAcceptedTerms:e.has_accepted_terms??!1,isGuest:e.is_guest}}import{getAddress as ih}from"@ethersproject/address";import{isHexString as J3}from"@ethersproject/bytes";import X3 from"eventemitter3";import C3 from"@coinbase/wallet-sdk";import{jsx as rf,jsxs as u3}from"react/jsx-runtime";var _o=({style:e,...t})=>u3("svg",{width:"1024",height:"1024",viewBox:"0 0 1024 1024",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...e},...t,children:[rf("rect",{width:"1024",height:"1024",fill:"#0052FF",rx:100,ry:100}),rf("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"})]});import{getAddress as ro}from"@ethersproject/address";import{Web3Provider as cf}from"@ethersproject/providers";import{default as g3}from"eventemitter3";import y3 from"eventemitter3";var m3=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation"],of=e=>m3.includes(e);import{ErrorCode as f3}from"@ethersproject/logger";import{ProviderErrors as Rn}from"@privy-io/js-sdk-core";var fi=class extends pe{constructor(){super("Wallet timeout");this.type="wallet_error"}},hi=class extends pe{constructor(){super("User rejected connection");this.type="wallet_error"}},Dr=e=>{if(e instanceof pe)return e;if(e?.code&&e?.reason){let t=new wt(e);return e.code===f3.ACTION_REJECTED&&(t.details=Rn.E4001_USER_REJECTED_REQUEST),t}return e?.code?new wt(e):new pe("Unknown connector error",e)},Pr=class extends tt{constructor(r,o,n){super(r);this.type="provider_error";this.code=o,this.data=n}},wt=class extends Pr{constructor(r){let o=r;super(o.message,o.code,o.data);let n=Object.values(Rn).find(i=>i.eipCode===o.code);this.details=n||Rn.UNKNOWN_ERROR,o.code===-32002&&(o.message?.includes("already pending for origin")?o.message?.includes("wallet_requestPermissions")?this.details=Rn.E32002_CONNECTION_ALREADY_PENDING:this.details=Rn.E32002_REQUEST_ALREADY_PENDING:o.message?.includes("Already processing")&&o.message.includes("eth_requestAccounts")&&(this.details=Rn.E32002_WALLET_LOCKED))}},h3={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0},ERROR_USER_REJECTED_CONNECTION:{message:"You rejected the request",detail:"Please try connecting again.",retryable:!0},ERROR_USER_LIMIT_REACHED:{message:"Unable to link",detail:"You've reached the maximum number of linked wallets.",retryable:!1}},eo={...h3,...Rn};var Ke=class{constructor(t,r){this.removeListener=(t,r)=>{if(this.walletProvider)try{return this.walletProvider.removeListener(t,r)}catch{console.warn("Unable to remove wallet provider listener")}};this.walletTimeout=(t=new fi,r=this.rpcTimeoutDuration)=>new Promise((o,n)=>setTimeout(()=>{n(t)},r));this.setWalletProvider=t=>{this.walletProvider&&this._subscriptions.forEach(r=>{this.removeListener(r.eventName,r.listener)}),this.walletProvider=t,this._subscriptions.forEach(r=>{this.walletProvider?.on(r.eventName,r.listener)})};this.walletProvider=t,this.rpcTimeoutDuration=r||_n,this._subscriptions=[]}on(t,r){if(this.walletProvider)return this.walletProvider.on(t,r);this._subscriptions.push({eventName:t,listener:r})}async request(t){if(!this.walletProvider)throw new pe(`A wallet request of type ${t.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(t),this.walletTimeout()]).catch(r=>{throw Dr(r)})}},Uo=class extends Error{constructor(r,o,n){super(r);this.code=o,this.data=n}},wa=class extends y3{constructor(r,o,n,i,a,l=1){super();this.walletProxy=r,this.address=o,this.chainId=l,this.rpcConfig=n,this.chains=i,this.provider=qt(l,this.chains,n,{appId:a}),this.rpcTimeoutDuration=yi(n,"privy"),this.appId=a}async handleSendTransaction(r){if(!r.params||!Array.isArray(r.params))throw new Uo(`Invalid params for ${r.method}`,4200);let o=r.params[0];if(!await Ee()||!this.address)throw new Uo("Disconnected",4900);return(await sf(o)).hash}handleSwitchEthereumChain(r){if(!r.params||!Array.isArray(r.params))throw new Uo(`Invalid params for ${r.method}`,4200);let o;if(typeof r.params[0]=="string")o=r.params[0];else if("chainId"in r.params[0]&&typeof r.params[0].chainId=="string")o=r.params[0].chainId;else throw new Uo(`Invalid params for ${r.method}`,4200);this.chainId=Number(o),this.provider=qt(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",o)}async handlePersonalSign(r){if(!r.params||!Array.isArray(r.params))throw new Error("Invalid params for personal_sign");let o=r.params[0],n=r.params[1];return await nf(o,void 0,n)}async handleSignedTypedData(r){if(!r.params||!Array.isArray(r.params))throw new Error("Invalid params for eth_signTypedData_v4");let o=typeof r.params[1]=="string"?JSON.parse(r.params[1]):r.params[1];return await af(pa(o))}async handleEstimateGas(r){if(!r.params||!Array.isArray(r.params))throw new Error("Invalid params for eth_estimateGas");delete r.params[0].gasPrice,delete r.params[0].maxFeePerGas,delete r.params[0].maxPriorityFeePerGas;let o={...r.params[0],chainId:wn(this.chainId)};try{return await this.provider.send("eth_estimateGas",[o])}catch(n){console.warn(`Gas estimation failed with error: ${n}. Retrying gas estimation by omitting the 'from' address`);try{return delete o.from,await this.provider.send("eth_estimateGas",[o])}catch(i){throw console.warn(`Gas estimation failed with error: ${i} when omitting the 'from' address`),n}}}async request(r){switch(console.debug("Embedded1193Provider.request() called with args",r),r.method){case"eth_accounts":case"eth_requestAccounts":return this.address?[this.address]:[];case"eth_chainId":return wn(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(r);case"eth_sendTransaction":return this.handleSendTransaction(r);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(r);case"personal_sign":return this.handlePersonalSign(r);case"eth_signTypedData_v4":return this.handleSignedTypedData(r);default:break}if(of(r.method)){let o=await Ee();if(await lf(),!o||!this.address)throw new Uo("Disconnected",4900);try{return(await this.walletProxy.rpc({address:this.address,accessToken:o,request:{method:r.method,params:r.params}})).response.data}catch(n){throw console.error(n),new Uo("Disconnected",4900)}}else return this.provider.send(r.method,r.params)}async connect(){let r=await Ee();if(!r||!this.address)return null;try{return(await this.walletProxy.connect({address:this.address,accessToken:r})).address}catch(o){return console.error(o),null}}},to=class extends Ke{constructor(r){super(r,r.rpcTimeoutDuration)}},Fo=class extends Ke{constructor(t){super(t,t.rpcTimeoutDuration)}sendAsync(t,r){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};var v3=(e,t)=>{switch(t){case"coinbase_wallet":return e.message.includes("addEthereumChain");default:return e.code===4902||e.message?.includes("4902")}},Kt=class extends g3{constructor(r,o,n,i){super();this.onAccountsChanged=r=>{r.length===0?this.onDisconnect():this.syncAccounts(r)};this.onChainChanged=r=>{this.wallets.forEach(o=>{o.chainId=li(r),this.walletClientType==="privy"&&j.put(zs(o.address),r)}),this.emit("walletsUpdated")};this.onDisconnect=()=>{this.connected=!1,this.wallets=[],this.emit("walletsUpdated")};this.onConnect=()=>{this.connected=!0,this.syncAccounts()};this.wallets=[],this.walletClientType=r,this.chains=o,this.defaultChain=n,this.rpcConfig=i,this.rpcTimeoutDuration=yi(i,r),this.connected=!1,this.initialized=!1}buildConnectedWallet(r,o,n,i){let a=async()=>!!this.wallets.find(l=>ro(l.address)===ro(r));return{address:ro(r),chainId:o,meta:n,imported:i,switchChain:async l=>{if(!a)throw new pe("Wallet is not currently connected.");let s=this.wallets.find(C=>ro(C.address)===ro(r))?.chainId;if(!s)throw new pe("Unable to determine current chainId.");let c,m;if(typeof l=="number"?(c=`0x${l.toString(16)}`,m=l):(c=l,m=Number(l)),s===li(c))return;let f=this.chains.find(C=>C.id===m);if(!f)throw new pe(`Unsupported chainId: ${l}`);let u=async()=>{await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[{chainId:c}]})};try{return await u()}catch(C){if(v3(C,this.walletClientType))return await this.proxyProvider.request({method:"wallet_addEthereumChain",params:[{chainId:c,chainName:f.name,nativeCurrency:f.nativeCurrency,rpcUrls:[f.rpcUrls.default?.http[0]??""],blockExplorerUrls:[f.blockExplorers?.default.url??""]}]}),u();throw this.walletClientType==="rainbow"&&C.message?.includes("wallet_switchEthereumChain")?new pe(`Rainbow does not support the chainId ${o}`):C}},connectedAt:Date.now(),walletClientType:this.walletClientType,connectorType:this.connectorType,isConnected:a,getEthereumProvider:async()=>{if(!await a())throw new pe("Wallet is not currently connected.");return this.proxyProvider},getEthersProvider:async()=>{if(!await a())throw new pe("Wallet is not currently connected.");return new cf(new to(this.proxyProvider))},getWeb3jsProvider:async()=>{if(!await a())throw new pe("Wallet is not currently connected.");return new Fo(this.proxyProvider)},sign:async l=>{if(!await a())throw new pe("Wallet is not currently connected.");return await this.sign(l)},disconnect:()=>{this.disconnect()}}}async syncAccounts(r){let o=r;try{if(o===void 0){let c=await da(()=>this.proxyProvider.request({method:"eth_accounts"}),{maxAttempts:10,delayMs:500});console.debug(`eth_accounts for ${this.walletClientType}:`,c),Array.isArray(c)&&(o=c)}}catch(c){console.warn("Wallet did not respond to eth_accounts. Defaulting to prefetched accounts.",c)}if(!o||!Array.isArray(o)||o.length<=0||!o[0])return;let n=o[0],i=ro(n),a=[],l;if(this.walletClientType==="privy"){let c=j.get(zs(i));this.chains.find(m=>m.id===Number(c))||(j.del(zs(i)),c=null),l=c||`0x${this.defaultChain.id.toString(16)}`;try{await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[{chainId:l}]})}catch{console.warn(`Unable to switch embedded wallet to chain ID ${l} on initialization`)}}else try{let c=await da(()=>this.proxyProvider.request({method:"eth_chainId"}),{maxAttempts:10,delayMs:500});if(console.debug(`eth_chainId for ${this.walletClientType}:`,c),typeof c=="string")l=c;else if(typeof c=="number")l=`0x${c.toString(16)}`;else throw new Error("Invalid chainId returned from provider")}catch(c){console.warn(`Failed to get chainId from provider, defaulting to ${xd}`,c),l=xd}let s=li(l);if(!a.find(c=>ro(c.address)===i)){let c={name:this.walletBranding.name,icon:typeof this.walletBranding.icon=="string"?this.walletBranding.icon:void 0,id:this.walletBranding.id};a.push(this.buildConnectedWallet(ro(n),s,c,this.connectorType==="embedded_imported"))}ll(a,this.wallets)||(this.wallets=a,this.emit("walletsUpdated"))}async getConnectedWallet(){let r=await this.proxyProvider.request({method:"eth_accounts"});return this.wallets.sort((o,n)=>n.connectedAt-o.connectedAt).find(o=>r.find(n=>ro(n)===ro(o.address)))||null}async isConnected(){let r=await this.proxyProvider.request({method:"eth_accounts"});return Array.isArray(r)&&r.length>0}async sign(r){return await this.connect({showPrompt:!1}),new cf(new to(this.proxyProvider)).getSigner().signMessage(r)}subscribeListeners(){this.proxyProvider.on("accountsChanged",this.onAccountsChanged),this.proxyProvider.on("chainChanged",this.onChainChanged),this.proxyProvider.on("disconnect",this.onDisconnect),this.proxyProvider.on("connect",this.onConnect)}unsubscribeListeners(){this.proxyProvider.removeListener("accountsChanged",this.onAccountsChanged),this.proxyProvider.removeListener("chainChanged",this.onChainChanged),this.proxyProvider.removeListener("disconnect",this.onDisconnect),this.proxyProvider.removeListener("connect",this.onConnect)}};var w3=[1,11155111,137,10,8453,84532,42161,7777777,43114,56],df=(e,t)=>e.makeWeb3Provider({options:t}),cl,dl=class extends Kt{constructor(r,o,n,i,a,l){super("coinbase_wallet",r,o,n);this.connectorType="coinbase_wallet";this.displayName="Coinbase Wallet";if(this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.connectionOptions=i.coinbaseWallet.connectionOptions??"all",this.walletClientType=this.connectionOptions==="smartWalletOnly"?"coinbase_smart_wallet":"coinbase_wallet",this.walletClientType==="coinbase_smart_wallet"&&(this.displayName="Coinbase Smart Wallet"),!cl){let s=[o.id].concat(r.map(m=>m.id)),c=this.connectionOptions!=="eoaOnly"?s.filter(m=>!w3.includes(m)):[];c.length>0&&console.warn(`The following configured chains are not supported by the Coinbase Smart Wallet: ${c.join(", ")}`),cl=new C3({appName:a,appLogoUrl:l,appChainIds:s})}this.proxyProvider.setWalletProvider(df(cl,this.connectionOptions))}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return r.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:_o,id:"com.coinbase.wallet"}}async promptConnection(){try{let r=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!r||r.length===0||!r[0])throw new pe("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([r[0]])}catch(r){throw Dr(r)}}updateConnectionPreference(r){this.connectionOptions=r,this.walletClientType=r==="smartWalletOnly"?"coinbase_smart_wallet":"coinbase_wallet",this.proxyProvider.setWalletProvider(df(cl,this.connectionOptions))}};import{jsx as pf}from"react/jsx-runtime";var Bo=({...e})=>pf("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:pf("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:e.color||"var(--privy-color-foreground-3)"})});var ba=class extends Kt{constructor(r,o,n,i,a=!1){super("privy",o,n,i);this.connectorType="embedded";this.proxyProvider=r,a&&(this.connectorType="embedded_imported"),this.subscribeListeners()}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[wn(r?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:Bo,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}};import{jsx as uf}from"react/jsx-runtime";var gi=({style:e,...t})=>uf("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",style:{...e},...t,children:uf("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25"})});import{jsx as ir,jsxs as b3}from"react/jsx-runtime";var vi=({style:e,...t})=>b3("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",...e},...t,children:[ir("style",{children:".s1{stroke-linecap:round;stroke-linejoin:round}.s2{fill:#e4761b;stroke:#e4761b}.s3{fill:#f6851b;stroke:#f6851b}"}),ir("path",{fill:"#e2761b",stroke:"#e2761b",className:"s1",d:"m274.1 35.5-99.5 73.9L193 65.8z"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"})]});import{jsx as mf,jsxs as E3}from"react/jsx-runtime";var oo=({style:e,...t})=>E3("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...e},...t,children:[mf("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),mf("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"})]});var wi=class extends Kt{constructor(r,o,n,i,a){super(a||"unknown",r,o,n);this.connectorType="injected";this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=i;let l=i.provider;this.proxyProvider.setWalletProvider(l)}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return r.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 r=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!r||r.length===0||!r[0])throw new pe("Unable to retrieve accounts");await this.syncAccounts([r[0]])}catch(r){throw Dr(r)}}},Ci,bi=class extends Kt{constructor(r,o,n,i,a){super(a??"unknown",r,o,n);this.connectorType="injected";Es(this,Ci,void 0);this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(i),a==="metamask"?yd(this,Ci,{name:"MetaMask",icon:vi,id:"io.metamask"}):a==="phantom"&&yd(this,Ci,{name:"Phantom",icon:oo,id:"phantom"})}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return r.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return xu(this,Ci)??{name:"Browser Extension",icon:gi,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let r=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!r||r.length===0||!r[0])throw new pe("Unable to retrieve accounts");await this.syncAccounts([r[0]])}catch(r){throw Dr(r)}}};Ci=new WeakMap;import{getAddress as Mk}from"@ethersproject/address";import{Web3Provider as Ok}from"@ethersproject/providers";import{isMobile as T3}from"react-device-detect";var pl=class extends wi{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{T3||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let t=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!t||t.length===0||!t[0])throw new pe("Unable to retrieve accounts");await this.syncAccounts([t[0]])}catch(t){throw Dr(t)}}};var ul=class extends Kt{constructor(r,o){super(r,[],o,{});this.connectorType="null";this.proxyProvider=new Ke(void 0,_n);this.connectorType=r}get walletBranding(){return{name:"Wallet",id:""}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw new Error("connect called for an uninstalled wallet via the NullConnector")}disconnect(){throw new Error("disconnect called for an uninstalled wallet via the NullConnector")}promptConnection(r){throw new Error(`promptConnection called for an uninstalled wallet via the NullConnector for ${r}`)}};var ml=class extends ul{constructor(t){super("phantom",t)}get walletBranding(){return{name:"Phantom",icon:oo,id:"phantom"}}};import{EthereumProvider as Y3,OPTIONAL_EVENTS as j3,OPTIONAL_METHODS as Z3}from"@walletconnect/ethereum-provider";import{isMobile as Q3}from"react-device-detect";import{createContext as B3,useContext as H3,useEffect as Ld,useRef as G3,useState as V3}from"react";import{jsx as S3}from"react/jsx-runtime";function ff({src:e,...t}){return S3("img",{src:e,...t,style:{display:"none"}})}import{useContext as eh,useEffect as Xf,useMemo as N3,useState as D3}from"react";import{createContext as U3}from"react";var Nt={appearance:{landingHeader:"Log in or sign up",theme:"light",accentColor:"#676FFF",walletList:["detected_wallets","metamask","coinbase_wallet","rainbow","wallet_connect"]},walletConnectCloudProjectId:Lm,rpcConfig:{rpcUrls:{},rpcTimeouts:{}},externalWallets:{coinbaseWallet:{connectionOptions:"all"}},captchaEnabled:!1,_render:{standalone:!1},fundingMethodConfig:{moonpay:{useSandbox:!1}}};var hf=({input:e})=>{if(!e||!e.primary[0])return;let t=[e.primary[0]],r=[];e.primary.length>4&&console.warn("You should not specify greater than 4 login methods in `loginMethodsAndOrder.primary`");for(let o of e.primary.slice(1))t.includes(o)?console.warn(`Duplicated login method: ${o}`):t.push(o);for(let o of e.overflow??[])!t.includes(o)&&!r.includes(o)?r.push(o):console.warn(`Duplicated login method: ${o}`);return{primary:t,overflow:r}};var _3=new Set(["coinbase_wallet","cryptocom","metamask","okx_wallet","phantom","rainbow","uniswap","zerion","wallet_connect","detected_wallets","rabby_wallet","safe"]),yf=e=>_3.has(e),gf=(e,t,r)=>r.indexOf(e)===t,vf=({input:e,overrides:t})=>t?t.primary.concat(t.overflow??[]).filter(yf).filter(gf):e?e.filter(yf).filter(gf):Nt.appearance.walletList;var Cf={id:42161,name:"Arbitrum One",network:"arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-mainnet.rpc.privy.systems"]},alchemy:{http:["https://arb-mainnet.g.alchemy.com/v2"],webSocket:["wss://arb-mainnet.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-mainnet.infura.io/v3"],webSocket:["wss://arbitrum-mainnet.infura.io/ws/v3"]},default:{http:["https://arb1.arbitrum.io/rpc"]},public:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://arbiscan.io"},default:{name:"Arbiscan",url:"https://arbiscan.io"}}};var wf={id:421613,name:"Arbitrum Goerli",network:"arbitrum-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"AGOR",decimals:18},rpcUrls:{default:{http:["https://goerli-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"}},testnet:!0};var bf={id:421614,name:"Arbitrum Sepolia",network:"arbitrum-sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]},public:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Blockscout",url:"https://sepolia-explorer.arbitrum.io"}},testnet:!0};var Ef={id:43114,name:"Avalanche",network:"avalanche",nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]},public:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://snowtrace.io"},default:{name:"SnowTrace",url:"https://snowtrace.io"}}};var Tf={id:43113,name:"Avalanche Fuji",network:"avalanche-fuji",nativeCurrency:{decimals:18,name:"Avalanche Fuji",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax-test.network/ext/bc/C/rpc"]},public:{http:["https://api.avax-test.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://testnet.snowtrace.io"},default:{name:"SnowTrace",url:"https://testnet.snowtrace.io"}},testnet:!0};var Sf={id:8453,network:"base",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-mainnet.rpc.privy.systems"]},blast:{http:["https://base-mainnet.blastapi.io"],webSocket:["wss://base-mainnet.blastapi.io"]},default:{http:["https://mainnet.base.org"]},public:{http:["https://mainnet.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://basescan.org"},default:{name:"Basescan",url:"https://basescan.org"}},testnet:!0};var _f={id:84531,network:"base-goerli",name:"Base Goerli Testnet",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://goerli.basescan.org"}},testnet:!0};var Pf={id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.base.org"]},public:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Blockscout",url:"https://base-sepolia.blockscout.com"}},testnet:!0};var Af={id:80085,network:"berachain-artio",name:"Berachain Artio",nativeCurrency:{name:"BERA",symbol:"BERA",decimals:18},rpcUrls:{default:{http:["https://berachain-artio.rpc.privy.systems"]},public:{http:["https://berachain-artio.rpc.privy.systems"]}},blockExplorers:{default:{name:"Beratrail",url:"https://artio.beratrail.io"}},testnet:!0};var xf={id:42220,name:"Celo Mainnet",network:"celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]},infura:{http:["https://celo-mainnet.infura.io/v3"]},public:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/mainnet"},etherscan:{name:"CeloScan",url:"https://celoscan.io"}},testnet:!1};var kf={id:44787,name:"Celo Alfajores Testnet",network:"celo-alfajores",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://alfajores-forno.celo-testnet.org"]},infura:{http:["https://celo-alfajores.infura.io/v3"]},public:{http:["https://alfajores-forno.celo-testnet.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/alfajores"},etherscan:{name:"CeloScan",url:"https://alfajores.celoscan.io/"}},testnet:!0};var Rf={id:314,name:"Filecoin - Mainnet",network:"filecoin-mainnet",nativeCurrency:{decimals:18,name:"filecoin",symbol:"FIL"},rpcUrls:{default:{http:["https://api.node.glif.io/rpc/v1"]},public:{http:["https://api.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filfox",url:"https://filfox.info/en"},filscan:{name:"Filscan",url:"https://filscan.io"},filscout:{name:"Filscout",url:"https://filscout.io/en"},glif:{name:"Glif",url:"https://explorer.glif.io"}}};var If={id:314159,name:"Filecoin - Calibration testnet",network:"filecoin-calibration",nativeCurrency:{decimals:18,name:"testnet filecoin",symbol:"tFIL"},rpcUrls:{default:{http:["https://api.calibration.node.glif.io/rpc/v1"]},public:{http:["https://api.calibration.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filscan",url:"https://calibration.filscan.io"}}};var Mf={id:17069,name:"Garnet Holesky",network:"garnet-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.garnetchain.com"]},public:{http:["https://rpc.garnetchain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.garnetchain.com"}}};var Wf={id:5,network:"goerli",name:"Goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.ankr.com/eth_goerli"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.etherscan.io"}},testnet:!0};var Of={id:17e3,name:"Holesky",network:"holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-holesky.publicnode.com"]},public:{http:["https://ethereum-holesky.publicnode.com"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://holesky.etherscan.io"},default:{name:"EtherScan",url:"https://holesky.etherscan.io"}}};var Lf={id:59144,network:"linea-mainnet",name:"Linea Mainnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]},public:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://lineascan.build"},etherscan:{name:"Etherscan",url:"https://lineascan.build"}},testnet:!1};var Nf={id:59140,network:"linea-testnet",name:"Linea Goerli Testnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-goerli.infura.io/v3"],webSocket:["wss://linea-goerli.infura.io/ws/v3"]},default:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]},public:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.lineascan.build"},etherscan:{name:"Etherscan",url:"https://goerli.lineascan.build"}},testnet:!0};var Df={id:42,network:"lukso",name:"LUKSO",nativeCurrency:{name:"LUKSO",symbol:"LYX",decimals:18},rpcUrls:{default:{http:["https://rpc.mainnet.lukso.network"],webSocket:["wss://ws-rpc.mainnet.lukso.network"]}},blockExplorers:{default:{name:"LUKSO Mainnet Explorer",url:"https://explorer.execution.mainnet.lukso.network"}}};var fl={id:1,network:"homestead",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://mainnet.rpc.privy.systems"]},alchemy:{http:["https://eth-mainnet.g.alchemy.com/v2"],webSocket:["wss://eth-mainnet.g.alchemy.com/v2"]},infura:{http:["https://mainnet.infura.io/v3"],webSocket:["wss://mainnet.infura.io/ws/v3"]},default:{http:["https://cloudflare-eth.com"]},public:{http:["https://cloudflare-eth.com"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://etherscan.io"},default:{name:"Etherscan",url:"https://etherscan.io"}}};var Uf={id:10,name:"OP Mainnet",network:"optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-mainnet.rpc.privy.systems"]},alchemy:{http:["https://opt-mainnet.g.alchemy.com/v2"],webSocket:["wss://opt-mainnet.g.alchemy.com/v2"]},infura:{http:["https://optimism-mainnet.infura.io/v3"],webSocket:["wss://optimism-mainnet.infura.io/ws/v3"]},default:{http:["https://mainnet.optimism.io"]},public:{http:["https://mainnet.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://optimistic.etherscan.io"},default:{name:"Optimism Explorer",url:"https://explorer.optimism.io"}}};var Ff={id:420,name:"Optimism Goerli Testnet",network:"optimism-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.optimism.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"}},testnet:!0};var Bf={id:11155420,name:"Optimism Sepolia",network:"optimism-sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.optimism.io"]},public:{http:["https://sepolia.optimism.io"]},infura:{http:["https://optimism-sepolia.infura.io/v3"]}},blockExplorers:{default:{name:"Blockscout",url:"https://optimism-sepolia.blockscout.com"}},testnet:!0};var Hf={id:137,name:"Polygon Mainnet",network:"matic",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{privy:{http:["https://polygon-mainnet.rpc.privy.systems"]},alchemy:{http:["https://polygon-mainnet.g.alchemy.com/v2"],webSocket:["wss://polygon-mainnet.g.alchemy.com/v2"]},infura:{http:["https://polygon-mainnet.infura.io/v3"],webSocket:["wss://polygon-mainnet.infura.io/ws/v3"]},default:{http:["https://polygon-rpc.com"]},public:{http:["https://polygon-rpc.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://polygonscan.com"},default:{name:"PolygonScan",url:"https://polygonscan.com"}}};var Gf={id:80001,name:"Mumbai",network:"maticmum",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{default:{http:["https://matic-mumbai.chainstacklabs.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"}},testnet:!0};var Vf={id:690,name:"Redstone",network:"redstone",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.redstonechain.com"]},public:{http:["https://rpc.redstonechain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.redstone.xyz/"}}};var qf={id:17001,name:"Redstone Holesky",network:"redstone-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.holesky.redstone.xyz"]},public:{http:["https://rpc.holesky.redstone.xyz"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"},default:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"}}};var zf={id:11155111,network:"sepolia",name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"SEP",decimals:18},rpcUrls:{privy:{http:["https://sepolia.rpc.privy.systems"]},alchemy:{http:["https://eth-sepolia.g.alchemy.com/v2"],webSocket:["wss://eth-sepolia.g.alchemy.com/v2"]},infura:{http:["https://sepolia.infura.io/v3"],webSocket:["wss://sepolia.infura.io/ws/v3"]},default:{http:["https://rpc.sepolia.org"]},public:{http:["https://rpc.sepolia.org"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://sepolia.etherscan.io"},default:{name:"Etherscan",url:"https://sepolia.etherscan.io"}},testnet:!0};var $f={id:7777777,name:"Zora",network:"zora",nativeCurrency:{decimals:18,name:"Ether",symbol:"ETH"},rpcUrls:{default:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]},public:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://explorer.zora.energy"}}};var Kf={id:999999999,name:"Zora Sepolia",network:"zora-sepolia",nativeCurrency:{decimals:18,name:"Zora Sepolia",symbol:"ETH"},rpcUrls:{default:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]},public:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]}},blockExplorers:{default:{name:"Zora Sepolia Explorer",url:"https://sepolia.explorer.zora.energy/"}},testnet:!0};var Yf={id:999,name:"Zora Goerli Testnet",network:"zora-testnet",nativeCurrency:{decimals:18,name:"Zora Goerli",symbol:"ETH"},rpcUrls:{default:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]},public:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://testnet.explorer.zora.energy"}},testnet:!0};var Ea=[Cf,wf,bf,Wf,zf,fl,Uf,Ff,Bf,Hf,Gf,xf,kf,Rf,If,Sf,_f,Pf,Af,Df,Lf,Nf,Ef,Tf,$f,Yf,Kf,Of,Vf,Mf,qf],lI=new Set(Ea.map(e=>e.id));import In from"tinycolor2";var jf="#FFFFFF",P3="#040217",A3=jf,x3="#1E1E1D";function k3(e){return e<.8&&e>.2&&console.warn("Background color is not light or dark enough, which could lead to accessibility issues."),e>.5?"light":"dark"}function Ur(e,t){let r=Math.max(0,Math.min(1,e.toHsl().l+t));return In({...e.toHsl(),l:r})}var R3="#51BA81",I3="#FFB74D",M3="#EC6351",W3=jf,O3=P3;function Zf({backgroundTheme:e,accentHex:t}){let r;switch(e){case"light":r=A3;break;case"dark":r=x3;break;default:r=e;break}let o=In(r),n=In(t),i=In(R3),a=In(I3),l=In(M3),s=k3(o.getLuminance()),c=Ur(o,s==="light"?-.04:.11),m=Ur(o,s==="light"?-.88:.87),f=Ur(o,s==="light"?-.7:.75),u=Ur(o,s==="light"?-.43:.45).desaturate(s==="light"?60:20),C=Ur(o,s==="light"?-.08:.25).desaturate(s==="light"?60:20),v=Ur(n,.15),g=Ur(n,-.06),b=Ur(l,.3),E=Ur(a,.3),k=In(n.getLuminance()>.5?O3:W3),_=Ur(i,-.16),S=Ur(i,.4);return{colorScheme:s,background:o.toHslString(),background2:c.toHslString(),foreground:m.toHslString(),foreground2:f.toHslString(),foreground3:u.toHslString(),foreground4:C.toHslString(),accent:n.toHslString(),accentLight:v.toHslString(),accentDark:g.toHslString(),foregroundAccent:k.toHslString(),success:i.toHslString(),successDark:_.toHslString(),successLight:S.toHslString(),error:l.toHslString(),errorLight:b.toHslString(),warn:a.toHslString(),warnLight:E.toHslString()}}function Md(e,t,r){let o=r?console.warn:()=>{},n,i,a,l,s,c,m,f,u,C,v,g,b,E,k;t?.loginMethods?(n=t.loginMethods.includes("email"),i=t.loginMethods.includes("sms"),l=t.loginMethods.includes("wallet"),s=t.loginMethods.includes("google"),c=t.loginMethods.includes("twitter"),m=t.loginMethods.includes("discord"),u=t.loginMethods.includes("spotify"),C=t.loginMethods.includes("instagram"),f=t.loginMethods.includes("tiktok"),g=t.loginMethods.includes("github"),v=t.loginMethods.includes("linkedin"),b=t.loginMethods.includes("apple"),E=t.loginMethods.includes("farcaster"),k=t.loginMethods.includes("telegram")):(n=e.emailAuth,i=e.smsAuth,l=e.walletAuth,s=e.googleOAuth,c=e.twitterOAuth,m=e.discordOAuth,g=e.githubOAuth,u=e.spotifyOAuth,C=e.instagramOAuth,f=e.tiktokOAuth,v=e.linkedinOAuth,b=e.appleOAuth,E=e.farcasterAuth,k=e.telegramAuth),typeof window<"u"&&typeof window.PublicKeyCredential!="function"?a=!1:e.passkeyAuth&&(a=!0);let _=[n,i].filter(Boolean),S=[s,c,m,g,u,C,f,v,b,E,k].filter(Boolean),R=[l].filter(Boolean);if(_.length+S.length+R.length===0)throw new Error("You must enable at least one login method");let M=t?.appearance?.showWalletLoginFirst!==void 0?t?.appearance?.showWalletLoginFirst:e.showWalletLoginFirst;M&&R.length===0?(o("You should only enable `showWalletLoginFirst` when `wallet` logins are also enabled. `showWalletLoginFirst` has been set to false"),M=!1):!M&&S.length+_.length===0&&(o("You should only disable `showWalletLoginFirst` when `email`, `sms`, or social logins are also enabled. `showWalletLoginFirst` has been set to true"),M=!0);let D=t?.externalWallets?.walletConnect?.enabled??!0;t?.loginMethods&&t.loginMethodsAndOrder&&o("You should only configure one of `loginMethods` or `loginMethodsAndOrder`");let H=vf({input:t?.appearance?.walletList,overrides:t?.loginMethodsAndOrder}),K=hf({input:t?.loginMethodsAndOrder}),Y=t?.intl?.defaultCountry??"US",{chains:O,defaultChain:U}=L3({additionalChains:t?.additionalChains,supportedChains:t?.supportedChains,defaultChainFromConfig:t?.defaultChain,hasRpcConfigDefined:Object.keys(t?.rpcConfig?.rpcUrls??{}).length>0}),W=!!t?.defaultChain,be=t?.customAuth?.getCustomAccessToken&&t?.customAuth?.enabled!==!1,ce,X=!(e.enforceWalletUis??!0);if(e.legacyWalletUiConfig??!0?be?ce=t?.embeddedWallets?.noPromptOnSignature??!0:ce=t?.embeddedWallets?.noPromptOnSignature??X:ce=X,t?.embeddedWallets?.waitForTransactionConfirmation===!1&&ce!==!0)throw new Error("Overriding `config.embeddedWallets.waitForTransactionConfirmation` requires that you disable wallet UIs in the dashboard.");let{requireUserPasswordOnCreate:ne,...ee}=t?.embeddedWallets??{};return{id:e.id,name:e.name,allowlistConfig:e.allowlistConfig,legacyWalletUiConfig:e.legacyWalletUiConfig,appearance:{logo:t?.appearance?.logo??e.logoUrl,landingHeader:t?.appearance?.landingHeader??Nt.appearance.landingHeader,loginMessage:typeof t?.appearance?.loginMessage=="string"?t?.appearance?.loginMessage.slice(0,100):t?.appearance?.loginMessage,palette:Zf({backgroundTheme:t?.appearance?.theme??Nt.appearance.theme,accentHex:t?.appearance?.accentColor??e.accentColor??Nt.appearance.accentColor}),loginGroupPriority:M?"web3-first":"web2-first",hideDirectWeb2Inputs:!!t?.appearance?.hideDirectWeb2Inputs,walletList:H},loginMethods:{wallet:l,email:n,sms:i,passkey:a,google:s,twitter:c,discord:m,github:g,spotify:u,instagram:C,tiktok:f,linkedin:v,apple:b,farcaster:E,telegram:k},loginMethodsAndOrder:K,legal:{termsAndConditionsUrl:t?.legal?.termsAndConditionsUrl??e.termsAndConditionsUrl,privacyPolicyUrl:t?.legal?.privacyPolicyUrl??e.privacyPolicyUrl,requireUsersAcceptTerms:e.requireUsersAcceptTerms??!1},walletConnectCloudProjectId:t?.walletConnectCloudProjectId??e.walletConnectCloudProjectId??Nt.walletConnectCloudProjectId,rpcConfig:{rpcUrls:t?.rpcConfig?.rpcUrls??Nt.rpcConfig.rpcUrls,rpcTimeouts:t?.rpcConfig?.rpcTimeouts??Nt.rpcConfig.rpcTimeouts},chains:O,defaultChain:U,intl:{defaultCountry:Y},shouldEnforceDefaultChainOnConnect:W,captchaEnabled:e.captchaEnabled??Nt.captchaEnabled,captchaSiteKey:e.captchaSiteKey,externalWallets:{coinbaseWallet:{connectionOptions:t?.externalWallets?.coinbaseWallet?.connectionOptions??Nt.externalWallets.coinbaseWallet.connectionOptions},walletConnect:{enabled:D}},embeddedWallets:{...e.embeddedWalletConfig,...typeof ne=="boolean"?{requireUserOwnedRecoveryOnCreate:ne}:{},...be?{createOnLogin:"all-users",requireUserOwnedRecoveryOnCreate:!1,userOwnedRecoveryOptions:["user-passcode"]}:{},waitForTransactionConfirmation:!0,priceDisplay:{primary:"fiat-currency",secondary:"native-token"},...ee,noPromptOnSignature:ce},mfa:{methods:e.mfaMethods??[],noPromptOnMfaRequired:t?.mfa?.noPromptOnMfaRequired??!1},customAuth:be?{enabled:!0,...t.customAuth}:void 0,loginConfig:{twitterOAuthOnMobileEnabled:e.twitterOAuthOnMobileEnabled??!1,telegramAuthConfiguration:e.telegramAuthConfiguration},headless:!!t?.headless,render:{standalone:t?._render?.standalone??Nt._render.standalone},fundingConfig:e.fundingConfig,fundingMethodConfig:{...t?.fundingMethodConfig??Nt.fundingMethodConfig,moonpay:{...t?.fundingMethodConfig?.moonpay??Nt.fundingMethodConfig.moonpay,useSandbox:t?.fundingMethodConfig?.moonpay.useSandbox??t?.fiatOnRamp?.useSandbox??Nt.fundingMethodConfig.moonpay.useSandbox}}}}function Qf(e,t){if(!e)return{legacyCreateEmbeddedWalletFlag:t};let{appearance:r,additionalChains:o,supportedChains:n,defaultChain:i,...a}=e;return{...a,...o?{additionalChains:o.map(s=>s.id)}:void 0,...n?{supportedChains:n.map(s=>s.id)}:void 0,...i?{defaultChain:i.id}:void 0,legacyCreateEmbeddedWalletFlag:t}}function L3({additionalChains:e,supportedChains:t,defaultChainFromConfig:r,hasRpcConfigDefined:o}){let n;if(e&&t&&console.warn("You should only specify one of `additionalChains` or `supportedChains`. Using `supportedChains`."),t){if(t.length===0)throw new Error("`supportedChains` must contain at least one chain");t.filter(s=>s.rpcUrls.privyWalletOverride).length>0&&o&&console.warn("You have specified at least one `supportedChain` with `privyWalletOverride` but also have `rpcConfig` defined. The `rpcConfig` will be ignored. `rpcConfig` is deprecated and you should use `privyWalletOverride` in a `supportedChain`."),n=t.map(s=>s.rpcUrls.privyWalletOverride?s:Ea.find(m=>m.id===s.id)??s)}else n=Ea.concat(e??[]);let i=t?n[0]:fl,a=r??i;if(!n.find(l=>l.id===a.id))throw new Error("`defaultChain` must be included in `supportedChains`");return{chains:n,defaultChain:a}}var Jf=function(e,t=0){let r=3735928559^t,o=1103547991^t;for(let n=0,i;n<e.length;n++)i=e.charCodeAt(n),r=Math.imul(r^i,2654435761),o=Math.imul(o^i,1597334677);return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)};import{jsx as F3}from"react/jsx-runtime";var th={showWalletLoginFirst:!0,allowlistConfig:{errorTitle:null,errorDetail:null,errorCtaText:null,errorCtaLink:null},walletAuth:!0,emailAuth:!0,smsAuth:!1,googleOAuth:!1,twitterOAuth:!1,discordOAuth:!1,githubOAuth:!1,linkedinOAuth:!1,appleOAuth:!1,termsAndConditionsUrl:null,privacyPolicyUrl:null,embeddedWalletConfig:{createOnLogin:"off",requireUserOwnedRecoveryOnCreate:!1,userOwnedRecoveryOptions:["user-passcode"]},fiatOnRampEnabled:!1,captchaEnabled:!1,captchaSiteKey:""},Wd=Md(th,void 0,!1),Od=U3({appConfig:Wd,isServerConfigLoaded:!1}),rh=({children:e,legacyCreateEmbeddedWalletFlag:t,client:r,clientConfig:o})=>{let[n,i]=D3(null),a=N3(()=>Md(n??th,o,!!n),[n,o]);return Xf(()=>{if(!n)return;let l=Qf(o,t),s=Jf(JSON.stringify(l)).toString(),c=`privy:sent:${n.id}:${s}`;localStorage.getItem(c)||(r.createAnalyticsEvent({eventName:"sdk_initialize",payload:l}),localStorage.setItem(c,"t"))},[o,t,n]),Xf(()=>{n||(async()=>{try{let s=await r.getServerConfig();s.customApiUrl&&r.updateApiUrl(s.customApiUrl),i(s)}catch(s){console.warn("Error generating app config: ",s)}})()},[]),F3(Od.Provider,{value:{appConfig:a,isServerConfigLoaded:!!n},children:e})},Ne=()=>{let{appConfig:e}=eh(Od);return e},hl=()=>{let{isServerConfigLoaded:e}=eh(Od);return e};var T=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};import{jsx as z3,jsxs as $3}from"react/jsx-runtime";var oh=B3({ready:!1,app:Wd,currentScreen:null,lastScreen:null,navigate:T,navigateBack:T,resetNavigation:T,setModalData:T,onUserCloseViaDialogOrKeybindRef:void 0}),q3=["LANDING","CONNECT_ONLY_LANDING_SCREEN",null],nh=e=>{let t=Ne(),r=e.authenticated,[o,n]=V3(e.initialScreen);Ld(()=>{!r&&!q3.includes(e.initialScreen)&&e.setInitialScreen(null)},[r]);let i=G3(null);Ld(()=>{e.open||(i.current=null)},[e.open]),Ld(()=>{i.current=null},[e.initialScreen]);let a={ready:!!t.id,app:t,data:e.data,setModalData:e.setModalData,currentScreen:e.initialScreen,lastScreen:o,navigate:(l,s=!0)=>{e.setInitialScreen(l),s&&n(e.initialScreen)},navigateBack:()=>{e.setInitialScreen(o)},resetNavigation:()=>{e.setInitialScreen(null),n(null)},onUserCloseViaDialogOrKeybindRef:i};return $3(oh.Provider,{value:a,children:[(typeof t.appearance.logo=="string"||t.appearance.logo?.type==="img")&&z3(ff,{src:typeof t.appearance.logo=="string"?t.appearance.logo:t.appearance.logo.props.src}),e.children]})},P=()=>H3(oh);import{jsx as Ei,jsxs as K3}from"react/jsx-runtime";var Ta=({style:e,...t})=>{let{app:r}=P();return K3("svg",{width:"28",height:"28",viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...e},...t,children:[Ei("rect",{width:"28",height:"28",rx:"3",fill:r?.appearance.palette.colorScheme==="dark"?"#3396ff":"#141414"}),Ei("g",{clipPath:"url(#clip0_1765_9946)",children:Ei("path",{d:"M8.09448 10.3941C11.3558 7.20196 16.6442 7.20196 19.9055 10.3941L20.2982 10.7782C20.3369 10.8157 20.3677 10.8606 20.3887 10.9102C20.4097 10.9599 20.4206 11.0132 20.4206 11.0671C20.4206 11.121 20.4097 11.1744 20.3887 11.224C20.3677 11.2737 20.3369 11.3186 20.2982 11.3561L18.9554 12.6702C18.9158 12.7086 18.8628 12.7301 18.8077 12.7301C18.7526 12.7301 18.6996 12.7086 18.66 12.6702L18.1198 12.1415C15.8448 9.91503 12.1557 9.91503 9.88015 12.1415L9.30167 12.7075C9.26207 12.7459 9.20909 12.7673 9.15395 12.7673C9.0988 12.7673 9.04582 12.7459 9.00622 12.7075L7.66346 11.3934C7.62475 11.3559 7.59397 11.3109 7.57295 11.2613C7.55193 11.2117 7.5411 11.1583 7.5411 11.1044C7.5411 11.0505 7.55193 10.9971 7.57295 10.9475C7.59397 10.8979 7.62475 10.8529 7.66346 10.8154L8.09448 10.3941ZM22.6829 13.1115L23.8776 14.2814C23.9163 14.319 23.9471 14.3639 23.9681 14.4135C23.9892 14.4632 24 14.5165 24 14.5704C24 14.6243 23.9892 14.6777 23.9681 14.7273C23.9471 14.777 23.9163 14.8219 23.8776 14.8594L18.4893 20.1332C18.4102 20.2101 18.3042 20.2531 18.1938 20.2531C18.0835 20.2531 17.9775 20.2101 17.8984 20.1332L14.0743 16.3901C14.0545 16.3708 14.0279 16.36 14.0003 16.36C13.9726 16.36 13.9461 16.3708 13.9263 16.3901L10.1021 20.1332C10.023 20.2101 9.91703 20.2531 9.8067 20.2531C9.69636 20.2531 9.59038 20.2101 9.51124 20.1332L4.12236 14.8594C4.08365 14.8219 4.05287 14.777 4.03185 14.7273C4.01083 14.6777 4 14.6243 4 14.5704C4 14.5165 4.01083 14.4632 4.03185 14.4135C4.05287 14.3639 4.08365 14.319 4.12236 14.2814L5.31767 13.1115C5.39678 13.0348 5.50265 12.9919 5.61285 12.9919C5.72305 12.9919 5.82892 13.0348 5.90803 13.1115L9.73216 16.8546C9.75194 16.874 9.7785 16.8848 9.80616 16.8848C9.83381 16.8848 9.86037 16.874 9.88015 16.8546L13.7043 13.1115C13.7834 13.0346 13.8894 12.9916 13.9997 12.9916C14.1101 12.9916 14.216 13.0346 14.2952 13.1115L18.1198 16.8546C18.1396 16.874 18.1662 16.8848 18.1938 16.8848C18.2215 16.8848 18.2481 16.874 18.2678 16.8546L22.092 13.1115C22.1711 13.0346 22.2771 12.9916 22.3874 12.9916C22.4977 12.9916 22.6037 13.0346 22.6829 13.1115Z",fill:"white"})}),Ei("defs",{children:Ei("clipPath",{id:"clip0_1765_9946",children:Ei("rect",{width:"20",height:"12.2531",fill:"white",transform:"translate(4 8)"})})})]})};var Fr=class extends Kt{constructor(r,o,n,i,a,l,s,c){super(c||"unknown",n,i,o);this.connectorType="wallet_connect_v2";this.privyAppId=l,this.privyAppName=s,this.walletConnectCloudProjectId=r,this.rpcConfig=o,this.shouldEnforceDefaultChainOnConnect=a,this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),c&&(this.walletEntry=Us[c],this.walletClientType=c)}async initialize(){let r=await this.createProvider();if(this.provider=r,this.proxyProvider.setWalletProvider(r),this.subscribeListeners(),r.session){if(this.walletProvider?.session?.peer.metadata.url){let n=Ds(this.walletProvider?.session?.peer.metadata.url);this.walletEntry=n?.entry,this.walletClientType=n?.walletClientType||"unknown"}this.connected=!0,await this.syncAccounts()}this.initialized=!0,this.emit("initialized");let{WalletConnectModal:o}=await import("@walletconnect/modal");this.modal=new o({projectId:this.walletConnectCloudProjectId,themeVariables:{"--wcm-z-index":"1000000"}}),this.modal.subscribeModal(n=>{!n.open&&!this.walletProvider?.session&&this.onQrModalClosed&&this.onQrModalClosed()})}async connect(r){return r.showPrompt&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return!!this.walletProvider?.connected}get walletBranding(){return this.walletClientType==="metamask"?{name:"MetaMask",icon:vi,id:"io.metamask"}:{name:bm(this.walletProvider?.session?.peer.metadata.name||"")||"WalletConnect",icon:this.walletProvider?.session?.peer.metadata.icons?.[0]||Ta,id:this.walletProvider?.session?.peer.metadata.name.toLowerCase()||"wallet_connect_v2"}}async resetConnection(r){this.walletProvider&&this.walletProvider.connected&&(await this.walletProvider.disconnect(),this.walletProvider.signer.session=void 0,this.walletEntry=Us[r],this.walletClientType=r,this.redirectUri=void 0,this.fallbackUniversalRedirectUri=void 0,Rm(),this.onDisconnect())}async promptConnection(){if(this.provider)return new Promise((r,o)=>{let n=()=>{o(new hi)};this.onQrModalClosed=n,(async()=>{let a="",l=await Promise.race([this.walletProvider?.enable(),this.proxyProvider.walletTimeout()]);if(l?.length&&(a=l[0]),!a||a==="")throw new pe("Unable to retrieve address");if(this.walletProvider?.session?.peer.metadata.url){let s=Ds(this.walletProvider?.session?.peer.metadata.url);this.walletEntry=s?.entry,this.walletClientType=s?.walletClientType||"unknown",this.proxyProvider.rpcTimeoutDuration=yi(this.rpcConfig,this.walletClientType)}this.connected=!0,await this.syncAccounts(l),r()})().catch(a=>{if(a){o(Dr(a));return}o(new pe("Unknown error during connection"))}).finally(()=>this.modal?.closeModal())})}disconnect(){this.walletProvider?.disconnect().then(()=>this.onDisconnect()).catch(()=>console.warn("Unable to disconnect Wallet Connect provider"))}get walletProvider(){return this.proxyProvider.walletProvider}setWalletProvider(r){this.proxyProvider.setWalletProvider(r)}async createProvider(){let r={};for(let a of this.chains){let l=Tm(a.id,this.chains,this.rpcConfig,this.privyAppId);l&&(r[a.id]=l)}let o=this.shouldEnforceDefaultChainOnConnect?[this.defaultChain.id]:[],n=this.chains.map(a=>a.id),i=await Y3.init({projectId:this.walletConnectCloudProjectId,chains:o,optionalChains:n,optionalEvents:j3,optionalMethods:Z3,rpcMap:r,showQrModal:!1,metadata:{description:this.privyAppName,name:this.privyAppName,url:window.location.toString(),icons:[]}});return i.on("display_uri",a=>{if(i.signer.abortPairingAttempt(),Q3&&this.walletEntry){let{redirect:l,href:s}=Am(a,this.walletEntry);Im({href:s,name:this.walletEntry.displayName}),this.redirectUri=l;let c=xm(a,this.walletEntry);c?.redirect&&(this.fallbackUniversalRedirectUri=c.redirect),Fs(l,"_self")}else this.modal?.openModal({uri:a,chains:[this.defaultChain.id]})}),i.on("connect",()=>{if(this.modal?.closeModal(),i.session?.peer.metadata.url){let a=Ds(i.session?.peer.metadata.url);this.walletEntry=a?.entry,this.walletClientType=a?.walletClientType||"unknown"}}),i}async enableProvider(){return this.walletProvider?.connected?Promise.resolve(this.walletProvider.accounts):await this.walletProvider?.enable()}};var Dd=e=>{let t=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses")?.split(" ").filter(o=>J3(o)).map(o=>ih(o));return t?.length?!!e?.linkedAccounts.filter(o=>o.type=="wallet"&&t.includes(o.address)).length:!1},yi=(e,t)=>e.rpcTimeouts?e.rpcTimeouts[t]||_n:_n,Sa=class extends X3{constructor(r,o,n,i,a,l,s,c,m,f,u){super();this.getEthereumProvider=()=>{let r=this.wallets[0],o=this.walletConnectors.find(n=>n.wallets.find(i=>i.address===r?.address));return!r||!o?new Ke:o.proxyProvider};this.privyAppId=r,this.walletConnectCloudProjectId=o,this.rpcConfig=n,this.chains=i,this.defaultChain=a,this.walletConnectors=[],this.initialized=!1,this.store=l,this.walletList=s,this.shouldEnforceDefaultChainOnConnect=c,this.externalWalletConfig=m,this.privyAppName=f,this.privyAppLogo=u,this.storedConnections=Nd()}get wallets(){let r=new Set,o=this.walletConnectors.flatMap(i=>i.wallets).sort((i,a)=>i.connectedAt&&a.connectedAt?a.connectedAt-i.connectedAt:0).filter(i=>{let a=`${i.address}${i.walletClientType}${i.connectorType}`;return r.has(a)?!1:(r.add(a),!0)}),n=o.findIndex(i=>i.address===(this.activeWallet?this.activeWallet:"unknown"));return n>=0&&o.unshift(o.splice(n,1)[0]),o}async initialize(){if(this.initialized)return;j.get(Pd)&&(j.getKeys().forEach(o=>{o.startsWith("walletconnect")&&j.del(o)}),j.del(Pd));let r=Em(this.store,this.walletList,this.externalWalletConfig).then(o=>{o.forEach(({type:n,eip6963InjectedProvider:i,legacyInjectedProvider:a})=>{this.createWalletConnector("injected",n,{eip6963InjectedProvider:i,legacyInjectedProvider:a})})});this.walletList.includes("coinbase_wallet")&&this.createWalletConnector("coinbase_wallet","coinbase_wallet"),!No()&&this.walletList.includes("phantom")&&this.createWalletConnector("phantom","phantom"),this.externalWalletConfig.walletConnect.enabled&&this.createWalletConnector("wallet_connect_v2","unknown"),await r,this.initialized=!0}findWalletConnector(r,o){return r==="wallet_connect_v2"?this.walletConnectors.find(n=>n.connectorType===r)??null:this.walletConnectors.find(n=>n.connectorType===r&&n.walletClientType===o)??null}onInitialized(r){r.wallets.forEach(o=>{let n=this.storedConnections.find(i=>i.address===o.address&&i.connectorType===o.connectorType&&i.walletClientType===o.walletClientType);n&&(o.connectedAt=n.connectedAt)}),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(r){r.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnector(r,o,n,i){let a=this.findWalletConnector("embedded","privy");if(a)a.proxyProvider.walletProxy=r;else{let l=new wa(r,o,this.rpcConfig,this.chains,i,n.id),s=new ba(l,this.chains,n,this.rpcConfig);this.addWalletConnector(s)}}addImportedWalletConnector(r,o,n,i){let a=this.findWalletConnector("embedded_imported","privy");if(a)a.proxyProvider.walletProxy=r;else{let l=new wa(r,o,this.rpcConfig,this.chains,i,n.id),s=!0,c=new ba(l,this.chains,n,this.rpcConfig,s);this.addWalletConnector(c)}}removeEmbeddedWalletConnector(){let r=this.findWalletConnector("embedded","privy");if(r){let o=this.walletConnectors.indexOf(r);this.walletConnectors.splice(o,1),this.saveConnectionHistory(),this.storedConnections=Nd(),this.emit("walletsUpdated")}}removeImportedWalletConnector(){let r=this.findWalletConnector("embedded_imported","privy");if(r){let o=this.walletConnectors.indexOf(r);this.walletConnectors.splice(o,1),this.saveConnectionHistory(),this.storedConnections=Nd(),this.emit("walletsUpdated")}}async createWalletConnector(r,o,n){let i=this.findWalletConnector(r,o);if(i)return i instanceof Fr&&i.resetConnection(o),i;let l=(()=>{if(r==="injected"){if(o==="metamask"&&n?.eip6963InjectedProvider)return new pl(this.chains,this.defaultChain,this.rpcConfig,n?.eip6963InjectedProvider,"metamask");if(o==="metamask"&&n?.legacyInjectedProvider)return new bi(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider,"metamask");if(o==="phantom"&&n?.legacyInjectedProvider)return new bi(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider,"phantom");if(n?.legacyInjectedProvider&&o==="unknown_browser_extension")return new bi(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider);if(n?.eip6963InjectedProvider)return new wi(this.chains,this.defaultChain,this.rpcConfig,n?.eip6963InjectedProvider,o)}else return r==="coinbase_wallet"?new dl(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):r==="phantom"?new ml(this.defaultChain):new Fr(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,o)})();return l&&this.addWalletConnector(l),l||null}addWalletConnector(r){this.walletConnectors.push(r),r.on("initialized",()=>this.onInitialized(r)),r.on("walletsUpdated",()=>this.onWalletsUpdated(r)),r.initialize().catch(o=>{console.debug("Failed to initialize connector",o)})}saveConnectionHistory(){let r=this.wallets.map(o=>({address:o.address,connectorType:o.connectorType,walletClientType:o.walletClientType,connectedAt:o.connectedAt}));j.put(Ad,r)}async activeWalletSign(r){let o=this.wallets,n=o.length>0?o[0]:null;return n?n.sign(r):null}setActiveWallet(r){this.activeWallet=ih(r),this.emit("walletsUpdated")}};function ll(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){let o=e[r],n=t[r];if(o?.address!==n?.address||o?.chainId!==n?.chainId||o?.connectorType!==n?.connectorType||o?.connectedAt!==n?.connectedAt||o?.walletClientType!==n?.walletClientType||o?.isConnected!==n?.isConnected||o?.linked!==n?.linked)return!1}return!0}var e0=e=>e&&typeof e.address=="string"&&typeof e.connectorType=="string"&&typeof e.walletClientType=="string"&&typeof e.connectedAt=="number",Nd=()=>{let e=j.get(Ad);return e&&Array.isArray(e)&&e.map(o=>e0(o)).every(Boolean)?e:[]};import{ofetch as t0}from"ofetch";var r0=[_s,As,Ps,Rs],yl=class{constructor({appId:t,appClientId:r,client:o,defaults:n}){this.appId=t,this.appClientId=r,this.clientAnalyticsId=o.clientAnalyticsId,this.sdkVersion=Ed,this.client=o,this.defaults=n,this.fallbackApiUrl=o.fallbackApiUrl,this.baseFetch=t0.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:i,options:a})=>{let l=new Headers(a.headers);l.set("privy-app-id",this.appId),this.appClientId&&l.set("privy-client-id",this.appClientId),l.set("privy-ca-id",this.clientAnalyticsId||""),l.set("privy-client",`react-auth:${this.sdkVersion}`);let s=r0.includes(i.toString());if(!l.has("authorization")){let c=await this.client.getAccessToken({disableAutoRefresh:s});c!==null&&l.set("authorization",`Bearer ${c}`)}a.headers=l,a.retryDelay&&(a.retryDelay=a.retryDelay*3)},onRequestError:({error:i})=>{if(i instanceof DOMException&&i.name==="AbortError")throw new Ts}})}async get(t,r){try{return await this.baseFetch(t,r)}catch(o){throw le(o)}}async post(t,r,o){try{return await this.baseFetch(t,{method:"POST",...r?{body:r}:{},...o})}catch(n){throw le(n)}}async delete(t,r){try{return await this.baseFetch(t,{method:"DELETE",...r})}catch(o){throw le(o)}}};var ah=e=>({challenge:e.challenge,allowCredentials:e.allow_credentials?.map(t=>({id:t.id,type:t.type,transports:t.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});import Ho from"js-cookie";function sh(e){return e instanceof Lo?"email":e instanceof Do?"sms":e instanceof So?"siwe":e instanceof di?"guest":e instanceof si?"custom_auth":e instanceof Xr?e.meta.provider:null}import*as lh from"jose";var Ar=class{static parse(t){try{return new Ar(t)}catch{return null}}constructor(t){this.value=t,this._decoded=lh.decodeJwt(t)}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(t=0){let r=Date.now(),o=(this.expiration-t)*1e3;return r>=o}};var o0=30,gl=class{constructor(){this.authenticateOnce=new Le(async t=>this._authenticate(t)),this.linkOnce=new Le(async t=>this._link(t)),this.refreshOnce=new Le(this._refresh.bind(this)),this.destroyOnce=new Le(this._destroy.bind(this)),this.forkSessionOnce=new Le(this._forkSession.bind(this))}get token(){try{let t=j.get(bn);return typeof t=="string"?new Ar(t).value:null}catch(t){return console.error(t),this.destroyLocalState(),null}}get refreshToken(){try{let t=j.get(Gs);return typeof t=="string"?t:null}catch(t){return console.error(t),this.destroyLocalState(),null}}get forkedToken(){try{let t=j.get(ma);return typeof t=="string"?t:null}catch(t){return console.error(t),this.destroyLocalState(),null}}getProviderAccessToken(t){try{let r=j.get(ha(t));if(typeof r=="string"){let o=new Ar(r);return o.isExpired()?(j.del(ha(t)),null):o.value}else return null}catch(r){return console.error(r),null}}get mightHaveServerCookies(){try{let t=Ho.get(Vs);return t!==void 0&&t.length>0}catch(t){console.error(t)}return!1}hasRefreshCredentials(){return this.mightHaveServerCookies||typeof this.token=="string"&&typeof this.refreshToken=="string"&&this.refreshToken!==Gm}hasRecoveryCredentials(){return typeof this.forkedToken=="string"}hasActiveToken(){let t=Ar.parse(this.token);return t!==null&&!t.isExpired(o0)}authenticate(t){return this.authenticateOnce.execute(t)}link(t){return this.linkOnce.execute(t)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(t,r){typeof r=="string"?j.put(ha(t),r):j.del(ha(t))}async _authenticate(t){try{let r=await t.authenticate(),{user:o,is_new_user:n,oauth_tokens:i}=r;this.handleTokenResponse(r);let a=i,l=a?{provider:a.provider,accessToken:a.access_token,accessTokenExpiresInSeconds:a.access_token_expires_in_seconds,refreshToken:a.refresh_token,refreshTokenExpiresInSeconds:i.refresh_token_expires_in_seconds,scopes:a.scopes}:void 0,s=sh(t);return s&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:s,isNewUser:n}}),s==="siwe"&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:t.meta.connectorType,walletClientType:t.meta.walletClientType}}),{user:$t(o),isNewUser:n,oAuthTokens:l}}catch(r){throw console.warn("Error authenticating session"),rt(r)}}async _link(t){try{let r=await t.link(),o=r.oauth_tokens,n=o?{provider:o.provider,accessToken:o.access_token,accessTokenExpiresInSeconds:o.access_token_expires_in_seconds,refreshToken:o.refresh_token,refreshTokenExpiresInSeconds:o.refresh_token_expires_in_seconds,scopes:o.scopes}:void 0;return{user:$t(r),oAuthTokens:n}}catch(r){throw console.warn("Error linking account"),rt(r)}}async _refresh(){if(!this.api)throw new w("Session has no API instance");if(!this.client)throw new w("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let t=this.token,r=this.refreshToken,o=this.forkedToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let n;if(t&&r||this.mightHaveServerCookies){let i={};t&&(i.authorization=`Bearer ${t}`);let a=r?{refresh_token:r}:{};n=await this.api.post(_s,a,{headers:i}),o&&this.clearForkedToken()}else if(o)n=await this.api.post(As,{refresh_token:o}),this.clearForkedToken();else return null;return this.handleTokenResponse(n),$t(n.user)}catch(n){if(n instanceof Wt&&n.privyErrorCode==="missing_or_invalid_token")return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw rt(n)}}handleTokenResponse(t){t.session_update_action?t.session_update_action==="set"?(this.storeRefreshToken(t.refresh_token),this.storeToken(t.token),t.identity_token&&this.storeIdentityToken(t.identity_token)):t.session_update_action==="clear"?this.destroyLocalState():t.session_update_action==="ignore"&&t.token&&(this.storeToken(t.token),t.identity_token&&this.storeIdentityToken(t.identity_token)):(this.storeRefreshToken(t.refresh_token),this.storeToken(t.token),t.identity_token&&this.storeIdentityToken(t.identity_token))}async _destroy(){try{await this.api?.post(Ps,{refresh_token:this.refreshToken})}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new w("Session has no API instance");let t=this.refreshToken;try{let r=await this.api.post(Ru,{refresh_token:t});return this.storeRefreshToken(r.refresh_token),this.storeToken(r.token),r.new_session_refresh_token}catch(r){throw rt(r)}}destroyLocalState(){this.storeRefreshToken(null),this.storeToken(null),this.clearIdentityToken(),this.clearForkedToken()}storeToken(t){if(typeof t=="string"){let r=j.get(bn);if(j.put(bn,t),!this.client?.useServerCookies){let o=Ar.parse(t)?.expiration;Ho.set(Td,t,{sameSite:"Strict",secure:!0,expires:o?new Date(o*1e3):void 0})}r!==t&&this.client?.onStoreToken?.(t)}else j.del(bn),Ho.remove(Td),this.client?.onDeleteToken?.()}storeRefreshToken(t){typeof t=="string"?(j.put(Gs,t),this.client?.useServerCookies||Ho.set(Vs,"t",{sameSite:"Strict",secure:!0,expires:30})):(j.del(Gs),Ho.remove(Dm),Ho.remove(Vs))}storeIdentityToken(t){if(this.client?.useServerCookies)return;j.put(Sd,t);let r=Ar.parse(t)?.expiration;Ho.set(_d,t,{sameSite:"Strict",secure:!0,expires:r?new Date(r*1e3):void 0})}clearIdentityToken(){j.del(Sd),Ho.remove(_d)}clearForkedToken(){j.del(ma)}};var Ud,vl,ch,_a=class{constructor(t){Es(this,vl);this.apiUrl=t.apiUrl||Bs,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=!!t.apiUrl&&t.apiUrl.startsWith("https://privy."),this.timeout=t.timeout||Nm,this.appId=t.appId,this.appClientId=t.appClientId,this.clientAnalyticsId=ku(this,vl,ch).call(this),Ud||(Ud=new gl),this.session=Ud,this.api=this.generateApi(),this.session.client=this}initializeConnectorManager({walletConnectCloudProjectId:t,rpcConfig:r,chains:o,defaultChain:n,store:i,walletList:a,shouldEnforceDefaultChainOnConnect:l,externalWalletConfig:s,appName:c}){this.connectors||(this.connectors=new Sa(this.appId,t,r,o,n,i,a,l,s,c))}sessionHasActiveToken(){return this.session.hasActiveToken()}generateApi(){let t=new yl({appId:this.appId,appClientId:this.appClientId,client:this,defaults:{baseURL:this.apiUrl,timeout:this.timeout}});return this.session.api=t,t}updateApiUrl(t){this.apiUrl=t||this.fallbackApiUrl,this.api=this.generateApi(),t&&(this.useServerCookies=!0)}authenticate(){if(!this.authFlow)throw new w("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new w("No auth flow in progress.");let{oAuthTokens:t}=await this.session.link(this.authFlow);return{user:await this.getAuthenticatedUser(),oAuthTokens:t}}storeProviderAccessToken(t,r){this.session.storeProviderAccessToken(t,r)}getProviderAccessToken(t){return this.session.getProviderAccessToken(t)}async logout(){await this.session.destroy(),this.authFlow=void 0}clearProviderAcccessTokens(t){t.linkedAccounts.filter(o=>o.type==="cross_app").forEach(o=>{this.storeProviderAccessToken(o.providerApp.id,null)})}startAuthFlow(t){return t.api=this.api,this.authFlow=t,this.authFlow}async initMfaSmsVerification(){try{await this.api.post(cm,{action:"verify"})}catch(t){throw le(t)}}async initMfaPasskeyVerification(){try{let t=await this.api.post(dm,{});return ah(t.options)}catch(t){throw le(t)}}async acceptTerms(){try{let t=await this.api.post(pm,{});return $t(t)}catch(t){throw rt(t)}}async unlinkEmail(t){try{let r=await this.api.post(Vu,{address:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkPhone(t){try{let r=await this.api.post(Ku,{phoneNumber:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkWallet(t){try{let r=await this.api.post(Ou,{address:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkOAuth(t,r){try{let o=await this.api.post(Qu,{provider:t,subject:r});return await this.getAuthenticatedUser()??$t(o)}catch(o){throw rt(o)}}async unlinkFarcaster(t){try{let r=await this.api.post(Fu,{fid:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkTelegram(t){try{let r=await this.api.post(lm,{telegram_user_id:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkPasskey(t){try{let r=await this.api.post(im,{credential_id:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async createAnalyticsEvent({eventName:t,payload:r,timestamp:o,options:n}){if(!(typeof window>"u"))try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(Rs,{event_name:t,client_id:this.clientAnalyticsId,payload:{...r||{},clientTimestamp:o?o.toISOString():new Date().toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch{}}async signMoonpayOnRampUrl(t){try{return this.api.post(fm,t)}catch(r){throw rt(r)}}async initCoinbaseOnRamp(t){try{return this.api.post(hm,t)}catch(r){throw rt(r)}}async getCoinbaseOnRampStatus({partnerUserId:t}){try{return this.api.get(`${ym}?partnerUserId=${t}`)}catch(r){throw rt(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()||this.session.hasRecoveryCredentials()?this.session.refresh():null}async getAccessToken(t){return this.session.hasActiveToken()?Ar.parse(this.session.token)?.audience!==this.appId?(await this.logout(),null):this.session.token:!t?.disableAutoRefresh&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getServerConfig(){try{let t={},r=this.session.token;r&&(t.authorization=`Bearer ${r}`);let o=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:t}),n=o.telegram_auth_config?{botId:o.telegram_auth_config.bot_id,botName:o.telegram_auth_config.bot_name,linkEnabled:o.telegram_auth_config.link_enabled,seamlessAuthEnabled:o.telegram_auth_config.seamless_auth_enabled}:void 0,i=o.funding_config?{methods:o.funding_config.methods,defaultRecommendedAmount:o.funding_config.default_recommended_amount,defaultRecommendedCurrency:o.funding_config.default_recommended_currency,promptFundingOnWalletCreation:o.funding_config.prompt_funding_on_wallet_creation}:void 0;return{id:o.id,name:o.name,verificationKey:o.verification_key,logoUrl:o.logo_url||void 0,accentColor:o.accent_color||void 0,showWalletLoginFirst:o.show_wallet_login_first,allowlistConfig:{errorTitle:o.allowlist_config.error_title,errorDetail:o.allowlist_config.error_detail,errorCtaText:o.allowlist_config.cta_text,errorCtaLink:o.allowlist_config.cta_link},walletAuth:o.wallet_auth,emailAuth:o.email_auth,smsAuth:o.sms_auth,googleOAuth:o.google_oauth,twitterOAuth:o.twitter_oauth,discordOAuth:o.discord_oauth,githubOAuth:o.github_oauth,spotifyOAuth:o.spotify_oauth,instagramOAuth:o.instagram_oauth,tiktokOAuth:o.tiktok_oauth,linkedinOAuth:o.linkedin_oauth,appleOAuth:o.apple_oauth,farcasterAuth:o.farcaster_auth,passkeyAuth:o.passkey_auth,telegramAuth:o.telegram_auth,termsAndConditionsUrl:o.terms_and_conditions_url,embeddedWalletConfig:{createOnLogin:o.embedded_wallet_config?.create_on_login,userOwnedRecoveryOptions:o.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:o.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:o.privacy_policy_url,requireUsersAcceptTerms:o.require_users_accept_terms,customApiUrl:o.custom_api_url,walletConnectCloudProjectId:o.wallet_connect_cloud_project_id,fiatOnRampEnabled:o.fiat_on_ramp_enabled,captchaEnabled:o.captcha_enabled,captchaSiteKey:o.captcha_site_key,twitterOAuthOnMobileEnabled:o.twitter_oauth_on_mobile_enabled,createdAt:new Date(o.created_at*1e3),updatedAt:new Date(o.updated_at*1e3),mfaMethods:o.mfa_methods,enforceWalletUis:o.enforce_wallet_uis,legacyWalletUiConfig:o.legacy_wallet_ui_config,telegramAuthConfiguration:n,fundingConfig:i}}catch(t){throw rt(t)}}async getUsdTokenPrice(t){try{return(await this.api.get(`/api/v1/token_price?chainId=${t.id}&tokenSymbol=${t.nativeCurrency.symbol}`)).usd}catch{console.error(`Unable to fetch token price for chain with id ${t.id}`);return}}async requestFarcasterSignerStatus(t){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:t})}catch(r){throw console.error("Unable to fetch Farcaster signer status"),r}}async forkSession(){return await this.session.forkSession()}async generateSiweNonce({address:t,captchaToken:r}){try{return(await this.api.post(Iu,{address:t,token:r})).nonce}catch(o){throw rt(o)}}async authenticateWithSiweInternal({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i}){return await this.api.post(Mu,{message:t,signature:r,chainId:o,walletClientType:n,connectorType:i})}async linkWithSiweInternal({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i}){return await this.api.post(Wu,{message:t,signature:r,chainId:o,walletClientType:n,connectorType:i})}async linkWithSiwe({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i}){try{let a=await this.linkWithSiweInternal({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i});return $t(a)}catch(a){throw rt(a)}}};vl=new WeakSet,ch=function(){if(typeof window>"u")return null;try{let r=j.get(fa);if(typeof r=="string"&&r.length>0)return r}catch{}let t=n0();try{return j.put(fa,t),t}catch{return t}};import{Turnstile as d0}from"@marsidev/react-turnstile";import{useEffect as p0,useMemo as u0}from"react";import{useMemo as i0,useRef as a0,useContext as s0,useState as Fd,createContext as l0}from"react";import{jsx as c0}from"react/jsx-runtime";var dh=l0({siteKey:"",enabled:!1,appId:void 0,token:void 0,error:void 0,status:"disabled",setToken:T,setError:T,setExecuting:T,waitForResult:()=>Promise.resolve(""),ref:{current:null},remove:T,reset:T,execute:T}),ar=class extends tt{constructor(r,o,n){super(r||"Captcha failed");this.type="Captcha";o instanceof Error&&(this.cause=o),this.privyErrorCode=n}},ph=({children:e,id:t,captchaSiteKey:r,captchaEnabled:o})=>{let n=a0(null),[i,a]=Fd(),[l,s]=Fd(),[c,m]=Fd(!1),f=i0(()=>o?!c&&!i&&!l?{status:"ready"}:c&&!i&&!l?{status:"loading"}:i&&!l?{status:"success",token:i}:l?{status:"error",error:l}:{status:"ready"}:{status:"disabled"},[o,i,l,c]);return c0(dh.Provider,{value:{...f,ref:n,enabled:o,siteKey:r,appId:t,setToken:a,setError:s,setExecuting:m,remove(){o&&(n.current?.remove(),m(!1),s(void 0),a(void 0))},reset(){o&&(n.current?.reset(),m(!1),s(void 0),a(void 0))},execute(){o&&(m(!0),n.current?.execute())},async waitForResult(){if(!o)return"";try{return await wm(()=>n.current?.getResponse(),{interval:200,timeout:2e4})}catch{throw new ar("Captcha failed",null,"captcha_timeout")}}},children:e})},Te=()=>s0(dh);import{jsx as uh}from"react/jsx-runtime";var Bd=e=>{let{enabled:t,siteKey:r,appId:o,setError:n,setToken:i,setExecuting:a,ref:l}=Te(),[,s]=u0(()=>r?.split("t:")||[],[r]);if(p0(()=>l.current?.remove,[]),!t)return null;if(!s)throw new Error("Unsupported captcha site key");return uh("div",{className:"hidden h-0 w-0",children:uh(d0,{...e,ref:l,siteKey:s,options:{action:o,size:"invisible",...e.delayedExecution?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{e.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{e.onError?.(),n("Captcha failed"),a(!1)},onSuccess:c=>{e.onSuccess?.(c),i(c),a(!1)},onExpire:()=>{e.onExpire?.();try{l.current?.reset(),n(void 0),i(void 0)}catch{n("expired_and_failed_reset")}}})})};import{useCallback as d_,useEffect as pC,useRef as p_,useState as u_}from"react";import fC from"styled-components";import{createContext as m0,useContext as f0}from"react";var Hd=m0({isNewUserThisSession:!1,linkingOrConnectingHint:null,walletConnectionStatus:null,connectors:[],rpcConfig:{rpcUrls:{}},showFiatPrices:!0,chains:[],clientAnalyticsId:null,pendingTransaction:null,appId:"notAdded",nativeTokenSymbolForChainId:T,initializeWalletProxy:T,getAuthMeta:T,getAuthFlow:T,closePrivyModal:T,openPrivyModal:T,connectWallet:T,initLoginWithWallet:T,loginWithWallet:T,initLoginWithFarcaster:T,loginWithFarcaster:T,loginWithCode:T,initLoginWithEmail:T,initLoginWithSms:T,initUpdateEmail:T,initUpdatePhone:T,resendEmailCode:T,resendSmsCode:T,initLoginWithHeadlessOAuth:T,loginWithHeadlessOAuth:T,crossAppAuthFlow:T,initLoginWithOAuth:T,recoveryOAuthFlow:T,loginWithOAuth:T,initLoginWithPasskey:T,loginWithPasskey:T,initLinkWithPasskey:T,linkWithPasskey:T,refreshUser:T,loginWithGuestAccountFlow:T,walletProxy:null,createAnalyticsEvent:T,acceptTerms:T,getUsdTokenPrice:T,recoverEmbeddedEthereumWallet:T,getMoonpaySignedUrl:T,initCoinbaseOnRamp:T,getCoinbaseOnRampStatus:T,updateWallets:T,fundWallet:T,setReadyToTrue:T,requestFarcasterSignerStatus:T,initLoginWithTelegram:T,loginWithTelegram:T,generateSiweMessage:T,linkWithSiwe:T,embeddedSolanaWallet:null,createEmbeddedSolanaWallet:T,recoverEmbeddedSolanaWallet:T,solanaSignMessage:T,connectCoinbaseSmartWallet:T}),I=()=>f0(Hd);import{createContext as h0,useContext as y0}from"react";var we=h0({ready:!1,authenticated:!1,user:null,walletConnectors:null,connectWallet:T,login:T,connectOrCreateWallet:T,linkEmail:T,linkPhone:T,linkFarcaster:T,linkWallet:T,linkCrossAppAccount:T,linkGoogle:T,linkTwitter:T,linkDiscord:T,linkGithub:T,linkSpotify:T,linkInstagram:T,linkTelegram:T,linkTiktok:T,linkLinkedIn:T,linkApple:T,linkPasskey:T,updateEmail:T,updatePhone:T,logout:T,getAccessToken:T,getEthereumProvider:T,getEthersProvider:T,getWeb3jsProvider:T,unlinkEmail:T,unlinkPhone:T,unlinkWallet:T,unlinkGoogle:T,unlinkTwitter:T,unlinkDiscord:T,unlinkGithub:T,unlinkSpotify:T,unlinkInstagram:T,unlinkTiktok:T,unlinkLinkedIn:T,unlinkApple:T,unlinkCrossAppAccount:T,unlinkFarcaster:T,unlinkTelegram:T,unlinkPasskey:T,setActiveWallet:T,forkSession:T,createWallet:T,importWallet:T,signMessage:T,signTypedData:T,enrollInMfa:T,initEnrollmentWithSms:T,initEnrollmentWithTotp:T,initEnrollmentWithPasskey:T,promptMfa:T,init:T,submitEnrollmentWithSms:T,submitEnrollmentWithTotp:T,submitEnrollmentWithPasskey:T,unenroll:T,submit:T,cancel:T,sendTransaction:T,exportWallet:T,setWalletPassword:T,setWalletRecovery:T,requestFarcasterSignerFromWarpcast:T,getFarcasterSignerPublicKey:T,signFarcasterMessage:T,createGuestAccount:T,initLoginWithEmail:T,initLoginWithSms:T,otpState:{status:"initial"},loginWithCode:T,fundWallet:T,initLoginWithHeadlessOAuth:T,loginWithHeadlessOAuth:T,generateSiweMessage:T,linkWithSiwe:T,signMessageWithCrossAppWallet:T,signTypedDataWithCrossAppWallet:T,sendTransactionWithCrossAppWallet:T,isHeadlessOAuthLoading:!1,isModalOpen:!1,mfaMethods:[]}),q=()=>y0(we);import{useEffect as g0,useState as v0}from"react";var mh=e=>{let[t,r]=v0("auto");return g0(()=>{let o=new ResizeObserver(n=>{r(n[0]?.contentRect.height??"auto")});return e.current&&o.observe(e.current),()=>{e.current&&o.unobserve(e.current)}},[e.current]),t};import{createContext as C0,useContext as w0,useEffect as b0}from"react";var fh={login:{onComplete:[],onError:[],onOAuthLoginComplete:[]},logout:{onSuccess:[]},connectWallet:{onSuccess:[],onError:[]},createWallet:{onSuccess:[],onError:[]},linkAccount:{onSuccess:[],onError:[]},configureMfa:{onMfaRequired:[]},setWalletPassword:{onSuccess:[],onError:[]},setWalletRecovery:{onSuccess:[],onError:[]},signMessage:{onSuccess:[],onError:[]},signTypedData:{onSuccess:[],onError:[]},sendTransaction:{onSuccess:[],onError:[]},accessToken:{onAccessTokenGranted:[],onAccessTokenRemoved:[]},oAuthAuthorization:{onOAuthTokenGrant:[]},fundWallet:{onUserExited:[]}},Gd=C0(void 0),hh=()=>w0(Gd);function Pe(e,t){if(!t)return;let o=hh().current[e];return b0(()=>{for(let[n,i]of Object.entries(t))o.hasOwnProperty(n)||console.warn(`Invalid event type "${n}" for action "${e}"`),o[n]?.push(i);return()=>{for(let[n,i]of Object.entries(t))o.hasOwnProperty(n)||console.warn(`Invalid event type "${n}" for action "${e}"`),o[n]=o[n]?.filter(a=>a!==i)}},[t])}function F(e,t,r,...o){for(let n of e.current[t][r])n(...o)}function Ti(){let e=hh();return(t,r,...o)=>F(e,t,r,...o)}function Vd(e){Pe("configureMfa",e)}import V0 from"@heroicons/react/24/outline/QuestionMarkCircleIcon";import Eh from"styled-components";import Mn,{css as yh}from"styled-components";import zd from"styled-components";import{Fragment as T0,jsx as qd,jsxs as S0}from"react/jsx-runtime";var it=({success:e,fail:t})=>S0(T0,{children:[qd(at,{className:e?"success":t?"fail":""}),qd(Pa,{className:e?"success":t?"fail":""})]}),at=zd.span`
12
+ - https://privy.io`};var So=class{constructor(t,r,o){this.getNonceOnce=new Le(this._getNonceOnce.bind(this)),this.wallet=t,this.captchaToken=o,this.client=r}get meta(){return{connectorType:this.wallet.connectorType,walletClientType:this.wallet.walletClientType}}async authenticate(){if(!this.client)throw new w("SiweFlow has no client instance");try{let{message:t,signature:r}=await this.sign(),o=await this.client.authenticateWithSiweInternal({message:t,signature:r,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType});return{user:o.user,token:o.token,refresh_token:o.refresh_token,identity_token:o.identity_token,is_new_user:o.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.client)throw new w("SiweFlow has no client instance");try{let{message:t,signature:r}=await this.sign();return await this.client.linkWithSiweInternal({message:t,signature:r,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType})}catch(t){throw le(t)}}async sign(){if(!this.client)throw new w("SiweFlow has no client instance");if(await this.buildSiweMessage(),!this.preparedMessage)throw new w("Could not prepare SIWE message");let t=await this.wallet.sign(this.preparedMessage);return{message:this.preparedMessage,signature:t}}async _getNonceOnce(){if(!this.client)throw new w("SiweFlow has no client instance");return await this.client.generateSiweNonce({address:this.wallet.address,captchaToken:this.captchaToken})}async buildSiweMessage(){if(!this.client)throw new w("SiweFlow has no client instance");let t=this.wallet.address,r=this.wallet.chainId.replace("eip155:","");return this.nonce||(this.nonce=await this.getNonceOnce.execute()),this.preparedMessage=il({address:t,chainId:r,nonce:this.nonce}),this.preparedMessage}};var Do=class{constructor(t,r){this.meta={phoneNumber:t,captchaToken:r}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new w("phone number and sms code must be set prior to calling authenticate.");try{let t=await this.api.post(Yu,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new w("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post($u,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(t){throw le(t)}}async sendSmsCode(t,r){if(!this.api)throw new w("Auth flow has no API instance");if(t&&(this.meta.phoneNumber=t),r&&(this.meta.captchaToken=r),!this.meta.phoneNumber)throw new w("phone nNumber must be set when initialzing authentication.");try{return await this.api.post(zu,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken})}catch(o){throw le(o)}}},al=class extends Do{constructor(r,o,n){super(o,n);this.meta={phoneNumber:o,captchaToken:n,oldPhoneNumber:r}}async link(){if(!this.api)throw new w("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new w("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(ju,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(r){throw le(r)}}};var mi=class{constructor(t){this.meta={captchaToken:t}}async authenticate(){if(!this.api)throw new w("Auth flow has no API instance");try{let t=await this.api.post(am,{captcha_token:this.meta.captchaToken,telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData});return{user:t.user,token:t.token,refresh_token:t.refresh_token,identity_token:t.identity_token,is_new_user:t.is_new_user}}catch(t){throw le(t)}}async link(){if(!this.api)throw new w("Auth flow has no API instance");try{return await this.api.post(sm,{telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData})}catch(t){throw le(t)}}};function Id(e){let t={detail:"",retryable:!1};return e?.privyErrorCode==="linked_to_another_user"&&(t.detail="This account has already been linked to another user."),e?.privyErrorCode==="disallowed_login_method"&&(t.detail="Login with Telegram not allowed."),e?.privyErrorCode==="invalid_data"&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode==="cannot_link_more_of_type"&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode==="invalid_credentials"&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode==="too_many_requests"&&(t.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode==="too_many_requests"&&e.message.includes("rate limit")&&(t.detail="Request limit reached for Telegram. Please wait a moment and try again."),t}function tf(){let e;if(e=l3(),e)return ef(),{...e,flowType:"login-url"};if(e=c3(),e)return ef(),{...e,flowType:"web-app"}}function l3(){let e=new URLSearchParams(window.location.search),t=Number(e.get("id")||""),r=e.get("hash"),o=Number(e.get("auth_date")||""),n=e.get("first_name"),i=e.get("last_name")||void 0,a=e.get("username")||void 0,l=e.get("photo_url")||void 0;if(!(!t||!n||!o||!r))return{id:t,first_name:n,last_name:i,username:a,photo_url:l,auth_date:o,hash:r}}function c3(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=new URLSearchParams(decodeURIComponent(e.replace("#tgWebAppData=",""))),r=t.get("query_id"),o=t.get("user"),n=Number(t.get("auth_date")||""),i=t.get("hash");if(!(!r||!o||!n||!i))return{query_id:r,user:o,auth_date:n,hash:i}}function ef(){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)}import{v4 as n0}from"uuid";function J(e){return e?new Date(e*1e3):null}function d3(e){let t=[];for(let r of e){let o=r.type;switch(r.type){case"wallet":let n={address:r.address,type:r.type,imported:r.imported,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at),chainType:r.chain_type,chainId:r.chain_id,walletClient:r.wallet_client_type==="privy"?"privy":"unknown",walletClientType:r.wallet_client_type,connectorType:r.connector_type,recoveryMethod:r.recovery_method};t.push(n);break;case"cross_app":let i={type:r.type,subject:r.subject,embeddedWallets:r.embedded_wallets,smartWallets:r.smart_wallets,providerApp:{id:r.provider_app_id},verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(i);break;case"email":let a={address:r.address,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(a);break;case"phone":let l={number:r.phoneNumber,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(l);break;case"google_oauth":let s={subject:r.subject,email:r.email,name:r.name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(s);break;case"spotify_oauth":let c={subject:r.subject,email:r.email,name:r.name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(c);break;case"instagram_oauth":let m={subject:r.subject,username:r.username,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(m);break;case"twitter_oauth":let f={subject:r.subject,username:r.username,name:r.name,type:r.type,profilePictureUrl:r.profile_picture_url,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(f);break;case"discord_oauth":let u={subject:r.subject,username:r.username,email:r.email,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(u);break;case"github_oauth":let C={subject:r.subject,username:r.username,name:r.name,email:r.email,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(C);break;case"tiktok_oauth":let v={subject:r.subject,username:r.username,name:r.name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(v);break;case"linkedin_oauth":let g={subject:r.subject,name:r.name,email:r.email,vanityName:r.vanity_name,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(g);break;case"apple_oauth":let b={subject:r.subject,email:r.email,type:r.type,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(b);break;case"custom_auth":t.push({type:r.type,customUserId:r.custom_user_id,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)});break;case"farcaster":let E={type:r.type,fid:r.fid,ownerAddress:r.owner_address,displayName:r.display_name,username:r.username,bio:r.bio,pfp:r.profile_picture_url,url:r.homepage_url,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at),signerPublicKey:r.signer_public_key};t.push(E);break;case"passkey":let k={type:r.type,enrolledInMfa:r.enrolled_in_mfa,credentialId:r.credential_id,authenticatorName:r.authenticator_name,createdWithDevice:r.created_with_device,createdWithOs:r.created_with_os,createdWithBrowser:r.created_with_browser,verifiedAt:J(r.verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(k);break;case"telegram":let _={type:r.type,telegramUserId:r.telegram_user_id,firstName:r.first_name,lastName:r.last_name,username:r.username,photoUrl:r.photo_url,verifiedAt:J(r.first_verified_at),firstVerifiedAt:J(r.first_verified_at),latestVerifiedAt:J(r.latest_verified_at)};t.push(_);break;default:console.warn(`Unrecognized account type: ${o}. Please consider upgrading the Privy SDK.`)}}return t}function zt(e,t){return e.slice().sort((r,o)=>(o.firstVerifiedAt??o.verifiedAt).getTime()-(r.firstVerifiedAt??r.verifiedAt).getTime()).find(r=>r.type===t)}var ye=e=>e?.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClientType==="privy"&&!t.imported&&t.chainType==="ethereum")||null,kn=e=>e?.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClientType==="privy"&&!t.imported&&t.chainType==="solana")||null,sl=e=>e?.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClientType==="privy"&&t.imported&&t.chainType==="ethereum")||null,p3=e=>e.linkedAccounts.filter(t=>t.type==="wallet"),Lt=(e,t)=>ye(e)||kn(e)?!1:t==="all-users"||t==="users-without-wallets"&&!p3(e)?.length;function $t(e){if(!e)return null;let t=d3(e.linked_accounts),r=zt(t,"wallet"),o=zt(t,"email"),n=zt(t,"phone"),i=zt(t,"google_oauth"),a=zt(t,"twitter_oauth"),l=zt(t,"discord_oauth"),s=zt(t,"github_oauth"),c=zt(t,"spotify_oauth"),m=zt(t,"instagram_oauth"),f=zt(t,"tiktok_oauth"),u=zt(t,"linkedin_oauth"),C=zt(t,"apple_oauth"),v=zt(t,"farcaster"),g=zt(t,"telegram"),b=e.mfa_methods.map(({type:k,verified_at:_})=>({type:k,verifiedAt:J(_)}));return{id:e.id,createdAt:J(e.created_at),linkedAccounts:t,email:o&&{address:o?.address},phone:n&&{number:n?.number},wallet:r&&{address:r.address,chainType:r.chainType,chainId:r.chainId,walletClient:r.walletClient,walletClientType:r.walletClientType,connectorType:r.connectorType,recoveryMethod:r.recoveryMethod,imported:r.imported},google:i&&{subject:i.subject,email:i.email,name:i.name},twitter:a&&{subject:a.subject,username:a.username,name:a.name,profilePictureUrl:a.profilePictureUrl},discord:l&&{subject:l.subject,username:l.username,email:l.email},github:s&&{subject:s.subject,username:s.username,name:s.name,email:s.email},spotify:c&&{subject:c.subject,email:c.email,name:c.name},instagram:m&&{subject:m.subject,username:m.username},tiktok:f&&{subject:f.subject,username:f.username,name:f.name},linkedin:u&&{subject:u.subject,name:u.name,email:u.email,vanityName:u.vanityName},apple:C&&{subject:C.subject,email:C.email},farcaster:v&&{fid:v.fid,ownerAddress:v.ownerAddress,displayName:v.displayName,username:v.username,bio:v.bio,pfp:v.pfp,url:v.url,signerPublicKey:v.signerPublicKey},telegram:g&&{telegramUserId:g.telegramUserId,firstName:g.firstName,lastName:g.lastName,username:g.username,photoUrl:g.photoUrl},mfaMethods:b.map(k=>k.type),hasAcceptedTerms:e.has_accepted_terms??!1,isGuest:e.is_guest}}import{getAddress as ih}from"@ethersproject/address";import{isHexString as J3}from"@ethersproject/bytes";import X3 from"eventemitter3";import C3 from"@coinbase/wallet-sdk";import{jsx as rf,jsxs as u3}from"react/jsx-runtime";var _o=({style:e,...t})=>u3("svg",{width:"1024",height:"1024",viewBox:"0 0 1024 1024",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...e},...t,children:[rf("rect",{width:"1024",height:"1024",fill:"#0052FF",rx:100,ry:100}),rf("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"})]});import{getAddress as ro}from"@ethersproject/address";import{Web3Provider as cf}from"@ethersproject/providers";import{default as g3}from"eventemitter3";import y3 from"eventemitter3";var m3=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation"],of=e=>m3.includes(e);import{ErrorCode as f3}from"@ethersproject/logger";import{ProviderErrors as Rn}from"@privy-io/js-sdk-core";var fi=class extends pe{constructor(){super("Wallet timeout");this.type="wallet_error"}},hi=class extends pe{constructor(){super("User rejected connection");this.type="wallet_error"}},Dr=e=>{if(e instanceof pe)return e;if(e?.code&&e?.reason){let t=new wt(e);return e.code===f3.ACTION_REJECTED&&(t.details=Rn.E4001_USER_REJECTED_REQUEST),t}return e?.code?new wt(e):new pe("Unknown connector error",e)},Pr=class extends tt{constructor(r,o,n){super(r);this.type="provider_error";this.code=o,this.data=n}},wt=class extends Pr{constructor(r){let o=r;super(o.message,o.code,o.data);let n=Object.values(Rn).find(i=>i.eipCode===o.code);this.details=n||Rn.UNKNOWN_ERROR,o.code===-32002&&(o.message?.includes("already pending for origin")?o.message?.includes("wallet_requestPermissions")?this.details=Rn.E32002_CONNECTION_ALREADY_PENDING:this.details=Rn.E32002_REQUEST_ALREADY_PENDING:o.message?.includes("Already processing")&&o.message.includes("eth_requestAccounts")&&(this.details=Rn.E32002_WALLET_LOCKED))}},h3={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0},ERROR_USER_REJECTED_CONNECTION:{message:"You rejected the request",detail:"Please try connecting again.",retryable:!0},ERROR_USER_LIMIT_REACHED:{message:"Unable to link",detail:"You've reached the maximum number of linked wallets.",retryable:!1}},eo={...h3,...Rn};var Ke=class{constructor(t,r){this.removeListener=(t,r)=>{if(this.walletProvider)try{return this.walletProvider.removeListener(t,r)}catch{console.warn("Unable to remove wallet provider listener")}};this.walletTimeout=(t=new fi,r=this.rpcTimeoutDuration)=>new Promise((o,n)=>setTimeout(()=>{n(t)},r));this.setWalletProvider=t=>{this.walletProvider&&this._subscriptions.forEach(r=>{this.removeListener(r.eventName,r.listener)}),this.walletProvider=t,this._subscriptions.forEach(r=>{this.walletProvider?.on(r.eventName,r.listener)})};this.walletProvider=t,this.rpcTimeoutDuration=r||_n,this._subscriptions=[]}on(t,r){if(this.walletProvider)return this.walletProvider.on(t,r);this._subscriptions.push({eventName:t,listener:r})}async request(t){if(!this.walletProvider)throw new pe(`A wallet request of type ${t.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(t),this.walletTimeout()]).catch(r=>{throw Dr(r)})}},Uo=class extends Error{constructor(r,o,n){super(r);this.code=o,this.data=n}},wa=class extends y3{constructor(r,o,n,i,a,l=1){super();this.walletProxy=r,this.address=o,this.chainId=l,this.rpcConfig=n,this.chains=i,this.provider=qt(l,this.chains,n,{appId:a}),this.rpcTimeoutDuration=yi(n,"privy"),this.appId=a}async handleSendTransaction(r){if(!r.params||!Array.isArray(r.params))throw new Uo(`Invalid params for ${r.method}`,4200);let o=r.params[0];if(!await Ee()||!this.address)throw new Uo("Disconnected",4900);return(await sf(o)).hash}handleSwitchEthereumChain(r){if(!r.params||!Array.isArray(r.params))throw new Uo(`Invalid params for ${r.method}`,4200);let o;if(typeof r.params[0]=="string")o=r.params[0];else if("chainId"in r.params[0]&&typeof r.params[0].chainId=="string")o=r.params[0].chainId;else throw new Uo(`Invalid params for ${r.method}`,4200);this.chainId=Number(o),this.provider=qt(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",o)}async handlePersonalSign(r){if(!r.params||!Array.isArray(r.params))throw new Error("Invalid params for personal_sign");let o=r.params[0],n=r.params[1];return await nf(o,void 0,n)}async handleSignedTypedData(r){if(!r.params||!Array.isArray(r.params))throw new Error("Invalid params for eth_signTypedData_v4");let o=typeof r.params[1]=="string"?JSON.parse(r.params[1]):r.params[1];return await af(pa(o))}async handleEstimateGas(r){if(!r.params||!Array.isArray(r.params))throw new Error("Invalid params for eth_estimateGas");delete r.params[0].gasPrice,delete r.params[0].maxFeePerGas,delete r.params[0].maxPriorityFeePerGas;let o={...r.params[0],chainId:wn(this.chainId)};try{return await this.provider.send("eth_estimateGas",[o])}catch(n){console.warn(`Gas estimation failed with error: ${n}. Retrying gas estimation by omitting the 'from' address`);try{return delete o.from,await this.provider.send("eth_estimateGas",[o])}catch(i){throw console.warn(`Gas estimation failed with error: ${i} when omitting the 'from' address`),n}}}async request(r){switch(console.debug("Embedded1193Provider.request() called with args",r),r.method){case"eth_accounts":case"eth_requestAccounts":return this.address?[this.address]:[];case"eth_chainId":return wn(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(r);case"eth_sendTransaction":return this.handleSendTransaction(r);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(r);case"personal_sign":return this.handlePersonalSign(r);case"eth_signTypedData_v4":return this.handleSignedTypedData(r);default:break}if(of(r.method)){let o=await Ee();if(await lf(),!o||!this.address)throw new Uo("Disconnected",4900);try{return(await this.walletProxy.rpc({address:this.address,accessToken:o,request:{method:r.method,params:r.params}})).response.data}catch(n){throw console.error(n),new Uo("Disconnected",4900)}}else return this.provider.send(r.method,r.params)}async connect(){let r=await Ee();if(!r||!this.address)return null;try{return(await this.walletProxy.connect({address:this.address,accessToken:r})).address}catch(o){return console.error(o),null}}},to=class extends Ke{constructor(r){super(r,r.rpcTimeoutDuration)}},Fo=class extends Ke{constructor(t){super(t,t.rpcTimeoutDuration)}sendAsync(t,r){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};var v3=(e,t)=>{switch(t){case"coinbase_wallet":return e.message.includes("addEthereumChain");default:return e.code===4902||e.message?.includes("4902")}},Kt=class extends g3{constructor(r,o,n,i){super();this.onAccountsChanged=r=>{r.length===0?this.onDisconnect():this.syncAccounts(r)};this.onChainChanged=r=>{this.wallets.forEach(o=>{o.chainId=li(r),this.walletClientType==="privy"&&j.put(zs(o.address),r)}),this.emit("walletsUpdated")};this.onDisconnect=()=>{this.connected=!1,this.wallets=[],this.emit("walletsUpdated")};this.onConnect=()=>{this.connected=!0,this.syncAccounts()};this.wallets=[],this.walletClientType=r,this.chains=o,this.defaultChain=n,this.rpcConfig=i,this.rpcTimeoutDuration=yi(i,r),this.connected=!1,this.initialized=!1}buildConnectedWallet(r,o,n,i){let a=async()=>!!this.wallets.find(l=>ro(l.address)===ro(r));return{address:ro(r),chainId:o,meta:n,imported:i,switchChain:async l=>{if(!a)throw new pe("Wallet is not currently connected.");let s=this.wallets.find(C=>ro(C.address)===ro(r))?.chainId;if(!s)throw new pe("Unable to determine current chainId.");let c,m;if(typeof l=="number"?(c=`0x${l.toString(16)}`,m=l):(c=l,m=Number(l)),s===li(c))return;let f=this.chains.find(C=>C.id===m);if(!f)throw new pe(`Unsupported chainId: ${l}`);let u=async()=>{await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[{chainId:c}]})};try{return await u()}catch(C){if(v3(C,this.walletClientType))return await this.proxyProvider.request({method:"wallet_addEthereumChain",params:[{chainId:c,chainName:f.name,nativeCurrency:f.nativeCurrency,rpcUrls:[f.rpcUrls.default?.http[0]??""],blockExplorerUrls:[f.blockExplorers?.default.url??""]}]}),u();throw this.walletClientType==="rainbow"&&C.message?.includes("wallet_switchEthereumChain")?new pe(`Rainbow does not support the chainId ${o}`):C}},connectedAt:Date.now(),walletClientType:this.walletClientType,connectorType:this.connectorType,isConnected:a,getEthereumProvider:async()=>{if(!await a())throw new pe("Wallet is not currently connected.");return this.proxyProvider},getEthersProvider:async()=>{if(!await a())throw new pe("Wallet is not currently connected.");return new cf(new to(this.proxyProvider))},getWeb3jsProvider:async()=>{if(!await a())throw new pe("Wallet is not currently connected.");return new Fo(this.proxyProvider)},sign:async l=>{if(!await a())throw new pe("Wallet is not currently connected.");return await this.sign(l)},disconnect:()=>{this.disconnect()}}}async syncAccounts(r){let o=r;try{if(o===void 0){let c=await da(()=>this.proxyProvider.request({method:"eth_accounts"}),{maxAttempts:10,delayMs:500});console.debug(`eth_accounts for ${this.walletClientType}:`,c),Array.isArray(c)&&(o=c)}}catch(c){console.warn("Wallet did not respond to eth_accounts. Defaulting to prefetched accounts.",c)}if(!o||!Array.isArray(o)||o.length<=0||!o[0])return;let n=o[0],i=ro(n),a=[],l;if(this.walletClientType==="privy"){let c=j.get(zs(i));this.chains.find(m=>m.id===Number(c))||(j.del(zs(i)),c=null),l=c||`0x${this.defaultChain.id.toString(16)}`;try{await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[{chainId:l}]})}catch{console.warn(`Unable to switch embedded wallet to chain ID ${l} on initialization`)}}else try{let c=await da(()=>this.proxyProvider.request({method:"eth_chainId"}),{maxAttempts:10,delayMs:500});if(console.debug(`eth_chainId for ${this.walletClientType}:`,c),typeof c=="string")l=c;else if(typeof c=="number")l=`0x${c.toString(16)}`;else throw new Error("Invalid chainId returned from provider")}catch(c){console.warn(`Failed to get chainId from provider, defaulting to ${xd}`,c),l=xd}let s=li(l);if(!a.find(c=>ro(c.address)===i)){let c={name:this.walletBranding.name,icon:typeof this.walletBranding.icon=="string"?this.walletBranding.icon:void 0,id:this.walletBranding.id};a.push(this.buildConnectedWallet(ro(n),s,c,this.connectorType==="embedded_imported"))}ll(a,this.wallets)||(this.wallets=a,this.emit("walletsUpdated"))}async getConnectedWallet(){let r=await this.proxyProvider.request({method:"eth_accounts"});return this.wallets.sort((o,n)=>n.connectedAt-o.connectedAt).find(o=>r.find(n=>ro(n)===ro(o.address)))||null}async isConnected(){let r=await this.proxyProvider.request({method:"eth_accounts"});return Array.isArray(r)&&r.length>0}async sign(r){return await this.connect({showPrompt:!1}),new cf(new to(this.proxyProvider)).getSigner().signMessage(r)}subscribeListeners(){this.proxyProvider.on("accountsChanged",this.onAccountsChanged),this.proxyProvider.on("chainChanged",this.onChainChanged),this.proxyProvider.on("disconnect",this.onDisconnect),this.proxyProvider.on("connect",this.onConnect)}unsubscribeListeners(){this.proxyProvider.removeListener("accountsChanged",this.onAccountsChanged),this.proxyProvider.removeListener("chainChanged",this.onChainChanged),this.proxyProvider.removeListener("disconnect",this.onDisconnect),this.proxyProvider.removeListener("connect",this.onConnect)}};var w3=[1,11155111,137,10,8453,84532,42161,7777777,43114,56],df=(e,t)=>e.makeWeb3Provider({options:t}),cl,dl=class extends Kt{constructor(r,o,n,i,a,l){super("coinbase_wallet",r,o,n);this.connectorType="coinbase_wallet";this.displayName="Coinbase Wallet";if(this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.connectionOptions=i.coinbaseWallet.connectionOptions??"all",this.walletClientType=this.connectionOptions==="smartWalletOnly"?"coinbase_smart_wallet":"coinbase_wallet",this.walletClientType==="coinbase_smart_wallet"&&(this.displayName="Coinbase Smart Wallet"),!cl){let s=[o.id].concat(r.map(m=>m.id)),c=this.connectionOptions!=="eoaOnly"?s.filter(m=>!w3.includes(m)):[];c.length>0&&console.warn(`The following configured chains are not supported by the Coinbase Smart Wallet: ${c.join(", ")}`),cl=new C3({appName:a,appLogoUrl:l,appChainIds:s})}this.proxyProvider.setWalletProvider(df(cl,this.connectionOptions))}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return r.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:_o,id:"com.coinbase.wallet"}}async promptConnection(){try{let r=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!r||r.length===0||!r[0])throw new pe("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([r[0]])}catch(r){throw Dr(r)}}updateConnectionPreference(r){this.connectionOptions=r,this.walletClientType=r==="smartWalletOnly"?"coinbase_smart_wallet":"coinbase_wallet",this.proxyProvider.setWalletProvider(df(cl,this.connectionOptions))}};import{jsx as pf}from"react/jsx-runtime";var Bo=({...e})=>pf("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:pf("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:e.color||"var(--privy-color-foreground-3)"})});var ba=class extends Kt{constructor(r,o,n,i,a=!1){super("privy",o,n,i);this.connectorType="embedded";this.proxyProvider=r,a&&(this.connectorType="embedded_imported"),this.subscribeListeners()}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[wn(r?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:Bo,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}};import{jsx as uf}from"react/jsx-runtime";var gi=({style:e,...t})=>uf("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",style:{...e},...t,children:uf("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25"})});import{jsx as ir,jsxs as b3}from"react/jsx-runtime";var vi=({style:e,...t})=>b3("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",...e},...t,children:[ir("style",{children:".s1{stroke-linecap:round;stroke-linejoin:round}.s2{fill:#e4761b;stroke:#e4761b}.s3{fill:#f6851b;stroke:#f6851b}"}),ir("path",{fill:"#e2761b",stroke:"#e2761b",className:"s1",d:"m274.1 35.5-99.5 73.9L193 65.8z"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"}),ir("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"})]});import{jsx as mf,jsxs as E3}from"react/jsx-runtime";var oo=({style:e,...t})=>E3("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...e},...t,children:[mf("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),mf("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"})]});var wi=class extends Kt{constructor(r,o,n,i,a){super(a||"unknown",r,o,n);this.connectorType="injected";this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=i;let l=i.provider;this.proxyProvider.setWalletProvider(l)}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return r.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 r=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!r||r.length===0||!r[0])throw new pe("Unable to retrieve accounts");await this.syncAccounts([r[0]])}catch(r){throw Dr(r)}}},Ci,bi=class extends Kt{constructor(r,o,n,i,a){super(a??"unknown",r,o,n);this.connectorType="injected";Es(this,Ci,void 0);this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(i),a==="metamask"?yd(this,Ci,{name:"MetaMask",icon:vi,id:"io.metamask"}):a==="phantom"&&yd(this,Ci,{name:"Phantom",icon:oo,id:"phantom"})}async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(r){return r.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return xu(this,Ci)??{name:"Browser Extension",icon:gi,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let r=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!r||r.length===0||!r[0])throw new pe("Unable to retrieve accounts");await this.syncAccounts([r[0]])}catch(r){throw Dr(r)}}};Ci=new WeakMap;import{getAddress as Mk}from"@ethersproject/address";import{Web3Provider as Ok}from"@ethersproject/providers";import{isMobile as T3}from"react-device-detect";var pl=class extends wi{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{T3||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let t=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!t||t.length===0||!t[0])throw new pe("Unable to retrieve accounts");await this.syncAccounts([t[0]])}catch(t){throw Dr(t)}}};var ul=class extends Kt{constructor(r,o){super(r,[],o,{});this.connectorType="null";this.proxyProvider=new Ke(void 0,_n);this.connectorType=r}get walletBranding(){return{name:"Wallet",id:""}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw new Error("connect called for an uninstalled wallet via the NullConnector")}disconnect(){throw new Error("disconnect called for an uninstalled wallet via the NullConnector")}promptConnection(r){throw new Error(`promptConnection called for an uninstalled wallet via the NullConnector for ${r}`)}};var ml=class extends ul{constructor(t){super("phantom",t)}get walletBranding(){return{name:"Phantom",icon:oo,id:"phantom"}}};import{EthereumProvider as Y3,OPTIONAL_EVENTS as j3,OPTIONAL_METHODS as Z3}from"@walletconnect/ethereum-provider";import{isMobile as Q3}from"react-device-detect";import{createContext as B3,useContext as H3,useEffect as Ld,useRef as G3,useState as V3}from"react";import{jsx as S3}from"react/jsx-runtime";function ff({src:e,...t}){return S3("img",{src:e,...t,style:{display:"none"}})}import{useContext as eh,useEffect as Xf,useMemo as N3,useState as D3}from"react";import{createContext as U3}from"react";var Nt={appearance:{landingHeader:"Log in or sign up",theme:"light",accentColor:"#676FFF",walletList:["detected_wallets","metamask","coinbase_wallet","rainbow","wallet_connect"]},walletConnectCloudProjectId:Lm,rpcConfig:{rpcUrls:{},rpcTimeouts:{}},externalWallets:{coinbaseWallet:{connectionOptions:"all"}},captchaEnabled:!1,_render:{standalone:!1},fundingMethodConfig:{moonpay:{useSandbox:!1}}};var hf=({input:e})=>{if(!e||!e.primary[0])return;let t=[e.primary[0]],r=[];e.primary.length>4&&console.warn("You should not specify greater than 4 login methods in `loginMethodsAndOrder.primary`");for(let o of e.primary.slice(1))t.includes(o)?console.warn(`Duplicated login method: ${o}`):t.push(o);for(let o of e.overflow??[])!t.includes(o)&&!r.includes(o)?r.push(o):console.warn(`Duplicated login method: ${o}`);return{primary:t,overflow:r}};var _3=new Set(["coinbase_wallet","cryptocom","metamask","okx_wallet","phantom","rainbow","uniswap","zerion","wallet_connect","detected_wallets","rabby_wallet","safe"]),yf=e=>_3.has(e),gf=(e,t,r)=>r.indexOf(e)===t,vf=({input:e,overrides:t})=>t?t.primary.concat(t.overflow??[]).filter(yf).filter(gf):e?e.filter(yf).filter(gf):Nt.appearance.walletList;var Cf={id:42161,name:"Arbitrum One",network:"arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-mainnet.rpc.privy.systems"]},alchemy:{http:["https://arb-mainnet.g.alchemy.com/v2"],webSocket:["wss://arb-mainnet.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-mainnet.infura.io/v3"],webSocket:["wss://arbitrum-mainnet.infura.io/ws/v3"]},default:{http:["https://arb1.arbitrum.io/rpc"]},public:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://arbiscan.io"},default:{name:"Arbiscan",url:"https://arbiscan.io"}}};var wf={id:421613,name:"Arbitrum Goerli",network:"arbitrum-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"AGOR",decimals:18},rpcUrls:{default:{http:["https://goerli-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"}},testnet:!0};var bf={id:421614,name:"Arbitrum Sepolia",network:"arbitrum-sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]},public:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Blockscout",url:"https://sepolia-explorer.arbitrum.io"}},testnet:!0};var Ef={id:43114,name:"Avalanche",network:"avalanche",nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]},public:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://snowtrace.io"},default:{name:"SnowTrace",url:"https://snowtrace.io"}}};var Tf={id:43113,name:"Avalanche Fuji",network:"avalanche-fuji",nativeCurrency:{decimals:18,name:"Avalanche Fuji",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax-test.network/ext/bc/C/rpc"]},public:{http:["https://api.avax-test.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://testnet.snowtrace.io"},default:{name:"SnowTrace",url:"https://testnet.snowtrace.io"}},testnet:!0};var Sf={id:8453,network:"base",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-mainnet.rpc.privy.systems"]},blast:{http:["https://base-mainnet.blastapi.io"],webSocket:["wss://base-mainnet.blastapi.io"]},default:{http:["https://mainnet.base.org"]},public:{http:["https://mainnet.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://basescan.org"},default:{name:"Basescan",url:"https://basescan.org"}},testnet:!0};var _f={id:84531,network:"base-goerli",name:"Base Goerli Testnet",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://goerli.basescan.org"}},testnet:!0};var Pf={id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.base.org"]},public:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Blockscout",url:"https://base-sepolia.blockscout.com"}},testnet:!0};var Af={id:80085,network:"berachain-artio",name:"Berachain Artio",nativeCurrency:{name:"BERA",symbol:"BERA",decimals:18},rpcUrls:{default:{http:["https://berachain-artio.rpc.privy.systems"]},public:{http:["https://berachain-artio.rpc.privy.systems"]}},blockExplorers:{default:{name:"Beratrail",url:"https://artio.beratrail.io"}},testnet:!0};var xf={id:42220,name:"Celo Mainnet",network:"celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]},infura:{http:["https://celo-mainnet.infura.io/v3"]},public:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/mainnet"},etherscan:{name:"CeloScan",url:"https://celoscan.io"}},testnet:!1};var kf={id:44787,name:"Celo Alfajores Testnet",network:"celo-alfajores",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://alfajores-forno.celo-testnet.org"]},infura:{http:["https://celo-alfajores.infura.io/v3"]},public:{http:["https://alfajores-forno.celo-testnet.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/alfajores"},etherscan:{name:"CeloScan",url:"https://alfajores.celoscan.io/"}},testnet:!0};var Rf={id:314,name:"Filecoin - Mainnet",network:"filecoin-mainnet",nativeCurrency:{decimals:18,name:"filecoin",symbol:"FIL"},rpcUrls:{default:{http:["https://api.node.glif.io/rpc/v1"]},public:{http:["https://api.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filfox",url:"https://filfox.info/en"},filscan:{name:"Filscan",url:"https://filscan.io"},filscout:{name:"Filscout",url:"https://filscout.io/en"},glif:{name:"Glif",url:"https://explorer.glif.io"}}};var If={id:314159,name:"Filecoin - Calibration testnet",network:"filecoin-calibration",nativeCurrency:{decimals:18,name:"testnet filecoin",symbol:"tFIL"},rpcUrls:{default:{http:["https://api.calibration.node.glif.io/rpc/v1"]},public:{http:["https://api.calibration.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filscan",url:"https://calibration.filscan.io"}}};var Mf={id:17069,name:"Garnet Holesky",network:"garnet-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.garnetchain.com"]},public:{http:["https://rpc.garnetchain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.garnetchain.com"}}};var Wf={id:5,network:"goerli",name:"Goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.ankr.com/eth_goerli"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.etherscan.io"}},testnet:!0};var Of={id:17e3,name:"Holesky",network:"holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-holesky.publicnode.com"]},public:{http:["https://ethereum-holesky.publicnode.com"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://holesky.etherscan.io"},default:{name:"EtherScan",url:"https://holesky.etherscan.io"}}};var Lf={id:59144,network:"linea-mainnet",name:"Linea Mainnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]},public:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://lineascan.build"},etherscan:{name:"Etherscan",url:"https://lineascan.build"}},testnet:!1};var Nf={id:59140,network:"linea-testnet",name:"Linea Goerli Testnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-goerli.infura.io/v3"],webSocket:["wss://linea-goerli.infura.io/ws/v3"]},default:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]},public:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.lineascan.build"},etherscan:{name:"Etherscan",url:"https://goerli.lineascan.build"}},testnet:!0};var Df={id:42,network:"lukso",name:"LUKSO",nativeCurrency:{name:"LUKSO",symbol:"LYX",decimals:18},rpcUrls:{default:{http:["https://rpc.mainnet.lukso.network"],webSocket:["wss://ws-rpc.mainnet.lukso.network"]}},blockExplorers:{default:{name:"LUKSO Mainnet Explorer",url:"https://explorer.execution.mainnet.lukso.network"}}};var fl={id:1,network:"homestead",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://mainnet.rpc.privy.systems"]},alchemy:{http:["https://eth-mainnet.g.alchemy.com/v2"],webSocket:["wss://eth-mainnet.g.alchemy.com/v2"]},infura:{http:["https://mainnet.infura.io/v3"],webSocket:["wss://mainnet.infura.io/ws/v3"]},default:{http:["https://cloudflare-eth.com"]},public:{http:["https://cloudflare-eth.com"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://etherscan.io"},default:{name:"Etherscan",url:"https://etherscan.io"}}};var Uf={id:10,name:"OP Mainnet",network:"optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-mainnet.rpc.privy.systems"]},alchemy:{http:["https://opt-mainnet.g.alchemy.com/v2"],webSocket:["wss://opt-mainnet.g.alchemy.com/v2"]},infura:{http:["https://optimism-mainnet.infura.io/v3"],webSocket:["wss://optimism-mainnet.infura.io/ws/v3"]},default:{http:["https://mainnet.optimism.io"]},public:{http:["https://mainnet.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://optimistic.etherscan.io"},default:{name:"Optimism Explorer",url:"https://explorer.optimism.io"}}};var Ff={id:420,name:"Optimism Goerli Testnet",network:"optimism-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.optimism.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"}},testnet:!0};var Bf={id:11155420,name:"Optimism Sepolia",network:"optimism-sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.optimism.io"]},public:{http:["https://sepolia.optimism.io"]},infura:{http:["https://optimism-sepolia.infura.io/v3"]}},blockExplorers:{default:{name:"Blockscout",url:"https://optimism-sepolia.blockscout.com"}},testnet:!0};var Hf={id:137,name:"Polygon Mainnet",network:"matic",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{privy:{http:["https://polygon-mainnet.rpc.privy.systems"]},alchemy:{http:["https://polygon-mainnet.g.alchemy.com/v2"],webSocket:["wss://polygon-mainnet.g.alchemy.com/v2"]},infura:{http:["https://polygon-mainnet.infura.io/v3"],webSocket:["wss://polygon-mainnet.infura.io/ws/v3"]},default:{http:["https://polygon-rpc.com"]},public:{http:["https://polygon-rpc.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://polygonscan.com"},default:{name:"PolygonScan",url:"https://polygonscan.com"}}};var Gf={id:80001,name:"Mumbai",network:"maticmum",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{default:{http:["https://matic-mumbai.chainstacklabs.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"}},testnet:!0};var Vf={id:690,name:"Redstone",network:"redstone",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.redstonechain.com"]},public:{http:["https://rpc.redstonechain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.redstone.xyz/"}}};var qf={id:17001,name:"Redstone Holesky",network:"redstone-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.holesky.redstone.xyz"]},public:{http:["https://rpc.holesky.redstone.xyz"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"},default:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"}}};var zf={id:11155111,network:"sepolia",name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"SEP",decimals:18},rpcUrls:{privy:{http:["https://sepolia.rpc.privy.systems"]},alchemy:{http:["https://eth-sepolia.g.alchemy.com/v2"],webSocket:["wss://eth-sepolia.g.alchemy.com/v2"]},infura:{http:["https://sepolia.infura.io/v3"],webSocket:["wss://sepolia.infura.io/ws/v3"]},default:{http:["https://rpc.sepolia.org"]},public:{http:["https://rpc.sepolia.org"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://sepolia.etherscan.io"},default:{name:"Etherscan",url:"https://sepolia.etherscan.io"}},testnet:!0};var $f={id:7777777,name:"Zora",network:"zora",nativeCurrency:{decimals:18,name:"Ether",symbol:"ETH"},rpcUrls:{default:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]},public:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://explorer.zora.energy"}}};var Kf={id:999999999,name:"Zora Sepolia",network:"zora-sepolia",nativeCurrency:{decimals:18,name:"Zora Sepolia",symbol:"ETH"},rpcUrls:{default:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]},public:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]}},blockExplorers:{default:{name:"Zora Sepolia Explorer",url:"https://sepolia.explorer.zora.energy/"}},testnet:!0};var Yf={id:999,name:"Zora Goerli Testnet",network:"zora-testnet",nativeCurrency:{decimals:18,name:"Zora Goerli",symbol:"ETH"},rpcUrls:{default:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]},public:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://testnet.explorer.zora.energy"}},testnet:!0};var Ea=[Cf,wf,bf,Wf,zf,fl,Uf,Ff,Bf,Hf,Gf,xf,kf,Rf,If,Sf,_f,Pf,Af,Df,Lf,Nf,Ef,Tf,$f,Yf,Kf,Of,Vf,Mf,qf],lI=new Set(Ea.map(e=>e.id));import In from"tinycolor2";var jf="#FFFFFF",P3="#040217",A3=jf,x3="#1E1E1D";function k3(e){return e<.8&&e>.2&&console.warn("Background color is not light or dark enough, which could lead to accessibility issues."),e>.5?"light":"dark"}function Ur(e,t){let r=Math.max(0,Math.min(1,e.toHsl().l+t));return In({...e.toHsl(),l:r})}var R3="#51BA81",I3="#FFB74D",M3="#EC6351",W3=jf,O3=P3;function Zf({backgroundTheme:e,accentHex:t}){let r;switch(e){case"light":r=A3;break;case"dark":r=x3;break;default:r=e;break}let o=In(r),n=In(t),i=In(R3),a=In(I3),l=In(M3),s=k3(o.getLuminance()),c=Ur(o,s==="light"?-.04:.11),m=Ur(o,s==="light"?-.88:.87),f=Ur(o,s==="light"?-.7:.75),u=Ur(o,s==="light"?-.43:.45).desaturate(s==="light"?60:20),C=Ur(o,s==="light"?-.08:.25).desaturate(s==="light"?60:20),v=Ur(n,.15),g=Ur(n,-.06),b=Ur(l,.3),E=Ur(a,.3),k=In(n.getLuminance()>.5?O3:W3),_=Ur(i,-.16),S=Ur(i,.4);return{colorScheme:s,background:o.toHslString(),background2:c.toHslString(),foreground:m.toHslString(),foreground2:f.toHslString(),foreground3:u.toHslString(),foreground4:C.toHslString(),accent:n.toHslString(),accentLight:v.toHslString(),accentDark:g.toHslString(),foregroundAccent:k.toHslString(),success:i.toHslString(),successDark:_.toHslString(),successLight:S.toHslString(),error:l.toHslString(),errorLight:b.toHslString(),warn:a.toHslString(),warnLight:E.toHslString()}}function Md(e,t,r){let o=r?console.warn:()=>{},n,i,a,l,s,c,m,f,u,C,v,g,b,E,k;t?.loginMethods?(n=t.loginMethods.includes("email"),i=t.loginMethods.includes("sms"),l=t.loginMethods.includes("wallet"),s=t.loginMethods.includes("google"),c=t.loginMethods.includes("twitter"),m=t.loginMethods.includes("discord"),u=t.loginMethods.includes("spotify"),C=t.loginMethods.includes("instagram"),f=t.loginMethods.includes("tiktok"),g=t.loginMethods.includes("github"),v=t.loginMethods.includes("linkedin"),b=t.loginMethods.includes("apple"),E=t.loginMethods.includes("farcaster"),k=t.loginMethods.includes("telegram")):(n=e.emailAuth,i=e.smsAuth,l=e.walletAuth,s=e.googleOAuth,c=e.twitterOAuth,m=e.discordOAuth,g=e.githubOAuth,u=e.spotifyOAuth,C=e.instagramOAuth,f=e.tiktokOAuth,v=e.linkedinOAuth,b=e.appleOAuth,E=e.farcasterAuth,k=e.telegramAuth),typeof window<"u"&&typeof window.PublicKeyCredential!="function"?a=!1:e.passkeyAuth&&(a=!0);let _=[n,i].filter(Boolean),S=[s,c,m,g,u,C,f,v,b,E,k].filter(Boolean),R=[l].filter(Boolean);if(_.length+S.length+R.length===0)throw new Error("You must enable at least one login method");let M=t?.appearance?.showWalletLoginFirst!==void 0?t?.appearance?.showWalletLoginFirst:e.showWalletLoginFirst;M&&R.length===0?(o("You should only enable `showWalletLoginFirst` when `wallet` logins are also enabled. `showWalletLoginFirst` has been set to false"),M=!1):!M&&S.length+_.length===0&&(o("You should only disable `showWalletLoginFirst` when `email`, `sms`, or social logins are also enabled. `showWalletLoginFirst` has been set to true"),M=!0);let D=t?.externalWallets?.walletConnect?.enabled??!0;t?.loginMethods&&t.loginMethodsAndOrder&&o("You should only configure one of `loginMethods` or `loginMethodsAndOrder`");let H=vf({input:t?.appearance?.walletList,overrides:t?.loginMethodsAndOrder}),K=hf({input:t?.loginMethodsAndOrder}),Y=t?.intl?.defaultCountry??"US",{chains:O,defaultChain:U}=L3({additionalChains:t?.additionalChains,supportedChains:t?.supportedChains,defaultChainFromConfig:t?.defaultChain,hasRpcConfigDefined:Object.keys(t?.rpcConfig?.rpcUrls??{}).length>0}),W=!!t?.defaultChain,be=t?.customAuth?.getCustomAccessToken&&t?.customAuth?.enabled!==!1,ce,X=!(e.enforceWalletUis??!0);if(e.legacyWalletUiConfig??!0?be?ce=t?.embeddedWallets?.noPromptOnSignature??!0:ce=t?.embeddedWallets?.noPromptOnSignature??X:ce=X,t?.embeddedWallets?.waitForTransactionConfirmation===!1&&ce!==!0)throw new Error("Overriding `config.embeddedWallets.waitForTransactionConfirmation` requires that you disable wallet UIs in the dashboard.");let{requireUserPasswordOnCreate:ne,...ee}=t?.embeddedWallets??{};return{id:e.id,name:e.name,allowlistConfig:e.allowlistConfig,legacyWalletUiConfig:e.legacyWalletUiConfig,appearance:{logo:t?.appearance?.logo??e.logoUrl,landingHeader:t?.appearance?.landingHeader??Nt.appearance.landingHeader,loginMessage:typeof t?.appearance?.loginMessage=="string"?t?.appearance?.loginMessage.slice(0,100):t?.appearance?.loginMessage,palette:Zf({backgroundTheme:t?.appearance?.theme??Nt.appearance.theme,accentHex:t?.appearance?.accentColor??e.accentColor??Nt.appearance.accentColor}),loginGroupPriority:M?"web3-first":"web2-first",hideDirectWeb2Inputs:!!t?.appearance?.hideDirectWeb2Inputs,walletList:H},loginMethods:{wallet:l,email:n,sms:i,passkey:a,google:s,twitter:c,discord:m,github:g,spotify:u,instagram:C,tiktok:f,linkedin:v,apple:b,farcaster:E,telegram:k},loginMethodsAndOrder:K,legal:{termsAndConditionsUrl:t?.legal?.termsAndConditionsUrl??e.termsAndConditionsUrl,privacyPolicyUrl:t?.legal?.privacyPolicyUrl??e.privacyPolicyUrl,requireUsersAcceptTerms:e.requireUsersAcceptTerms??!1},walletConnectCloudProjectId:t?.walletConnectCloudProjectId??e.walletConnectCloudProjectId??Nt.walletConnectCloudProjectId,rpcConfig:{rpcUrls:t?.rpcConfig?.rpcUrls??Nt.rpcConfig.rpcUrls,rpcTimeouts:t?.rpcConfig?.rpcTimeouts??Nt.rpcConfig.rpcTimeouts},chains:O,defaultChain:U,intl:{defaultCountry:Y},shouldEnforceDefaultChainOnConnect:W,captchaEnabled:e.captchaEnabled??Nt.captchaEnabled,captchaSiteKey:e.captchaSiteKey,externalWallets:{coinbaseWallet:{connectionOptions:t?.externalWallets?.coinbaseWallet?.connectionOptions??Nt.externalWallets.coinbaseWallet.connectionOptions},walletConnect:{enabled:D}},embeddedWallets:{...e.embeddedWalletConfig,...typeof ne=="boolean"?{requireUserOwnedRecoveryOnCreate:ne}:{},...be?{createOnLogin:"all-users",requireUserOwnedRecoveryOnCreate:!1,userOwnedRecoveryOptions:["user-passcode"]}:{},waitForTransactionConfirmation:!0,priceDisplay:{primary:"fiat-currency",secondary:"native-token"},...ee,noPromptOnSignature:ce},mfa:{methods:e.mfaMethods??[],noPromptOnMfaRequired:t?.mfa?.noPromptOnMfaRequired??!1},customAuth:be?{enabled:!0,...t.customAuth}:void 0,loginConfig:{twitterOAuthOnMobileEnabled:e.twitterOAuthOnMobileEnabled??!1,telegramAuthConfiguration:e.telegramAuthConfiguration},headless:!!t?.headless,render:{standalone:t?._render?.standalone??Nt._render.standalone},fundingConfig:e.fundingConfig,fundingMethodConfig:{...t?.fundingMethodConfig??Nt.fundingMethodConfig,moonpay:{...t?.fundingMethodConfig?.moonpay??Nt.fundingMethodConfig.moonpay,useSandbox:t?.fundingMethodConfig?.moonpay.useSandbox??t?.fiatOnRamp?.useSandbox??Nt.fundingMethodConfig.moonpay.useSandbox}}}}function Qf(e,t){if(!e)return{legacyCreateEmbeddedWalletFlag:t};let{appearance:r,additionalChains:o,supportedChains:n,defaultChain:i,...a}=e;return{...a,...o?{additionalChains:o.map(s=>s.id)}:void 0,...n?{supportedChains:n.map(s=>s.id)}:void 0,...i?{defaultChain:i.id}:void 0,legacyCreateEmbeddedWalletFlag:t}}function L3({additionalChains:e,supportedChains:t,defaultChainFromConfig:r,hasRpcConfigDefined:o}){let n;if(e&&t&&console.warn("You should only specify one of `additionalChains` or `supportedChains`. Using `supportedChains`."),t){if(t.length===0)throw new Error("`supportedChains` must contain at least one chain");t.filter(s=>s.rpcUrls.privyWalletOverride).length>0&&o&&console.warn("You have specified at least one `supportedChain` with `privyWalletOverride` but also have `rpcConfig` defined. The `rpcConfig` will be ignored. `rpcConfig` is deprecated and you should use `privyWalletOverride` in a `supportedChain`."),n=t.map(s=>s.rpcUrls.privyWalletOverride?s:Ea.find(m=>m.id===s.id)??s)}else n=Ea.concat(e??[]);let i=t?n[0]:fl,a=r??i;if(!n.find(l=>l.id===a.id))throw new Error("`defaultChain` must be included in `supportedChains`");return{chains:n,defaultChain:a}}var Jf=function(e,t=0){let r=3735928559^t,o=1103547991^t;for(let n=0,i;n<e.length;n++)i=e.charCodeAt(n),r=Math.imul(r^i,2654435761),o=Math.imul(o^i,1597334677);return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)};import{jsx as F3}from"react/jsx-runtime";var th={showWalletLoginFirst:!0,allowlistConfig:{errorTitle:null,errorDetail:null,errorCtaText:null,errorCtaLink:null},walletAuth:!0,emailAuth:!0,smsAuth:!1,googleOAuth:!1,twitterOAuth:!1,discordOAuth:!1,githubOAuth:!1,linkedinOAuth:!1,appleOAuth:!1,termsAndConditionsUrl:null,privacyPolicyUrl:null,embeddedWalletConfig:{createOnLogin:"off",requireUserOwnedRecoveryOnCreate:!1,userOwnedRecoveryOptions:["user-passcode"]},fiatOnRampEnabled:!1,captchaEnabled:!1,captchaSiteKey:""},Wd=Md(th,void 0,!1),Od=U3({appConfig:Wd,isServerConfigLoaded:!1}),rh=({children:e,legacyCreateEmbeddedWalletFlag:t,client:r,clientConfig:o})=>{let[n,i]=D3(null),a=N3(()=>Md(n??th,o,!!n),[n,o]);return Xf(()=>{if(!n)return;let l=Qf(o,t),s=Jf(JSON.stringify(l)).toString(),c=`privy:sent:${n.id}:${s}`;localStorage.getItem(c)||(r.createAnalyticsEvent({eventName:"sdk_initialize",payload:l}),localStorage.setItem(c,"t"))},[o,t,n]),Xf(()=>{n||(async()=>{try{let s=await r.getServerConfig();s.customApiUrl&&r.updateApiUrl(s.customApiUrl),i(s)}catch(s){console.warn("Error generating app config: ",s)}})()},[]),F3(Od.Provider,{value:{appConfig:a,isServerConfigLoaded:!!n},children:e})},Ne=()=>{let{appConfig:e}=eh(Od);return e},hl=()=>{let{isServerConfigLoaded:e}=eh(Od);return e};var T=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};import{jsx as z3,jsxs as $3}from"react/jsx-runtime";var oh=B3({ready:!1,app:Wd,currentScreen:null,lastScreen:null,navigate:T,navigateBack:T,resetNavigation:T,setModalData:T,onUserCloseViaDialogOrKeybindRef:void 0}),q3=["LANDING","CONNECT_ONLY_LANDING_SCREEN",null],nh=e=>{let t=Ne(),r=e.authenticated,[o,n]=V3(e.initialScreen);Ld(()=>{!r&&!q3.includes(e.initialScreen)&&e.setInitialScreen(null)},[r]);let i=G3(null);Ld(()=>{e.open||(i.current=null)},[e.open]),Ld(()=>{i.current=null},[e.initialScreen]);let a={ready:!!t.id,app:t,data:e.data,setModalData:e.setModalData,currentScreen:e.initialScreen,lastScreen:o,navigate:(l,s=!0)=>{e.setInitialScreen(l),s&&n(e.initialScreen)},navigateBack:()=>{e.setInitialScreen(o)},resetNavigation:()=>{e.setInitialScreen(null),n(null)},onUserCloseViaDialogOrKeybindRef:i};return $3(oh.Provider,{value:a,children:[(typeof t.appearance.logo=="string"||t.appearance.logo?.type==="img")&&z3(ff,{src:typeof t.appearance.logo=="string"?t.appearance.logo:t.appearance.logo.props.src}),e.children]})},P=()=>H3(oh);import{jsx as Ei,jsxs as K3}from"react/jsx-runtime";var Ta=({style:e,...t})=>{let{app:r}=P();return K3("svg",{width:"28",height:"28",viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...e},...t,children:[Ei("rect",{width:"28",height:"28",rx:"3",fill:r?.appearance.palette.colorScheme==="dark"?"#3396ff":"#141414"}),Ei("g",{clipPath:"url(#clip0_1765_9946)",children:Ei("path",{d:"M8.09448 10.3941C11.3558 7.20196 16.6442 7.20196 19.9055 10.3941L20.2982 10.7782C20.3369 10.8157 20.3677 10.8606 20.3887 10.9102C20.4097 10.9599 20.4206 11.0132 20.4206 11.0671C20.4206 11.121 20.4097 11.1744 20.3887 11.224C20.3677 11.2737 20.3369 11.3186 20.2982 11.3561L18.9554 12.6702C18.9158 12.7086 18.8628 12.7301 18.8077 12.7301C18.7526 12.7301 18.6996 12.7086 18.66 12.6702L18.1198 12.1415C15.8448 9.91503 12.1557 9.91503 9.88015 12.1415L9.30167 12.7075C9.26207 12.7459 9.20909 12.7673 9.15395 12.7673C9.0988 12.7673 9.04582 12.7459 9.00622 12.7075L7.66346 11.3934C7.62475 11.3559 7.59397 11.3109 7.57295 11.2613C7.55193 11.2117 7.5411 11.1583 7.5411 11.1044C7.5411 11.0505 7.55193 10.9971 7.57295 10.9475C7.59397 10.8979 7.62475 10.8529 7.66346 10.8154L8.09448 10.3941ZM22.6829 13.1115L23.8776 14.2814C23.9163 14.319 23.9471 14.3639 23.9681 14.4135C23.9892 14.4632 24 14.5165 24 14.5704C24 14.6243 23.9892 14.6777 23.9681 14.7273C23.9471 14.777 23.9163 14.8219 23.8776 14.8594L18.4893 20.1332C18.4102 20.2101 18.3042 20.2531 18.1938 20.2531C18.0835 20.2531 17.9775 20.2101 17.8984 20.1332L14.0743 16.3901C14.0545 16.3708 14.0279 16.36 14.0003 16.36C13.9726 16.36 13.9461 16.3708 13.9263 16.3901L10.1021 20.1332C10.023 20.2101 9.91703 20.2531 9.8067 20.2531C9.69636 20.2531 9.59038 20.2101 9.51124 20.1332L4.12236 14.8594C4.08365 14.8219 4.05287 14.777 4.03185 14.7273C4.01083 14.6777 4 14.6243 4 14.5704C4 14.5165 4.01083 14.4632 4.03185 14.4135C4.05287 14.3639 4.08365 14.319 4.12236 14.2814L5.31767 13.1115C5.39678 13.0348 5.50265 12.9919 5.61285 12.9919C5.72305 12.9919 5.82892 13.0348 5.90803 13.1115L9.73216 16.8546C9.75194 16.874 9.7785 16.8848 9.80616 16.8848C9.83381 16.8848 9.86037 16.874 9.88015 16.8546L13.7043 13.1115C13.7834 13.0346 13.8894 12.9916 13.9997 12.9916C14.1101 12.9916 14.216 13.0346 14.2952 13.1115L18.1198 16.8546C18.1396 16.874 18.1662 16.8848 18.1938 16.8848C18.2215 16.8848 18.2481 16.874 18.2678 16.8546L22.092 13.1115C22.1711 13.0346 22.2771 12.9916 22.3874 12.9916C22.4977 12.9916 22.6037 13.0346 22.6829 13.1115Z",fill:"white"})}),Ei("defs",{children:Ei("clipPath",{id:"clip0_1765_9946",children:Ei("rect",{width:"20",height:"12.2531",fill:"white",transform:"translate(4 8)"})})})]})};var Fr=class extends Kt{constructor(r,o,n,i,a,l,s,c){super(c||"unknown",n,i,o);this.connectorType="wallet_connect_v2";this.privyAppId=l,this.privyAppName=s,this.walletConnectCloudProjectId=r,this.rpcConfig=o,this.shouldEnforceDefaultChainOnConnect=a,this.proxyProvider=new Ke(void 0,this.rpcTimeoutDuration),c&&(this.walletEntry=Us[c],this.walletClientType=c)}async initialize(){let r=await this.createProvider();if(this.provider=r,this.proxyProvider.setWalletProvider(r),this.subscribeListeners(),r.session){if(this.walletProvider?.session?.peer.metadata.url){let n=Ds(this.walletProvider?.session?.peer.metadata.url);this.walletEntry=n?.entry,this.walletClientType=n?.walletClientType||"unknown"}this.connected=!0,await this.syncAccounts()}this.initialized=!0,this.emit("initialized");let{WalletConnectModal:o}=await import("@walletconnect/modal");this.modal=new o({projectId:this.walletConnectCloudProjectId,themeVariables:{"--wcm-z-index":"1000000"}}),this.modal.subscribeModal(n=>{!n.open&&!this.walletProvider?.session&&this.onQrModalClosed&&this.onQrModalClosed()})}async connect(r){return r.showPrompt&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return!!this.walletProvider?.connected}get walletBranding(){return this.walletClientType==="metamask"?{name:"MetaMask",icon:vi,id:"io.metamask"}:{name:bm(this.walletProvider?.session?.peer.metadata.name||"")||"WalletConnect",icon:this.walletProvider?.session?.peer.metadata.icons?.[0]||Ta,id:this.walletProvider?.session?.peer.metadata.name.toLowerCase()||"wallet_connect_v2"}}async resetConnection(r){this.walletProvider&&this.walletProvider.connected&&(await this.walletProvider.disconnect(),this.walletProvider.signer.session=void 0,this.walletEntry=Us[r],this.walletClientType=r,this.redirectUri=void 0,this.fallbackUniversalRedirectUri=void 0,Rm(),this.onDisconnect())}async promptConnection(){if(this.provider)return new Promise((r,o)=>{let n=()=>{o(new hi)};this.onQrModalClosed=n,(async()=>{let a="",l=await Promise.race([this.walletProvider?.enable(),this.proxyProvider.walletTimeout()]);if(l?.length&&(a=l[0]),!a||a==="")throw new pe("Unable to retrieve address");if(this.walletProvider?.session?.peer.metadata.url){let s=Ds(this.walletProvider?.session?.peer.metadata.url);this.walletEntry=s?.entry,this.walletClientType=s?.walletClientType||"unknown",this.proxyProvider.rpcTimeoutDuration=yi(this.rpcConfig,this.walletClientType)}this.connected=!0,await this.syncAccounts(l),r()})().catch(a=>{if(a){o(Dr(a));return}o(new pe("Unknown error during connection"))}).finally(()=>this.modal?.closeModal())})}disconnect(){this.walletProvider?.disconnect().then(()=>this.onDisconnect()).catch(()=>console.warn("Unable to disconnect Wallet Connect provider"))}get walletProvider(){return this.proxyProvider.walletProvider}setWalletProvider(r){this.proxyProvider.setWalletProvider(r)}async createProvider(){let r={};for(let a of this.chains){let l=Tm(a.id,this.chains,this.rpcConfig,this.privyAppId);l&&(r[a.id]=l)}let o=this.shouldEnforceDefaultChainOnConnect?[this.defaultChain.id]:[],n=this.chains.map(a=>a.id),i=await Y3.init({projectId:this.walletConnectCloudProjectId,chains:o,optionalChains:n,optionalEvents:j3,optionalMethods:Z3,rpcMap:r,showQrModal:!1,metadata:{description:this.privyAppName,name:this.privyAppName,url:window.location.toString(),icons:[]}});return i.on("display_uri",a=>{if(i.signer.abortPairingAttempt(),Q3&&this.walletEntry){let{redirect:l,href:s}=Am(a,this.walletEntry);Im({href:s,name:this.walletEntry.displayName}),this.redirectUri=l;let c=xm(a,this.walletEntry);c?.redirect&&(this.fallbackUniversalRedirectUri=c.redirect),Fs(l,"_self")}else this.modal?.openModal({uri:a,chains:[this.defaultChain.id]})}),i.on("connect",()=>{if(this.modal?.closeModal(),i.session?.peer.metadata.url){let a=Ds(i.session?.peer.metadata.url);this.walletEntry=a?.entry,this.walletClientType=a?.walletClientType||"unknown"}}),i}async enableProvider(){return this.walletProvider?.connected?Promise.resolve(this.walletProvider.accounts):await this.walletProvider?.enable()}};var Dd=e=>{let t=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses")?.split(" ").filter(o=>J3(o)).map(o=>ih(o));return t?.length?!!e?.linkedAccounts.filter(o=>o.type=="wallet"&&t.includes(o.address)).length:!1},yi=(e,t)=>e.rpcTimeouts?e.rpcTimeouts[t]||_n:_n,Sa=class extends X3{constructor(r,o,n,i,a,l,s,c,m,f,u){super();this.getEthereumProvider=()=>{let r=this.wallets[0],o=this.walletConnectors.find(n=>n.wallets.find(i=>i.address===r?.address));return!r||!o?new Ke:o.proxyProvider};this.privyAppId=r,this.walletConnectCloudProjectId=o,this.rpcConfig=n,this.chains=i,this.defaultChain=a,this.walletConnectors=[],this.initialized=!1,this.store=l,this.walletList=s,this.shouldEnforceDefaultChainOnConnect=c,this.externalWalletConfig=m,this.privyAppName=f,this.privyAppLogo=u,this.storedConnections=Nd()}get wallets(){let r=new Set,o=this.walletConnectors.flatMap(i=>i.wallets).sort((i,a)=>i.connectedAt&&a.connectedAt?a.connectedAt-i.connectedAt:0).filter(i=>{let a=`${i.address}${i.walletClientType}${i.connectorType}`;return r.has(a)?!1:(r.add(a),!0)}),n=o.findIndex(i=>i.address===(this.activeWallet?this.activeWallet:"unknown"));return n>=0&&o.unshift(o.splice(n,1)[0]),o}async initialize(){if(this.initialized)return;j.get(Pd)&&(j.getKeys().forEach(o=>{o.startsWith("walletconnect")&&j.del(o)}),j.del(Pd));let r=Em(this.store,this.walletList,this.externalWalletConfig).then(o=>{o.forEach(({type:n,eip6963InjectedProvider:i,legacyInjectedProvider:a})=>{this.createWalletConnector("injected",n,{eip6963InjectedProvider:i,legacyInjectedProvider:a})})});this.walletList.includes("coinbase_wallet")&&this.createWalletConnector("coinbase_wallet","coinbase_wallet"),!No()&&this.walletList.includes("phantom")&&this.createWalletConnector("phantom","phantom"),this.externalWalletConfig.walletConnect.enabled&&this.createWalletConnector("wallet_connect_v2","unknown"),await r,this.initialized=!0}findWalletConnector(r,o){return r==="wallet_connect_v2"?this.walletConnectors.find(n=>n.connectorType===r)??null:this.walletConnectors.find(n=>n.connectorType===r&&n.walletClientType===o)??null}onInitialized(r){r.wallets.forEach(o=>{let n=this.storedConnections.find(i=>i.address===o.address&&i.connectorType===o.connectorType&&i.walletClientType===o.walletClientType);n&&(o.connectedAt=n.connectedAt)}),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(r){r.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnector(r,o,n,i){let a=this.findWalletConnector("embedded","privy");if(a)a.proxyProvider.walletProxy=r;else{let l=new wa(r,o,this.rpcConfig,this.chains,i,n.id),s=new ba(l,this.chains,n,this.rpcConfig);this.addWalletConnector(s)}}addImportedWalletConnector(r,o,n,i){let a=this.findWalletConnector("embedded_imported","privy");if(a)a.proxyProvider.walletProxy=r;else{let l=new wa(r,o,this.rpcConfig,this.chains,i,n.id),s=!0,c=new ba(l,this.chains,n,this.rpcConfig,s);this.addWalletConnector(c)}}removeEmbeddedWalletConnector(){let r=this.findWalletConnector("embedded","privy");if(r){let o=this.walletConnectors.indexOf(r);this.walletConnectors.splice(o,1),this.saveConnectionHistory(),this.storedConnections=Nd(),this.emit("walletsUpdated")}}removeImportedWalletConnector(){let r=this.findWalletConnector("embedded_imported","privy");if(r){let o=this.walletConnectors.indexOf(r);this.walletConnectors.splice(o,1),this.saveConnectionHistory(),this.storedConnections=Nd(),this.emit("walletsUpdated")}}async createWalletConnector(r,o,n){let i=this.findWalletConnector(r,o);if(i)return i instanceof Fr&&i.resetConnection(o),i;let l=(()=>{if(r==="injected"){if(o==="metamask"&&n?.eip6963InjectedProvider)return new pl(this.chains,this.defaultChain,this.rpcConfig,n?.eip6963InjectedProvider,"metamask");if(o==="metamask"&&n?.legacyInjectedProvider)return new bi(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider,"metamask");if(o==="phantom"&&n?.legacyInjectedProvider)return new bi(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider,"phantom");if(n?.legacyInjectedProvider&&o==="unknown_browser_extension")return new bi(this.chains,this.defaultChain,this.rpcConfig,n?.legacyInjectedProvider);if(n?.eip6963InjectedProvider)return new wi(this.chains,this.defaultChain,this.rpcConfig,n?.eip6963InjectedProvider,o)}else return r==="coinbase_wallet"?new dl(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):r==="phantom"?new ml(this.defaultChain):new Fr(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,o)})();return l&&this.addWalletConnector(l),l||null}addWalletConnector(r){this.walletConnectors.push(r),r.on("initialized",()=>this.onInitialized(r)),r.on("walletsUpdated",()=>this.onWalletsUpdated(r)),r.initialize().catch(o=>{console.debug("Failed to initialize connector",o)})}saveConnectionHistory(){let r=this.wallets.map(o=>({address:o.address,connectorType:o.connectorType,walletClientType:o.walletClientType,connectedAt:o.connectedAt}));j.put(Ad,r)}async activeWalletSign(r){let o=this.wallets,n=o.length>0?o[0]:null;return n?n.sign(r):null}setActiveWallet(r){this.activeWallet=ih(r),this.emit("walletsUpdated")}};function ll(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){let o=e[r],n=t[r];if(o?.address!==n?.address||o?.chainId!==n?.chainId||o?.connectorType!==n?.connectorType||o?.connectedAt!==n?.connectedAt||o?.walletClientType!==n?.walletClientType||o?.isConnected!==n?.isConnected||o?.linked!==n?.linked)return!1}return!0}var e0=e=>e&&typeof e.address=="string"&&typeof e.connectorType=="string"&&typeof e.walletClientType=="string"&&typeof e.connectedAt=="number",Nd=()=>{let e=j.get(Ad);return e&&Array.isArray(e)&&e.map(o=>e0(o)).every(Boolean)?e:[]};import{ofetch as t0}from"ofetch";var r0=[_s,As,Ps,Rs],yl=class{constructor({appId:t,appClientId:r,client:o,defaults:n}){this.appId=t,this.appClientId=r,this.clientAnalyticsId=o.clientAnalyticsId,this.sdkVersion=Ed,this.client=o,this.defaults=n,this.fallbackApiUrl=o.fallbackApiUrl,this.baseFetch=t0.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:i,options:a})=>{let l=new Headers(a.headers);l.set("privy-app-id",this.appId),this.appClientId&&l.set("privy-client-id",this.appClientId),l.set("privy-ca-id",this.clientAnalyticsId||""),l.set("privy-client",`react-auth:${this.sdkVersion}`);let s=r0.includes(i.toString());if(!l.has("authorization")){let c=await this.client.getAccessToken({disableAutoRefresh:s});c!==null&&l.set("authorization",`Bearer ${c}`)}a.headers=l,a.retryDelay&&(a.retryDelay=a.retryDelay*3)},onRequestError:({error:i})=>{if(i instanceof DOMException&&i.name==="AbortError")throw new Ts}})}async get(t,r){try{return await this.baseFetch(t,r)}catch(o){throw le(o)}}async post(t,r,o){try{return await this.baseFetch(t,{method:"POST",...r?{body:r}:{},...o})}catch(n){throw le(n)}}async delete(t,r){try{return await this.baseFetch(t,{method:"DELETE",...r})}catch(o){throw le(o)}}};var ah=e=>({challenge:e.challenge,allowCredentials:e.allow_credentials?.map(t=>({id:t.id,type:t.type,transports:t.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});import Ho from"js-cookie";function sh(e){return e instanceof Lo?"email":e instanceof Do?"sms":e instanceof So?"siwe":e instanceof di?"guest":e instanceof si?"custom_auth":e instanceof Xr?e.meta.provider:null}import*as lh from"jose";var Ar=class{static parse(t){try{return new Ar(t)}catch{return null}}constructor(t){this.value=t,this._decoded=lh.decodeJwt(t)}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(t=0){let r=Date.now(),o=(this.expiration-t)*1e3;return r>=o}};var o0=30,gl=class{constructor(){this.authenticateOnce=new Le(async t=>this._authenticate(t)),this.linkOnce=new Le(async t=>this._link(t)),this.refreshOnce=new Le(this._refresh.bind(this)),this.destroyOnce=new Le(this._destroy.bind(this)),this.forkSessionOnce=new Le(this._forkSession.bind(this))}get token(){try{let t=j.get(bn);return typeof t=="string"?new Ar(t).value:null}catch(t){return console.error(t),this.destroyLocalState(),null}}get refreshToken(){try{let t=j.get(Gs);return typeof t=="string"?t:null}catch(t){return console.error(t),this.destroyLocalState(),null}}get forkedToken(){try{let t=j.get(ma);return typeof t=="string"?t:null}catch(t){return console.error(t),this.destroyLocalState(),null}}getProviderAccessToken(t){try{let r=j.get(ha(t));if(typeof r=="string"){let o=new Ar(r);return o.isExpired()?(j.del(ha(t)),null):o.value}else return null}catch(r){return console.error(r),null}}get mightHaveServerCookies(){try{let t=Ho.get(Vs);return t!==void 0&&t.length>0}catch(t){console.error(t)}return!1}hasRefreshCredentials(){return this.mightHaveServerCookies||typeof this.token=="string"&&typeof this.refreshToken=="string"&&this.refreshToken!==Gm}hasRecoveryCredentials(){return typeof this.forkedToken=="string"}hasActiveToken(){let t=Ar.parse(this.token);return t!==null&&!t.isExpired(o0)}authenticate(t){return this.authenticateOnce.execute(t)}link(t){return this.linkOnce.execute(t)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(t,r){typeof r=="string"?j.put(ha(t),r):j.del(ha(t))}async _authenticate(t){try{let r=await t.authenticate(),{user:o,is_new_user:n,oauth_tokens:i}=r;this.handleTokenResponse(r);let a=i,l=a?{provider:a.provider,accessToken:a.access_token,accessTokenExpiresInSeconds:a.access_token_expires_in_seconds,refreshToken:a.refresh_token,refreshTokenExpiresInSeconds:i.refresh_token_expires_in_seconds,scopes:a.scopes}:void 0,s=sh(t);return s&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:s,isNewUser:n}}),s==="siwe"&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:t.meta.connectorType,walletClientType:t.meta.walletClientType}}),{user:$t(o),isNewUser:n,oAuthTokens:l}}catch(r){throw console.warn("Error authenticating session"),rt(r)}}async _link(t){try{let r=await t.link(),o=r.oauth_tokens,n=o?{provider:o.provider,accessToken:o.access_token,accessTokenExpiresInSeconds:o.access_token_expires_in_seconds,refreshToken:o.refresh_token,refreshTokenExpiresInSeconds:o.refresh_token_expires_in_seconds,scopes:o.scopes}:void 0;return{user:$t(r),oAuthTokens:n}}catch(r){throw console.warn("Error linking account"),rt(r)}}async _refresh(){if(!this.api)throw new w("Session has no API instance");if(!this.client)throw new w("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let t=this.token,r=this.refreshToken,o=this.forkedToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let n;if(t&&r||this.mightHaveServerCookies){let i={};t&&(i.authorization=`Bearer ${t}`);let a=r?{refresh_token:r}:{};n=await this.api.post(_s,a,{headers:i}),o&&this.clearForkedToken()}else if(o)n=await this.api.post(As,{refresh_token:o}),this.clearForkedToken();else return null;return this.handleTokenResponse(n),$t(n.user)}catch(n){if(n instanceof Wt&&n.privyErrorCode==="missing_or_invalid_token")return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw rt(n)}}handleTokenResponse(t){t.session_update_action?t.session_update_action==="set"?(this.storeRefreshToken(t.refresh_token),this.storeToken(t.token),t.identity_token&&this.storeIdentityToken(t.identity_token)):t.session_update_action==="clear"?this.destroyLocalState():t.session_update_action==="ignore"&&t.token&&(this.storeToken(t.token),t.identity_token&&this.storeIdentityToken(t.identity_token)):(this.storeRefreshToken(t.refresh_token),this.storeToken(t.token),t.identity_token&&this.storeIdentityToken(t.identity_token))}async _destroy(){try{await this.api?.post(Ps,{refresh_token:this.refreshToken})}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new w("Session has no API instance");let t=this.refreshToken;try{let r=await this.api.post(Ru,{refresh_token:t});return this.storeRefreshToken(r.refresh_token),this.storeToken(r.token),r.new_session_refresh_token}catch(r){throw rt(r)}}destroyLocalState(){this.storeRefreshToken(null),this.storeToken(null),this.clearIdentityToken(),this.clearForkedToken()}storeToken(t){if(typeof t=="string"){let r=j.get(bn);if(j.put(bn,t),!this.client?.useServerCookies){let o=Ar.parse(t)?.expiration;Ho.set(Td,t,{sameSite:"Strict",secure:!0,expires:o?new Date(o*1e3):void 0})}r!==t&&this.client?.onStoreToken?.(t)}else j.del(bn),Ho.remove(Td),this.client?.onDeleteToken?.()}storeRefreshToken(t){typeof t=="string"?(j.put(Gs,t),this.client?.useServerCookies||Ho.set(Vs,"t",{sameSite:"Strict",secure:!0,expires:30})):(j.del(Gs),Ho.remove(Dm),Ho.remove(Vs))}storeIdentityToken(t){if(this.client?.useServerCookies)return;j.put(Sd,t);let r=Ar.parse(t)?.expiration;Ho.set(_d,t,{sameSite:"Strict",secure:!0,expires:r?new Date(r*1e3):void 0})}clearIdentityToken(){j.del(Sd),Ho.remove(_d)}clearForkedToken(){j.del(ma)}};var Ud,vl,ch,_a=class{constructor(t){Es(this,vl);this.apiUrl=t.apiUrl||Bs,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=!!t.apiUrl&&t.apiUrl.startsWith("https://privy."),this.timeout=t.timeout||Nm,this.appId=t.appId,this.appClientId=t.appClientId,this.clientAnalyticsId=ku(this,vl,ch).call(this),Ud||(Ud=new gl),this.session=Ud,this.api=this.generateApi(),this.session.client=this}initializeConnectorManager({walletConnectCloudProjectId:t,rpcConfig:r,chains:o,defaultChain:n,store:i,walletList:a,shouldEnforceDefaultChainOnConnect:l,externalWalletConfig:s,appName:c}){this.connectors||(this.connectors=new Sa(this.appId,t,r,o,n,i,a,l,s,c))}sessionHasActiveToken(){return this.session.hasActiveToken()}generateApi(){let t=new yl({appId:this.appId,appClientId:this.appClientId,client:this,defaults:{baseURL:this.apiUrl,timeout:this.timeout}});return this.session.api=t,t}updateApiUrl(t){this.apiUrl=t||this.fallbackApiUrl,this.api=this.generateApi(),t&&(this.useServerCookies=!0)}authenticate(){if(!this.authFlow)throw new w("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new w("No auth flow in progress.");let{oAuthTokens:t}=await this.session.link(this.authFlow);return{user:await this.getAuthenticatedUser(),oAuthTokens:t}}storeProviderAccessToken(t,r){this.session.storeProviderAccessToken(t,r)}getProviderAccessToken(t){return this.session.getProviderAccessToken(t)}async logout(){await this.session.destroy(),this.authFlow=void 0}clearProviderAcccessTokens(t){t.linkedAccounts.filter(o=>o.type==="cross_app").forEach(o=>{this.storeProviderAccessToken(o.providerApp.id,null)})}startAuthFlow(t){return t.api=this.api,this.authFlow=t,this.authFlow}async initMfaSmsVerification(){try{await this.api.post(cm,{action:"verify"})}catch(t){throw le(t)}}async initMfaPasskeyVerification(){try{let t=await this.api.post(dm,{});return ah(t.options)}catch(t){throw le(t)}}async acceptTerms(){try{let t=await this.api.post(pm,{});return $t(t)}catch(t){throw rt(t)}}async unlinkEmail(t){try{let r=await this.api.post(Vu,{address:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkPhone(t){try{let r=await this.api.post(Ku,{phoneNumber:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkWallet(t){try{let r=await this.api.post(Ou,{address:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkOAuth(t,r){try{let o=await this.api.post(Qu,{provider:t,subject:r});return await this.getAuthenticatedUser()??$t(o)}catch(o){throw rt(o)}}async unlinkFarcaster(t){try{let r=await this.api.post(Fu,{fid:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkTelegram(t){try{let r=await this.api.post(lm,{telegram_user_id:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async unlinkPasskey(t){try{let r=await this.api.post(im,{credential_id:t});return await this.getAuthenticatedUser()??$t(r)}catch(r){throw rt(r)}}async createAnalyticsEvent({eventName:t,payload:r,timestamp:o,options:n}){if(!(typeof window>"u"))try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(Rs,{event_name:t,client_id:this.clientAnalyticsId,payload:{...r||{},clientTimestamp:o?o.toISOString():new Date().toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch{}}async signMoonpayOnRampUrl(t){try{return this.api.post(fm,t)}catch(r){throw rt(r)}}async initCoinbaseOnRamp(t){try{return this.api.post(hm,t)}catch(r){throw rt(r)}}async getCoinbaseOnRampStatus({partnerUserId:t}){try{return this.api.get(`${ym}?partnerUserId=${t}`)}catch(r){throw rt(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()||this.session.hasRecoveryCredentials()?this.session.refresh():null}async getAccessToken(t){return this.session.hasActiveToken()?Ar.parse(this.session.token)?.audience!==this.appId?(await this.logout(),null):this.session.token:!t?.disableAutoRefresh&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getServerConfig(){try{let t={},r=this.session.token;r&&(t.authorization=`Bearer ${r}`);let o=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:t}),n=o.telegram_auth_config?{botId:o.telegram_auth_config.bot_id,botName:o.telegram_auth_config.bot_name,linkEnabled:o.telegram_auth_config.link_enabled,seamlessAuthEnabled:o.telegram_auth_config.seamless_auth_enabled}:void 0,i=o.funding_config?{methods:o.funding_config.methods,defaultRecommendedAmount:o.funding_config.default_recommended_amount,defaultRecommendedCurrency:o.funding_config.default_recommended_currency,promptFundingOnWalletCreation:o.funding_config.prompt_funding_on_wallet_creation}:void 0;return{id:o.id,name:o.name,verificationKey:o.verification_key,logoUrl:o.logo_url||void 0,accentColor:o.accent_color||void 0,showWalletLoginFirst:o.show_wallet_login_first,allowlistConfig:{errorTitle:o.allowlist_config.error_title,errorDetail:o.allowlist_config.error_detail,errorCtaText:o.allowlist_config.cta_text,errorCtaLink:o.allowlist_config.cta_link},walletAuth:o.wallet_auth,emailAuth:o.email_auth,smsAuth:o.sms_auth,googleOAuth:o.google_oauth,twitterOAuth:o.twitter_oauth,discordOAuth:o.discord_oauth,githubOAuth:o.github_oauth,spotifyOAuth:o.spotify_oauth,instagramOAuth:o.instagram_oauth,tiktokOAuth:o.tiktok_oauth,linkedinOAuth:o.linkedin_oauth,appleOAuth:o.apple_oauth,farcasterAuth:o.farcaster_auth,passkeyAuth:o.passkey_auth,telegramAuth:o.telegram_auth,termsAndConditionsUrl:o.terms_and_conditions_url,embeddedWalletConfig:{createOnLogin:o.embedded_wallet_config?.create_on_login,userOwnedRecoveryOptions:o.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:o.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:o.privacy_policy_url,requireUsersAcceptTerms:o.require_users_accept_terms,customApiUrl:o.custom_api_url,walletConnectCloudProjectId:o.wallet_connect_cloud_project_id,fiatOnRampEnabled:o.fiat_on_ramp_enabled,captchaEnabled:o.captcha_enabled,captchaSiteKey:o.captcha_site_key,twitterOAuthOnMobileEnabled:o.twitter_oauth_on_mobile_enabled,createdAt:new Date(o.created_at*1e3),updatedAt:new Date(o.updated_at*1e3),mfaMethods:o.mfa_methods,enforceWalletUis:o.enforce_wallet_uis,legacyWalletUiConfig:o.legacy_wallet_ui_config,telegramAuthConfiguration:n,fundingConfig:i}}catch(t){throw rt(t)}}async getUsdTokenPrice(t){try{return(await this.api.get(`/api/v1/token_price?chainId=${t.id}&tokenSymbol=${t.nativeCurrency.symbol}`)).usd}catch{console.error(`Unable to fetch token price for chain with id ${t.id}`);return}}async requestFarcasterSignerStatus(t){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:t})}catch(r){throw console.error("Unable to fetch Farcaster signer status"),r}}async forkSession(){return await this.session.forkSession()}async generateSiweNonce({address:t,captchaToken:r}){try{return(await this.api.post(Iu,{address:t,token:r})).nonce}catch(o){throw rt(o)}}async authenticateWithSiweInternal({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i}){return await this.api.post(Mu,{message:t,signature:r,chainId:o,walletClientType:n,connectorType:i})}async linkWithSiweInternal({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i}){return await this.api.post(Wu,{message:t,signature:r,chainId:o,walletClientType:n,connectorType:i})}async linkWithSiwe({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i}){try{let a=await this.linkWithSiweInternal({message:t,signature:r,chainId:o,walletClientType:n,connectorType:i});return $t(a)}catch(a){throw rt(a)}}};vl=new WeakSet,ch=function(){if(typeof window>"u")return null;try{let r=j.get(fa);if(typeof r=="string"&&r.length>0)return r}catch{}let t=n0();try{return j.put(fa,t),t}catch{return t}};import{Turnstile as d0}from"@marsidev/react-turnstile";import{useEffect as p0,useMemo as u0}from"react";import{useMemo as i0,useRef as a0,useContext as s0,useState as Fd,createContext as l0}from"react";import{jsx as c0}from"react/jsx-runtime";var dh=l0({siteKey:"",enabled:!1,appId:void 0,token:void 0,error:void 0,status:"disabled",setToken:T,setError:T,setExecuting:T,waitForResult:()=>Promise.resolve(""),ref:{current:null},remove:T,reset:T,execute:T}),ar=class extends tt{constructor(r,o,n){super(r||"Captcha failed");this.type="Captcha";o instanceof Error&&(this.cause=o),this.privyErrorCode=n}},ph=({children:e,id:t,captchaSiteKey:r,captchaEnabled:o})=>{let n=a0(null),[i,a]=Fd(),[l,s]=Fd(),[c,m]=Fd(!1),f=i0(()=>o?!c&&!i&&!l?{status:"ready"}:c&&!i&&!l?{status:"loading"}:i&&!l?{status:"success",token:i}:l?{status:"error",error:l}:{status:"ready"}:{status:"disabled"},[o,i,l,c]);return c0(dh.Provider,{value:{...f,ref:n,enabled:o,siteKey:r,appId:t,setToken:a,setError:s,setExecuting:m,remove(){o&&(n.current?.remove(),m(!1),s(void 0),a(void 0))},reset(){o&&(n.current?.reset(),m(!1),s(void 0),a(void 0))},execute(){o&&(m(!0),n.current?.execute())},async waitForResult(){if(!o)return"";try{return await wm(()=>n.current?.getResponse(),{interval:200,timeout:2e4})}catch{throw new ar("Captcha failed",null,"captcha_timeout")}}},children:e})},Te=()=>s0(dh);import{jsx as uh}from"react/jsx-runtime";var Bd=e=>{let{enabled:t,siteKey:r,appId:o,setError:n,setToken:i,setExecuting:a,ref:l}=Te(),[,s]=u0(()=>r?.split("t:")||[],[r]);if(p0(()=>l.current?.remove,[]),!t)return null;if(!s)throw new Error("Unsupported captcha site key");return uh("div",{className:"hidden h-0 w-0",children:uh(d0,{...e,ref:l,siteKey:s,options:{action:o,size:"invisible",...e.delayedExecution?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{e.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{e.onError?.(),n("Captcha failed"),a(!1)},onSuccess:c=>{e.onSuccess?.(c),i(c),a(!1)},onExpire:()=>{e.onExpire?.();try{l.current?.reset(),n(void 0),i(void 0)}catch{n("expired_and_failed_reset")}}})})};import{useCallback as d_,useEffect as pC,useRef as p_,useState as u_}from"react";import fC from"styled-components";import{createContext as m0,useContext as f0}from"react";var Hd=m0({isNewUserThisSession:!1,linkingOrConnectingHint:null,walletConnectionStatus:null,connectors:[],rpcConfig:{rpcUrls:{}},showFiatPrices:!0,chains:[],clientAnalyticsId:null,pendingTransaction:null,appId:"notAdded",nativeTokenSymbolForChainId:T,initializeWalletProxy:T,getAuthMeta:T,getAuthFlow:T,closePrivyModal:T,openPrivyModal:T,connectWallet:T,initLoginWithWallet:T,loginWithWallet:T,initLoginWithFarcaster:T,loginWithFarcaster:T,loginWithCode:T,initLoginWithEmail:T,initLoginWithSms:T,initUpdateEmail:T,initUpdatePhone:T,resendEmailCode:T,resendSmsCode:T,initLoginWithHeadlessOAuth:T,loginWithHeadlessOAuth:T,crossAppAuthFlow:T,initLoginWithOAuth:T,recoveryOAuthFlow:T,loginWithOAuth:T,initLoginWithPasskey:T,loginWithPasskey:T,initLinkWithPasskey:T,linkWithPasskey:T,refreshUser:T,loginWithGuestAccountFlow:T,walletProxy:null,createAnalyticsEvent:T,acceptTerms:T,getUsdTokenPrice:T,recoverEmbeddedEthereumWallet:T,getMoonpaySignedUrl:T,initCoinbaseOnRamp:T,getCoinbaseOnRampStatus:T,updateWallets:T,fundWallet:T,setReadyToTrue:T,requestFarcasterSignerStatus:T,initLoginWithTelegram:T,loginWithTelegram:T,generateSiweMessage:T,linkWithSiwe:T,embeddedSolanaWallet:null,createEmbeddedSolanaWallet:T,recoverEmbeddedSolanaWallet:T,solanaSignMessage:T,connectCoinbaseSmartWallet:T}),I=()=>f0(Hd);import{createContext as h0,useContext as y0}from"react";var we=h0({ready:!1,authenticated:!1,user:null,walletConnectors:null,connectWallet:T,login:T,connectOrCreateWallet:T,linkEmail:T,linkPhone:T,linkFarcaster:T,linkWallet:T,linkCrossAppAccount:T,linkGoogle:T,linkTwitter:T,linkDiscord:T,linkGithub:T,linkSpotify:T,linkInstagram:T,linkTelegram:T,linkTiktok:T,linkLinkedIn:T,linkApple:T,linkPasskey:T,updateEmail:T,updatePhone:T,logout:T,getAccessToken:T,getEthereumProvider:T,getEthersProvider:T,getWeb3jsProvider:T,unlinkEmail:T,unlinkPhone:T,unlinkWallet:T,unlinkGoogle:T,unlinkTwitter:T,unlinkDiscord:T,unlinkGithub:T,unlinkSpotify:T,unlinkInstagram:T,unlinkTiktok:T,unlinkLinkedIn:T,unlinkApple:T,unlinkCrossAppAccount:T,unlinkFarcaster:T,unlinkTelegram:T,unlinkPasskey:T,setActiveWallet:T,forkSession:T,createWallet:T,importWallet:T,signMessage:T,signTypedData:T,enrollInMfa:T,initEnrollmentWithSms:T,initEnrollmentWithTotp:T,initEnrollmentWithPasskey:T,promptMfa:T,init:T,submitEnrollmentWithSms:T,submitEnrollmentWithTotp:T,submitEnrollmentWithPasskey:T,unenroll:T,submit:T,cancel:T,sendTransaction:T,exportWallet:T,setWalletPassword:T,setWalletRecovery:T,requestFarcasterSignerFromWarpcast:T,getFarcasterSignerPublicKey:T,signFarcasterMessage:T,createGuestAccount:T,initLoginWithEmail:T,initLoginWithSms:T,otpState:{status:"initial"},loginWithCode:T,fundWallet:T,initLoginWithHeadlessOAuth:T,loginWithHeadlessOAuth:T,generateSiweMessage:T,linkWithSiwe:T,signMessageWithCrossAppWallet:T,signTypedDataWithCrossAppWallet:T,sendTransactionWithCrossAppWallet:T,isHeadlessOAuthLoading:!1,isModalOpen:!1,mfaMethods:[]}),q=()=>y0(we);import{useEffect as g0,useState as v0}from"react";var mh=e=>{let[t,r]=v0("auto");return g0(()=>{let o=new ResizeObserver(n=>{r(n[0]?.contentRect.height??"auto")});return e.current&&o.observe(e.current),()=>{e.current&&o.unobserve(e.current)}},[e.current]),t};import{createContext as C0,useContext as w0,useEffect as b0}from"react";var fh={login:{onComplete:[],onError:[],onOAuthLoginComplete:[]},logout:{onSuccess:[]},connectWallet:{onSuccess:[],onError:[]},createWallet:{onSuccess:[],onError:[]},linkAccount:{onSuccess:[],onError:[]},configureMfa:{onMfaRequired:[]},setWalletPassword:{onSuccess:[],onError:[]},setWalletRecovery:{onSuccess:[],onError:[]},signMessage:{onSuccess:[],onError:[]},signTypedData:{onSuccess:[],onError:[]},sendTransaction:{onSuccess:[],onError:[]},accessToken:{onAccessTokenGranted:[],onAccessTokenRemoved:[]},oAuthAuthorization:{onOAuthTokenGrant:[]},fundWallet:{onUserExited:[]}},Gd=C0(void 0),hh=()=>w0(Gd);function Pe(e,t){if(!t)return;let o=hh().current[e];return b0(()=>{for(let[n,i]of Object.entries(t))o.hasOwnProperty(n)||console.warn(`Invalid event type "${n}" for action "${e}"`),o[n]?.push(i);return()=>{for(let[n,i]of Object.entries(t))o.hasOwnProperty(n)||console.warn(`Invalid event type "${n}" for action "${e}"`),o[n]=o[n]?.filter(a=>a!==i)}},[t])}function F(e,t,r,...o){for(let n of e.current[t][r])n(...o)}function Ti(){let e=hh();return(t,r,...o)=>F(e,t,r,...o)}function Vd(e){Pe("configureMfa",e)}import V0 from"@heroicons/react/24/outline/QuestionMarkCircleIcon";import Eh from"styled-components";import Mn,{css as yh}from"styled-components";import zd from"styled-components";import{Fragment as T0,jsx as qd,jsxs as S0}from"react/jsx-runtime";var it=({success:e,fail:t})=>S0(T0,{children:[qd(at,{className:e?"success":t?"fail":""}),qd(Pa,{className:e?"success":t?"fail":""})]}),at=zd.span`
13
13
  && {
14
14
  width: 82px;
15
15
  height: 82px;
@@ -973,7 +973,7 @@ Resources:
973
973
  }
974
974
  `,Gw=dy(tr)`
975
975
  margin-left: auto;
976
- `;import{Fragment as Yw,jsx as Oi,jsxs as jw}from"react/jsx-runtime";var qw=["coinbase_wallet"],zw=["metamask","okx_wallet","rainbow","uniswap","zerion","rabby_wallet","cryptocom"],$w=["safe"],Kw=["phantom"],Li=({connectOnly:e})=>{let{connectors:t}=I(),{app:r}=P(),o=$o(r.appearance.walletList,t,e,r.appearance.walletList,r.externalWallets.walletConnect.enabled);return jw(Yw,{children:[...o]})},$o=(e,t,r,o,n)=>{let i=[],a=[],l=[],s=t.find(c=>c.connectorType==="wallet_connect_v2");for(let c of e)if(c==="detected_wallets"){let m=t.filter(({connectorType:f,walletClientType:u})=>u==="uniswap_wallet_extension"?!o.includes("uniswap"):u==="crypto.com_wallet_extension"?!o.includes("cryptocom"):f==="injected"&&!o.includes(u));for(let f of m){let{walletClientType:u,walletBranding:C}=f;(u==="unknown"?a:i).push(Oi(Bn,{connectOnly:r,provider:u,logo:C.icon,displayName:C.name,connector:f},`${c}-${u}`))}}else if(Kw.includes(c)){let m=t.find(f=>f.connectorType==="injected"&&f.walletClientType===c||f.connectorType===c);m&&i.push(Oi(Bn,{connectOnly:r,provider:c,connector:m},c))}else if(zw.includes(c)){let m=t.find(f=>c==="uniswap"?f.walletClientType==="uniswap_wallet_extension":c==="cryptocom"?f.walletClientType==="crypto.com_wallet_extension":f.connectorType==="injected"&&f.walletClientType===c);n&&!m&&(m=s),m&&i.push(Oi(Bn,{connectOnly:r,provider:c,connector:m},c))}else if(qw.includes(c)){let m=t.find(({connectorType:f})=>f===c);m&&i.push(Oi(Bn,{connectOnly:r,provider:c,connector:m},c))}else $w.includes(c)?s&&l.push(Oi(Bn,{connectOnly:r,provider:c,connector:s},c)):c==="wallet_connect"&&s&&l.push(Oi(Bn,{connectOnly:r,provider:c,connector:s},c));return[...a,...i,...l]};import{Fragment as Zw,jsx as Oa,jsxs as Qw}from"react/jsx-runtime";var py=()=>{let{app:e}=P(),{linkingOrConnectingHint:t}=I(),r=t?`Connect the wallet with address ${pt(t)} ${e?.name?`to ${e.name}.`:"."}`:`Connect a wallet to ${e?.name}`;return Qw(Zw,{children:[Oa(A,{},"header"),Oa(so,{title:"Connect your wallet",description:r}),Oa(Zt,{children:Oa(Li,{connectOnly:!0})}),Oa(z,{})]})};import{Fragment as Jw,jsx as Ni,jsxs as Xw}from"react/jsx-runtime";var uy=()=>{let{app:e}=P(),{linkingOrConnectingHint:t}=I(),r=t?`Connect the wallet with address ${pt(t)} ${e?.name?`to ${e.name}.`:"."}`:`Connect a wallet to ${e?.name}`;return Xw(Jw,{children:[Ni(A,{},"header"),Ni(Un,{title:"Connect your wallet",description:r}),Ni(Zt,{children:Ni(Li,{connectOnly:!0})}),e&&Ni(Ai,{app:e,alwaysShowImplicitConsent:!0}),Ni(z,{})]})};import{useEffect as vy,useState as Cy}from"react";import{isMobile as s4}from"react-device-detect";import l4 from"styled-components";import{useEffect as op,useState as Ko}from"react";import{isMobile as Ul}from"react-device-detect";import yy from"styled-components";import{useEffect as my,useRef as e4}from"react";var t4=(e,t)=>{let r=e4(()=>{});my(()=>{r.current=e}),my(()=>{if(t!==null){let o=setInterval(()=>r.current(),t||0);return()=>clearInterval(o)}},[t])},fy=t4;import{useState as r4,useEffect as o4,useCallback as n4}from"react";function hy(){let[e,t]=r4(!1),r=n4(()=>{document.hidden&&t(!0)},[]);return o4(()=>(document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)),[r]),{hasTabbedAway:e,reset:()=>t(!1)}}import{Fragment as ip,jsx as yt,jsxs as Di}from"react/jsx-runtime";var np=2,ap=e=>e?.privyErrorCode==="linked_to_another_user"?eo.ERROR_USER_EXISTS:e instanceof wt&&!e.details.default?e.details:e instanceof fi?eo.ERROR_TIMED_OUT:e instanceof hi?eo.ERROR_USER_REJECTED_CONNECTION:e?.privyErrorCode==="cannot_link_more_of_type"?eo.ERROR_USER_LIMIT_REACHED:eo.ERROR_WALLET_CONNECTION,gy=()=>{let[e,t]=Ko(!1),[r,o]=Ko(!1),[n,i]=Ko(void 0),{authenticated:a,logout:l}=q(),{app:s,navigate:c,navigateBack:m,lastScreen:f,currentScreen:u,setModalData:C}=P(),{getAuthFlow:v,walletConnectionStatus:g,closePrivyModal:b,initLoginWithWallet:E,loginWithWallet:k,updateWallets:_,createAnalyticsEvent:S}=I(),{walletConnectors:R}=q(),[M,D]=Ko(0),{user:H}=q(),[K]=Ko(H?.linkedAccounts.length||0),[Y,O]=Ko(""),[U,W]=Ko(""),[be,ce]=Ko(!1),{hasTabbedAway:X}=hy(),{enabled:ne,token:ee}=Te(),_e=Ul&&g?.connector?.connectorType==="wallet_connect_v2"||Ul&&g?.connector?.connectorType==="coinbase_wallet"||Ul&&g?.connector?.connectorType==="injected"&&g?.connector?.walletClientType==="phantom",xe=g?.status==="connected",je=g?.status==="switching_to_supported_chain";op(()=>{let V=v(),se=V instanceof So?V:void 0;if(xe&&!se&&(ne&&!ee&&!a?(C({captchaModalData:{callback:dt=>E(g.connectedWallet,dt).then(()=>{ce(!0)}),userIntentRequired:!1,onSuccessNavigateTo:"AWAITING_CONNECTION",onErrorNavigateTo:"ERROR_SCREEN"}}),c("CAPTCHA_SCREEN",!1)):E(g.connectedWallet,ee).then(()=>{ce(!0)})),se&&_e&&xe&&!se.preparedMessage){se.buildSiweMessage();return}!se||_e||!xe||r||(async()=>{o(!0),i(void 0);try{g?.connector?.connectorType==="wallet_connect_v2"&&g?.connector?.walletClientType==="metamask"&&await Cd(2500),await ft()}catch(dt){console.warn("Auto-prompted signature failed",dt)}finally{o(!1)}})()},[M,xe,be]),op(()=>{if(H&&e){let se=Re-500;if(s?.legal.requireUsersAcceptTerms&&!H.hasAcceptedTerms){let sa=setTimeout(()=>{c("AFFIRMATIVE_CONSENT_SCREEN")},se);return()=>clearTimeout(sa)}if(Lt(H,s?.embeddedWallets?.createOnLogin)){let sa=setTimeout(()=>{C({createWallet:{onSuccess:()=>{},onFailure:ys=>{console.error(ys),S({eventName:"embedded_wallet_creation_failure_logout",payload:{error:ys,screen:"ConnectionStatusScreen"}}),l()},callAuthOnSuccessOnClose:!0}}),c("EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN")},se);return()=>clearTimeout(sa)}_();let dt=setTimeout(()=>b({shouldCallAuthOnSuccess:!0,isSuccess:!0}),Re);return()=>clearTimeout(dt)}},[H,e]);let Fe=V=>{if(V?.privyErrorCode==="allowlist_rejected"){c("ALLOWLIST_REJECTION_SCREEN");return}else if(V?.privyErrorCode==="max_accounts_reached"){console.error(new Sr(V).toString()),c("USER_LIMIT_REACHED_SCREEN");return}else if(V?.privyErrorCode==="user_does_not_exist"){c("ACCOUNT_NOT_FOUND_SCREEN");return}i(ap(V))};async function ft(){try{await k(),t(!0)}catch(V){Fe(V)}finally{o(!1)}}op(()=>{g?.connectError&&Fe(g?.connectError)},[g]),fy(()=>{let V=Ze==="wallet_connect_v2"&&g?.connector instanceof Fr?g.connector.redirectUri:void 0;V&&O(V);let se=Ze==="wallet_connect_v2"&&g?.connector instanceof Fr?g.connector.fallbackUniversalRedirectUri:void 0;se&&W(se)},g?.connector instanceof Fr&&!Y?500:null);let Ze=g?.connector?.connectorType||"injected",de=g?.connector?.walletClientType||"unknown",Tr=kr[de]?.displayName||g?.connector?.walletBranding.name||"Browser Extension",Lr=kr[de]?.logo||g?.connector?.walletBranding.icon||(V=>yt(gi,{...V})),Qr=Tr==="Browser Extension"?Tr.toLowerCase():Tr,L;e?L=`Successfully connected with ${Qr}`:n?L=n.message:je?L="Switching networks":xe?L=r&&_e?"Signing":"Sign to verify":L=`Waiting for ${Qr}`;let ot="Don\u2019t see your wallet? Check your other browser windows.";if(e){let V=H?.linkedAccounts.length||0;K===V?ot="Wallet was already linked.":ot="You\u2019re good to go!"}else M>=np&&n?ot="Unable to connect wallet":n?ot=n.detail:je?ot="Switch your wallet to the requested network.":xe&&_e?ot="Sign the message in your wallet to verify it belongs to you.":de==="metamask"&&Ul?ot="Click continue to open and connect MetaMask.":de==="metamask"?ot="For the best experience, connect only one wallet at a time.":Ze==="wallet_connect"?ot="Open your mobile wallet app to continue":Ze==="coinbase_wallet"&&(Os()||(Dd(H)?ot="Continue with the Coinbase app. Not the right wallet? Reset your connection below.":ot="Open the Coinbase app on your phone to continue."));let Nr=R?.walletConnectors?.find(V=>V.walletClientType==="coinbase_wallet"),G=de==="coinbase_wallet"&&(Dd(H)||n===eo.ERROR_USER_EXISTS);return Di(ip,{children:[yt(A,{backFn:!f||u===f?void 0:m}),Di(i4,{children:[yt(sp,{walletLogo:Lr,success:e,fail:!!n}),Di(qe,{children:[yt("h3",{children:L}),yt("p",{children:ot}),!xe&&Y&&!X?Di("p",{children:["Still here?"," ",yt("a",{href:Y,target:"_blank",style:{textDecoration:"underline"},children:"Try connecting again"}),U&&Di(ip,{children:[" ","or"," ",yt("a",{href:U,target:"_blank",style:{textDecoration:"underline"},children:"use this different link"})]})]}):null]}),G?yt(B,{onClick:()=>Nr&&Nr?.disconnect(),disabled:e,children:"Use a different wallet"}):n==eo.ERROR_USER_EXISTS&&u!==f?yt(B,{onClick:m,children:"Use a different wallet"}):xe&&!e&&_e?yt(B,{onClick:()=>{o(!0),ft()},disabled:r,children:r?"Signing":"Sign with your wallet"}):!e&&n?.retryable&&M<np?yt(B,{onClick:()=>{D(M+1),i(void 0),xe?(o(!0),ft()):g?.connectRetry()},disabled:!e&&(!n?.retryable||M>=np),children:"Retry"}):!e&&!n?yt(B,{onClick:()=>{},disabled:!0,children:"Connecting"}):null]}),yt(Z,{})]})},i4=yy.div`
976
+ `;import{Fragment as Yw,jsx as Oi,jsxs as jw}from"react/jsx-runtime";var qw=["coinbase_wallet"],zw=["metamask","okx_wallet","rainbow","uniswap","uniswap_extension","zerion","rabby_wallet","cryptocom"],$w=["safe"],Kw=["phantom"],Li=({connectOnly:e})=>{let{connectors:t}=I(),{app:r}=P(),o=$o(r.appearance.walletList,t,e,r.appearance.walletList,r.externalWallets.walletConnect.enabled);return jw(Yw,{children:[...o]})},$o=(e,t,r,o,n)=>{let i=[],a=[],l=[],s=t.find(c=>c.connectorType==="wallet_connect_v2");for(let c of e)if(c==="detected_wallets"){let m=t.filter(({connectorType:f,walletClientType:u})=>u==="uniswap_wallet_extension"||u==="uniswap_extension"?!o.includes("uniswap"):u==="crypto.com_wallet_extension"?!o.includes("cryptocom"):f==="injected"&&!o.includes(u));for(let f of m){let{walletClientType:u,walletBranding:C}=f;(u==="unknown"?a:i).push(Oi(Bn,{connectOnly:r,provider:u,logo:C.icon,displayName:C.name,connector:f},`${c}-${u}`))}}else if(Kw.includes(c)){let m=t.find(f=>f.connectorType==="injected"&&f.walletClientType===c||f.connectorType===c);m&&i.push(Oi(Bn,{connectOnly:r,provider:c,connector:m},c))}else if(zw.includes(c)){let m=t.find(f=>c==="uniswap"?f.walletClientType==="uniswap_wallet_extension"||f.walletClientType==="uniswap_extension":c==="cryptocom"?f.walletClientType==="crypto.com_wallet_extension":f.connectorType==="injected"&&f.walletClientType===c);n&&!m&&(m=s),m&&i.push(Oi(Bn,{connectOnly:r,provider:c,connector:m,logo:m.connectorType==="injected"?m.walletBranding.icon:void 0,displayName:m.connectorType==="injected"?m.walletBranding.name:void 0},c))}else if(qw.includes(c)){let m=t.find(({connectorType:f})=>f===c);m&&i.push(Oi(Bn,{connectOnly:r,provider:c,connector:m},c))}else $w.includes(c)?s&&l.push(Oi(Bn,{connectOnly:r,provider:c,connector:s},c)):c==="wallet_connect"&&s&&l.push(Oi(Bn,{connectOnly:r,provider:c,connector:s},c));return[...a,...i,...l]};import{Fragment as Zw,jsx as Oa,jsxs as Qw}from"react/jsx-runtime";var py=()=>{let{app:e}=P(),{linkingOrConnectingHint:t}=I(),r=t?`Connect the wallet with address ${pt(t)} ${e?.name?`to ${e.name}.`:"."}`:`Connect a wallet to ${e?.name}`;return Qw(Zw,{children:[Oa(A,{},"header"),Oa(so,{title:"Connect your wallet",description:r}),Oa(Zt,{children:Oa(Li,{connectOnly:!0})}),Oa(z,{})]})};import{Fragment as Jw,jsx as Ni,jsxs as Xw}from"react/jsx-runtime";var uy=()=>{let{app:e}=P(),{linkingOrConnectingHint:t}=I(),r=t?`Connect the wallet with address ${pt(t)} ${e?.name?`to ${e.name}.`:"."}`:`Connect a wallet to ${e?.name}`;return Xw(Jw,{children:[Ni(A,{},"header"),Ni(Un,{title:"Connect your wallet",description:r}),Ni(Zt,{children:Ni(Li,{connectOnly:!0})}),e&&Ni(Ai,{app:e,alwaysShowImplicitConsent:!0}),Ni(z,{})]})};import{useEffect as vy,useState as Cy}from"react";import{isMobile as s4}from"react-device-detect";import l4 from"styled-components";import{useEffect as op,useState as Ko}from"react";import{isMobile as Ul}from"react-device-detect";import yy from"styled-components";import{useEffect as my,useRef as e4}from"react";var t4=(e,t)=>{let r=e4(()=>{});my(()=>{r.current=e}),my(()=>{if(t!==null){let o=setInterval(()=>r.current(),t||0);return()=>clearInterval(o)}},[t])},fy=t4;import{useState as r4,useEffect as o4,useCallback as n4}from"react";function hy(){let[e,t]=r4(!1),r=n4(()=>{document.hidden&&t(!0)},[]);return o4(()=>(document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)),[r]),{hasTabbedAway:e,reset:()=>t(!1)}}import{Fragment as ip,jsx as yt,jsxs as Di}from"react/jsx-runtime";var np=2,ap=e=>e?.privyErrorCode==="linked_to_another_user"?eo.ERROR_USER_EXISTS:e instanceof wt&&!e.details.default?e.details:e instanceof fi?eo.ERROR_TIMED_OUT:e instanceof hi?eo.ERROR_USER_REJECTED_CONNECTION:e?.privyErrorCode==="cannot_link_more_of_type"?eo.ERROR_USER_LIMIT_REACHED:eo.ERROR_WALLET_CONNECTION,gy=()=>{let[e,t]=Ko(!1),[r,o]=Ko(!1),[n,i]=Ko(void 0),{authenticated:a,logout:l}=q(),{app:s,navigate:c,navigateBack:m,lastScreen:f,currentScreen:u,setModalData:C}=P(),{getAuthFlow:v,walletConnectionStatus:g,closePrivyModal:b,initLoginWithWallet:E,loginWithWallet:k,updateWallets:_,createAnalyticsEvent:S}=I(),{walletConnectors:R}=q(),[M,D]=Ko(0),{user:H}=q(),[K]=Ko(H?.linkedAccounts.length||0),[Y,O]=Ko(""),[U,W]=Ko(""),[be,ce]=Ko(!1),{hasTabbedAway:X}=hy(),{enabled:ne,token:ee}=Te(),_e=Ul&&g?.connector?.connectorType==="wallet_connect_v2"||Ul&&g?.connector?.connectorType==="coinbase_wallet"||Ul&&g?.connector?.connectorType==="injected"&&g?.connector?.walletClientType==="phantom",xe=g?.status==="connected",je=g?.status==="switching_to_supported_chain";op(()=>{let V=v(),se=V instanceof So?V:void 0;if(xe&&!se&&(ne&&!ee&&!a?(C({captchaModalData:{callback:dt=>E(g.connectedWallet,dt).then(()=>{ce(!0)}),userIntentRequired:!1,onSuccessNavigateTo:"AWAITING_CONNECTION",onErrorNavigateTo:"ERROR_SCREEN"}}),c("CAPTCHA_SCREEN",!1)):E(g.connectedWallet,ee).then(()=>{ce(!0)})),se&&_e&&xe&&!se.preparedMessage){se.buildSiweMessage();return}!se||_e||!xe||r||(async()=>{o(!0),i(void 0);try{g?.connector?.connectorType==="wallet_connect_v2"&&g?.connector?.walletClientType==="metamask"&&await Cd(2500),await ft()}catch(dt){console.warn("Auto-prompted signature failed",dt)}finally{o(!1)}})()},[M,xe,be]),op(()=>{if(H&&e){let se=Re-500;if(s?.legal.requireUsersAcceptTerms&&!H.hasAcceptedTerms){let sa=setTimeout(()=>{c("AFFIRMATIVE_CONSENT_SCREEN")},se);return()=>clearTimeout(sa)}if(Lt(H,s?.embeddedWallets?.createOnLogin)){let sa=setTimeout(()=>{C({createWallet:{onSuccess:()=>{},onFailure:ys=>{console.error(ys),S({eventName:"embedded_wallet_creation_failure_logout",payload:{error:ys,screen:"ConnectionStatusScreen"}}),l()},callAuthOnSuccessOnClose:!0}}),c("EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN")},se);return()=>clearTimeout(sa)}_();let dt=setTimeout(()=>b({shouldCallAuthOnSuccess:!0,isSuccess:!0}),Re);return()=>clearTimeout(dt)}},[H,e]);let Fe=V=>{if(V?.privyErrorCode==="allowlist_rejected"){c("ALLOWLIST_REJECTION_SCREEN");return}else if(V?.privyErrorCode==="max_accounts_reached"){console.error(new Sr(V).toString()),c("USER_LIMIT_REACHED_SCREEN");return}else if(V?.privyErrorCode==="user_does_not_exist"){c("ACCOUNT_NOT_FOUND_SCREEN");return}i(ap(V))};async function ft(){try{await k(),t(!0)}catch(V){Fe(V)}finally{o(!1)}}op(()=>{g?.connectError&&Fe(g?.connectError)},[g]),fy(()=>{let V=Ze==="wallet_connect_v2"&&g?.connector instanceof Fr?g.connector.redirectUri:void 0;V&&O(V);let se=Ze==="wallet_connect_v2"&&g?.connector instanceof Fr?g.connector.fallbackUniversalRedirectUri:void 0;se&&W(se)},g?.connector instanceof Fr&&!Y?500:null);let Ze=g?.connector?.connectorType||"injected",de=g?.connector?.walletClientType||"unknown",Tr=kr[de]?.displayName||g?.connector?.walletBranding.name||"Browser Extension",Lr=kr[de]?.logo||g?.connector?.walletBranding.icon||(V=>yt(gi,{...V})),Qr=Tr==="Browser Extension"?Tr.toLowerCase():Tr,L;e?L=`Successfully connected with ${Qr}`:n?L=n.message:je?L="Switching networks":xe?L=r&&_e?"Signing":"Sign to verify":L=`Waiting for ${Qr}`;let ot="Don\u2019t see your wallet? Check your other browser windows.";if(e){let V=H?.linkedAccounts.length||0;K===V?ot="Wallet was already linked.":ot="You\u2019re good to go!"}else M>=np&&n?ot="Unable to connect wallet":n?ot=n.detail:je?ot="Switch your wallet to the requested network.":xe&&_e?ot="Sign the message in your wallet to verify it belongs to you.":de==="metamask"&&Ul?ot="Click continue to open and connect MetaMask.":de==="metamask"?ot="For the best experience, connect only one wallet at a time.":Ze==="wallet_connect"?ot="Open your mobile wallet app to continue":Ze==="coinbase_wallet"&&(Os()||(Dd(H)?ot="Continue with the Coinbase app. Not the right wallet? Reset your connection below.":ot="Open the Coinbase app on your phone to continue."));let Nr=R?.walletConnectors?.find(V=>V.walletClientType==="coinbase_wallet"),G=de==="coinbase_wallet"&&(Dd(H)||n===eo.ERROR_USER_EXISTS);return Di(ip,{children:[yt(A,{backFn:!f||u===f?void 0:m}),Di(i4,{children:[yt(sp,{walletLogo:Lr,success:e,fail:!!n}),Di(qe,{children:[yt("h3",{children:L}),yt("p",{children:ot}),!xe&&Y&&!X?Di("p",{children:["Still here?"," ",yt("a",{href:Y,target:"_blank",style:{textDecoration:"underline"},children:"Try connecting again"}),U&&Di(ip,{children:[" ","or"," ",yt("a",{href:U,target:"_blank",style:{textDecoration:"underline"},children:"use this different link"})]})]}):null]}),G?yt(B,{onClick:()=>Nr&&Nr?.disconnect(),disabled:e,children:"Use a different wallet"}):n==eo.ERROR_USER_EXISTS&&u!==f?yt(B,{onClick:m,children:"Use a different wallet"}):xe&&!e&&_e?yt(B,{onClick:()=>{o(!0),ft()},disabled:r,children:r?"Signing":"Sign with your wallet"}):!e&&n?.retryable&&M<np?yt(B,{onClick:()=>{D(M+1),i(void 0),xe?(o(!0),ft()):g?.connectRetry()},disabled:!e&&(!n?.retryable||M>=np),children:"Retry"}):!e&&!n?yt(B,{onClick:()=>{},disabled:!0,children:"Connecting"}):null]}),yt(Z,{})]})},i4=yy.div`
977
977
  display: flex;
978
978
  flex-direction: column;
979
979
  align-items: center;
@@ -3319,4 +3319,4 @@ You will have to sign up with another method first to register a passkey for you
3319
3319
  box-shadow: 0px 8px 36px rgba(55, 65, 81, 0.15);
3320
3320
  border-radius: var(--privy-border-radius-lg);
3321
3321
  }
3322
- `;import{useRef as gC,useEffect as v_}from"react";import{jsx as w_}from"react/jsx-runtime";function C_({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:o}=new URL(t);return r.async=!0,r.src=`${o}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}function vC(e){let t=gC(null),r=gC();return v_(()=>{r.current?.remove(),r.current=C_(e),t.current?.after(r.current)},[e]),w_("div",{ref:t,hidden:!0})}import{useState as b_}from"react";import{useEffect as CC,useRef as wC}from"react";var ud=class{constructor(){this.callbacks={}}enqueue(t,r){this.callbacks[t]=r}dequeue(t,r){let o=this.callbacks[r];if(!o)throw new Error(`cannot dequeue ${t} event: no event found for id ${r}`);switch(delete this.callbacks[r],t){case"privy:iframe:ready":return o;case"privy:wallet:create":return o;case"privy:wallet:import":return o;case"privy:wallet:connect":return o;case"privy:wallet:recover":return o;case"privy:wallet:rpc":return o;case"privy:wallet:set-recovery":return o;case"privy:mfa:verify":return o;case"privy:mfa:init-enrollment":return o;case"privy:mfa:submit-enrollment":return o;case"privy:mfa:unenroll":return o;case"privy:mfa:clear":return o;case"privy:farcaster:init-signer":return o;case"privy:farcaster:sign":return o;case"privy:solana-wallet:create":return o;case"privy:solana-wallet:connect":return o;case"privy:solana-wallet:recover":return o;case"privy:solana-wallet:rpc":return o;default:throw new Error(`invalid wallet event type ${t}`)}}};async function Cn(e,t,r,o,n,i=!1){let a=i,l=async m=>{if(a&&t&&t.length>0){m===(i?0:1)?n("configureMfa","onMfaRequired",t):o.current?.reject(new We("missing_or_invalid_mfa","MFA verification failed, retry."));let f=await new Promise((u,C)=>{r.current={resolve:u,reject:C};let v=1e3*60*5;setTimeout(()=>{let g=new We("mfa_timeout","Timed out waiting for MFA code");o.current?.reject(g),C(g)},v)});return await e(f)}return await e()},s=4,c=null;for(let m=0;m<s;m++)try{c=await l(m),o.current?.resolve(void 0);break}catch(f){if(f.type==="missing_or_invalid_mfa")a=!0;else throw o.current?.resolve(void 0),f}if(c===null){let m=new We("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw o.current?.reject(m),m}return c}import{jsx as A_}from"react/jsx-runtime";var E_=function(e){return()=>`id-${e++}`}(0);function T_(e){return typeof e.event=="string"&&/^privy:.+/.test(e.event)}function vt(e){return e.error!==void 0}var mt=new ud,gu=new Map,S_=(e,t)=>typeof t=="bigint"?t.toString():t,__=(e,t)=>`${e}${JSON.stringify(t,S_)}`;function Ct(e,t,r,o){let n=r.contentWindow;if(!n)throw new Error("iframe not initialized");let i=__(e,t);if(e==="privy:wallet:create"){let l=gu.get(i);if(l)return l}let a=new Promise((l,s)=>{let c=E_();mt.enqueue(c,{resolve:l,reject:s}),n.postMessage({id:c,event:e,data:t},o)}).finally(()=>{gu.delete(i)});return gu.set(i,a),a}function P_(e){switch(e.event){case"privy:iframe:ready":let t=mt.dequeue(e.event,e.id);return vt(e)?t.reject(new We(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":let r=mt.dequeue(e.event,e.id);return vt(e)?r.reject(new We(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:import":let o=mt.dequeue(e.event,e.id);return vt(e)?o.reject(new We(e.error.type,e.error.message)):o.resolve(e.data);case"privy:wallet:connect":let n=mt.dequeue(e.event,e.id);return vt(e)?n.reject(new We(e.error.type,e.error.message)):n.resolve(e.data);case"privy:wallet:recover":let i=mt.dequeue(e.event,e.id);return vt(e)?i.reject(new We(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:rpc":let a=mt.dequeue(e.event,e.id);return vt(e)?a.reject(new We(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:set-recovery":let l=mt.dequeue(e.event,e.id);return vt(e)?l.reject(new We(e.error.type,e.error.message)):l.resolve(e.data);case"privy:mfa:verify":let s=mt.dequeue(e.event,e.id);return vt(e)?s.reject(new We(e.error.type,e.error.message)):s.resolve(e.data);case"privy:mfa:init-enrollment":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:mfa:submit-enrollment":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:mfa:unenroll":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:mfa:clear":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:farcaster:init-signer":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:farcaster:sign":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:solana-wallet:create":let c=mt.dequeue(e.event,e.id);return vt(e)?c.reject(new We(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:connect":let m=mt.dequeue(e.event,e.id);return vt(e)?m.reject(new We(e.error.type,e.error.message)):m.resolve(e.data);case"privy:solana-wallet:recover":let f=mt.dequeue(e.event,e.id);return vt(e)?f.reject(new We(e.error.type,e.error.message)):f.resolve(e.data);case"privy:solana-wallet:rpc":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}function bC(e){let t=wC(null),r=wC(e.mfaMethods),o=Ti(),[n,i]=b_(!1);return CC(()=>{r.current=e.mfaMethods},[e.mfaMethods]),CC(()=>{if(!n)return;let a=t.current;if(!a)return;function l(u){u&&u.origin===e.origin&&T_(u.data)&&P_(u.data)}let s={create(u){return Ct("privy:wallet:create",u,a,e.origin)},import(u){return Ct("privy:wallet:import",u,a,e.origin)},connect(u){return Ct("privy:wallet:connect",u,a,e.origin)},recover(u){return Cn(C=>Ct("privy:wallet:recover",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o,!u.recoveryMethod||u.recoveryMethod==="privy")},rpc(u){return Cn(C=>Ct("privy:wallet:rpc",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},createSolana(u){return Ct("privy:solana-wallet:create",u,a,e.origin)},connectSolana(u){return Ct("privy:solana-wallet:connect",u,a,e.origin)},recoverSolana(u){return Ct("privy:solana-wallet:recover",u,a,e.origin)},rpcSolana(u){return Ct("privy:solana-wallet:rpc",u,a,e.origin)},setRecovery(u){return Cn(C=>Ct("privy:wallet:set-recovery",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},verifyMfa(u){return Cn(C=>Ct("privy:mfa:verify",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o,!0)},initEnrollMfa(u){return Cn(C=>Ct("privy:mfa:init-enrollment",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},submitEnrollMfa(u){return Cn(C=>Ct("privy:mfa:submit-enrollment",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},unenrollMfa(u){return Cn(C=>Ct("privy:mfa:unenroll",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o,!0)},clearMfa(u){return Ct("privy:mfa:clear",u,a,e.origin)},initFarcasterSigner(u){return Ct("privy:farcaster:init-signer",u,a,e.origin)},signFarcasterMessage(u){return Ct("privy:farcaster:sign",u,a,e.origin)}};window.addEventListener("message",l);let c=()=>e.onLoad(s),m=(...u)=>{console.warn("Privy iframe failed to load: ",...u),e.onLoadFailed()},f=new AbortController;return da(()=>Ct("privy:iframe:ready",{},a,e.origin),{abortSignal:f.signal}).then(c,m),()=>{window.removeEventListener("message",l),f.abort()}},[n]),A_("iframe",{ref:t,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>i(!0),src:Ns(e.origin,`/apps/${e.appId}/embedded-wallets`,{caid:e.clientAnalyticsId,client_id:e.appClientId})})}var md=class{constructor(t,r){this.walletProxy=t,this.address=r}async handleSignMessage(t){if(!t.params||typeof t.params.message!="string")throw new Error("Message must be provided as a string for Solana signMessage RPC");return await TC({message:t.params.message})}async request(t){if(console.debug("EmbeddedSolanaProvider.request() called with args",t),!await Ee())throw new Error("User must be authenticated to use embedded Solana wallet");if(!await EC())throw new w("Unable to connect to Solana embedded wallet");switch(t.method){case"signMessage":return await this.handleSignMessage(t);default:throw new Error("Embedded Solana provider does not yet support this RPC method.")}}};async function SC({url:e,popup:t}){return t.location=e,new Promise((o,n)=>{let a=setTimeout(()=>{n(new w("Authorization request timed out after 2 minutes.")),l()},12e4);function l(){t?.close(),window.removeEventListener("message",m)}let s,c=setInterval(()=>{t?.closed&&!s&&(l(),clearInterval(c),clearTimeout(a),n(new w("User rejected request")))},300);function m(f){f.data&&(f.data.type==="PRIVY_OAUTH_RESPONSE"&&f.data.stateCode&&f.data.authorizationCode&&(clearTimeout(a),o(f.data),l()),f.data.type==="PRIVY_OAUTH_ERROR"&&(clearTimeout(a),n(new w(f.data.error)),l()),f.data.type==="PRIVY_OAUTH_USE_BROADCAST_CHANNEL"&&(s=new BroadcastChannel("popup-privy-oauth"),s.onmessage=m))}window.addEventListener("message",m)})}var x_="https://cdn.apple-cloudkit.com";async function vu({url:e,popup:t,provider:r}){return t.location=e,new Promise((n,i)=>{function a(){t?.close(),window.removeEventListener("message",l)}function l(s){s.data&&(s.data.type==="PRIVY_OAUTH_RESPONSE"&&s.data.stateCode&&s.data.authorizationCode&&(n(s.data),a()),s.origin===x_&&s.data.ckSession&&(n({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:s.data.ckSession}),a()),s.data.type==="PRIVY_OAUTH_ERROR"&&(i(s.data.error),a()))}window.addEventListener("message",l)})}var _C=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});import{jsx as Er,jsxs as PC}from"react/jsx-runtime";var bo;function L_(e){return typeof e=="string"&&e.length===25}function Ee(){if(!bo){let e=j.get(bn);return Promise.resolve(e||null)}return bo.getAccessToken()}var AC,nf=(e,t,r)=>AC(e,t,r),xC,af=(e,t)=>xC(e,t),kC,sf=(e,t)=>kC(e,t),RC,lf=()=>RC(),IC,EC=()=>IC(),MC,TC=({message:e})=>MC({message:e}),N_=()=>{let t=new URLSearchParams(window.location.search).get("privy_token");if(!t)return;j.put(ma,t);let r=new URL(window.location.href);r.searchParams.delete("privy_token"),window.history.pushState({},"",r)},D_=({config:e,...t})=>{if(typeof window<"u"&&["localhost","127.0.0.1"].indexOf(window.location.hostname)<0&&window.location.protocol!=="https:")throw new w("Embedded wallet is only available over HTTPS");if(!L_(t.appId))throw new w("Cannot initialize the Privy provider with an invalid Privy app ID");bo||(bo=new _a({appId:t.appId,appClientId:t.clientId,apiUrl:t.apiUrl}));let r=Object.assign({},e);return t.createPrivyWalletOnLogin!==void 0&&r.embeddedWallets?.createOnLogin===void 0&&(r.embeddedWallets||(r.embeddedWallets={}),r.embeddedWallets.createOnLogin=t.createPrivyWalletOnLogin?"users-without-wallets":"off"),t.createPrivyWalletOnLogin!==void 0&&e?.embeddedWallets?.createOnLogin&&console.warn("Both `createPrivyWalletOnLogin` and `config.embeddedWallets.createOnLogin` are set. `createPrivyWalletOnLogin` is deprecated and should be removed."),Er(rh,{client:bo,clientConfig:r,legacyCreateEmbeddedWalletFlag:t.createPrivyWalletOnLogin,children:Er(U_,{...t,client:bo})})},U_=e=>{let t=e.client,[r,o]=ct(!1),[n,i]=ct(!1),[a,l]=ct(!1),[s,c]=ct(null),[m,f]=ct([]),[u,C]=ct(null),v=aa(m),[g,b]=ct(!1),[E,k]=ct(null),[_,S]=ct(!1),[R,M]=ct({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:T}),[D,H]=ct({status:"initial"}),[K,Y]=ct(null),[O,U]=ct(null),W=Ne(),be=hl(),[ce,X]=ct(!0),[ne,ee]=ct({}),[_e,xe]=ct(null),[je,Fe]=ct(null),[ft,Ze]=ct(!1),[de,Tr]=ct(!1),Lr=aa(null),Qr=aa(null),L=aa(fh),[ot,Nr]=ct(!1);t.onStoreToken=d=>{d&&F(L,"accessToken","onAccessTokenGranted",d)},t.onDeleteToken=()=>{c(null),l(!1),F(L,"accessToken","onAccessTokenRemoved")};let G=aa(null),V=aa(null),se=d=>{k(d),setTimeout(()=>{o(!0)},15),t.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:d}})},dt=d=>{W.embeddedWallets.createOnLogin!=="off"&&X(!0),se(d)};Zr(()=>{let d=kn(s);if(!d||!O)return;let p={address:d.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",meta:{name:"Privy Wallet",icon:Bo,id:"io.privy.solana.wallet"},getProvider:async()=>new md(O,d.address)};C(p)},[O,s]),Zr(()=>{if(!s){t.connectors?.removeEmbeddedWalletConnector();return}let d=ye(s),p=sl(s);if(d||t.connectors?.removeEmbeddedWalletConnector(),p||t.connectors?.removeImportedWalletConnector(),!t.connectors){console.debug("Failed to add embedded wallet connector: Client connectors not initialized");return}if(!O){console.debug("Failed to add embedded wallet connector: Wallet proxy not initialized");return}d&&t.connectors.addEmbeddedWalletConnector(O,d.address,W.defaultChain,e.appId),p&&t.connectors.addImportedWalletConnector(O,p.address,W.defaultChain,e.appId)},[O,s]),Zr(()=>{O&&je?.(O)},[O]),Zr(()=>{(async()=>{if(!W.customAuth?.enabled)return;X(!0);let{getCustomAccessToken:p,isLoading:h}=W.customAuth;if(!(!n||h))try{let y=await p();if(!y&&a){await ii.logout();return}if(!y||a)return;t.startAuthFlow(new si(y));let{user:x,isNewUser:N}=await t.authenticate();if(!x){await ii.logout();return}c(x||null),b(N||!1),l(!0),Tr(!0)}catch(y){console.warn(y),a&&await ii.logout()}})()},[W.customAuth?.enabled,W.customAuth?.getCustomAccessToken,W.customAuth?.isLoading,n,a]),Zr(()=>{de&&O&&s&&Lt(s,W.embeddedWallets.createOnLogin)&&(Tr(!1),fd(s,ci).catch(console.error))},[de&&O&&s]),Zr(()=>{async function d(){let p=sa(),h=ys();N_();let y=k_();t.initializeConnectorManager({walletConnectCloudProjectId:W.walletConnectCloudProjectId,rpcConfig:W.rpcConfig,chains:W.chains,defaultChain:W.defaultChain,store:y,walletList:W.appearance.walletList,shouldEnforceDefaultChainOnConnect:W.shouldEnforceDefaultChainOnConnect,externalWalletConfig:W.externalWallets,appName:W.name??"Privy"});let x;t.connectors?.on("connectorInitialized",()=>{x&&clearTimeout(x);let te=t.connectors.walletConnectors.length,oe=t.connectors.walletConnectors.reduce((Ve,Be)=>Ve+(Be.initialized?1:0),0);oe===te?Nr(!0):x=setTimeout(()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:oe,expected:te}),Nr(!0)},1500)}),t.connectors?.initialize().then(()=>{UC()});let N=await t.getAuthenticatedUser(),$=!!N;if(W.customAuth?.enabled||(l(!!N),N&&F(L,"login","onComplete",N,!1,!0,null,null),c(N)),p){V.current=$?"link":"login";return}if(h&&!$){V.current="login",dt("TELEGRAM_AUTH_SCREEN");return}re.setReadyToTrue(!!N)}!n&&be&&d()},[t,_e,n,be]),Zr(()=>{if(!n)return;if(!s){Ze(!0);return}if(!!!s.linkedAccounts.find(h=>h.type==="wallet"&&h.walletClientType==="privy")){Ze(!0);return}let p=!!m.find(h=>h.walletClientType==="privy");Ze(p)},[n,s,m]);let sa=()=>{let d=Ca();if(d.inProgress&&d.popupFlow){if(window.opener.location.origin!==window.location.origin){window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Origins between parent and child windows do not match."});return}if(d.authorizationCode==="error"){window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Something went wrong. Try again."});return}window.opener.postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:d.stateCode,authorizationCode:d.authorizationCode});return}let p="privy:";function h(y){return y.startsWith(p)}return d.inProgress&&h(d.provider)&&!d.popupFlow&&(new BroadcastChannel("popup-privy-oauth").postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:d.stateCode,authorizationCode:d.authorizationCode}),window.close()),!d.inProgress||d.headless?!1:(t.startAuthFlow(new Xr(d)),dt("AWAITING_OAUTH_SCREEN"),!0)},ys=()=>{let d=tf();if(!d||!W.loginMethods.telegram||!W.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let p=new mi;return t.startAuthFlow(p),d.flowType==="login-url"&&(p.meta.telegramWebAppData=void 0,p.meta.telegramAuthResult={id:d.id,first_name:d.first_name,last_name:d.last_name,auth_date:d.auth_date,username:d.username,photo_url:d.photo_url,hash:d.hash}),d.flowType==="web-app"&&(p.meta.telegramAuthResult=void 0,p.meta.telegramWebAppData={query_id:d.query_id,user:d.user,auth_date:d.auth_date,hash:d.hash}),!0},wu=async(d,p,h,y)=>{let x=await t.connectors?.createWalletConnector(d,p)||null;gs(x,p,h,y)};async function gs(d,p,h,y){if(d)M({status:"disconnected",connectedWallet:null,connectError:null,connector:d,connectRetry:T});else return M({status:"disconnected",connectedWallet:null,connectError:new pe("Unable to connect to wallet."),connector:null,connectRetry:T}),y?.(null,h);d instanceof Fr&&p&&await d.resetConnection(p),M({connector:d,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>gs(d,p,h,y)});try{let x=await d.connect({showPrompt:!0});if(W.shouldEnforceDefaultChainOnConnect&&!W.chains.find(N=>N.id===Number(x?.chainId.replace("eip155:","")))&&!(x?.connectorType==="wallet_connect_v2"&&x?.walletClientType==="metamask")){M(N=>({...N,connector:d,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:T}));try{await x?.switchChain(W.defaultChain.id),x&&(x.chainId=li(wn(W.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${W.defaultChain.id}`)}}return M(N=>({...N,status:"connected",connectedWallet:x,connectError:null,connectRetry:T})),x&&F(L,"connectWallet","onSuccess",x),y?.(x,h)}catch(x){return x instanceof tt?(console.warn(x.cause?x.cause:x.message),F(L,"connectWallet","onError",x.privyErrorCode||"generic_connect_wallet_error")):(console.warn(x),F(L,"connectWallet","onError","unknown_connect_wallet_error")),M(N=>({...N,status:"disconnected",connectedWallet:null,connectError:x})),y?.(null,h)}}let vs=async(d,p)=>{if(d===null)return;let h=new So(d,t,p);t.startAuthFlow(h)},UC=()=>{let d=new URLSearchParams(window.location.search),p=d.get("privy_connector"),h=d.get("privy_wallet_client");if(!p||!h)return;if(h==="phantom"&&!No()&&dt("LOGIN_FAILED_SCREEN"),!t.connectors)throw new w("Connector not initialized");se("AWAITING_CONNECTION");let y=new URL(window.location.href);y.searchParams.delete("privy_connector"),y.searchParams.delete("privy_wallet_client"),window.history.pushState({},"",y),wu(p,h,void 0,vs)};Zr(()=>{n&&a&&s===null&&t.getAuthenticatedUser().then(c)},[n,a,s,t]);let nt=d=>{if(!a)throw F(L,"linkAccount","onError","must_be_authenticated",{linkMethod:d}),new w("User must be authenticated before linking an account.")},bu=()=>{nt("siwe"),G.current="siwe",V.current="link",se("LINK_WALLET_SCREEN")},FC=d=>{if(!a||!s)return!1;if(d.walletClientType==="privy")return!0;for(let p of s.linkedAccounts)if(p.type==="wallet"&&p.address===d.address&&p.walletClientType!=="privy")return!0;return!1},BC=async d=>{if(!t.connectors)throw new w("Connector not initialized");let p=t.connectors.findWalletConnector(d.connectorType,d.walletClientType)||null;if(M(h=>({...h,connector:p,status:"connected",connectedWallet:d,connectError:null,connectRetry:T})),W.captchaEnabled&&!a){let h={callback:y=>vs(d,y),userIntentRequired:!1,onSuccessNavigateTo:"AWAITING_CONNECTION",onErrorNavigateTo:"ERROR_SCREEN"};ee({captchaModalData:h}),dt("CAPTCHA_SCREEN")}else await vs(d),dt("AWAITING_CONNECTION")},HC=async(d,p)=>{let{signedUrl:h,externalTransactionId:y}=await b1(t,d,p??{},W.appearance.palette,W.fundingMethodConfig?.moonpay.useSandbox??!1);return{signedUrl:h,externalTransactionId:y}},Cs=()=>{f(d=>{let p=t.connectors?.wallets.map(h=>({...h,linked:FC(h),loginOrLink:async()=>{if(!await h.isConnected())throw new w("Wallet is not connected");if(h.connectorType==="embedded"&&h.walletClientType==="privy")throw new w("Cannot link or login with embedded wallet");BC(h)},fund:async y=>{await re.fundWallet(h.address,y)},unlink:async()=>{if(!a)throw new w("User is not authenticated.");if(h.connectorType==="embedded"&&h.walletClientType==="privy")throw new w("Cannot unlink an embedded wallet");let y=await t.unlinkWallet(h.address);c(y)}}))||[];return ll(d,p)?d:p})};Zr(()=>{Cs()},[s?.linkedAccounts,a,n]),Zr(()=>{if(n){if(!t.connectors)throw new w("Connector not initialized");Cs(),t.connectors.on("walletsUpdated",Cs)}},[n]);let GC=d=>{if(d&&"suggestedAddress"in d&&d.suggestedAddress){let p=Oo(d.suggestedAddress);Y(p)}se(a?"CONNECT_ONLY_AUTHENTICATED_SCREEN":"CONNECT_ONLY_LANDING_SCREEN")};Zr(()=>{if(!m[0])return;let d=m[0],p=v.current.find(y=>y.address===d.address),h;if(d.walletClientType==="privy"?h=s?.linkedAccounts.find(y=>y.type==="wallet"&&y.address===d.address&&y.walletClientType==="privy"):h=s?.linkedAccounts.find(y=>y.type==="wallet"&&y.address===d.address&&y.walletClientType!=="privy"),!p&&h){let y=Object.assign({},s);y.wallet=h&&{address:h.address,chainType:h.chainType,chainId:h.chainId,walletClient:h.walletClient,walletClientType:h.walletClientType,connectorType:h.connectorType,imported:h.imported},c(y)}v.current=m},[m]);let fd=async(d,p)=>{if(ye(d))throw F(L,"createWallet","onError","embedded_wallet_already_exists"),new Error("Only one Privy wallet per user is currently allowed");let[y,x]=await Promise.all([re.initializeWalletProxy(p),Ee()]);if(!y&&W.customAuth?.enabled)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to connect to wallet proxy");if(!y||!x||W.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return new Promise((N,$)=>{X(!0),ee({createWallet:{onSuccess:oe=>{F(L,"createWallet","onSuccess",oe),N(oe)},onFailure:oe=>{F(L,"createWallet","onError","unknown_embedded_wallet_error"),$(oe)},callAuthOnSuccessOnClose:!1}}),se("EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN")});{await y.create({accessToken:x});let N=await re.refreshUser(),$=ye(N);if(!$)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to create wallet");return F(L,"createWallet","onSuccess",$),$}},VC=d=>{if(!W.chains.map(p=>p.id).includes(d))throw new pe(`Chain ID ${d} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,"unsupported_chain_id")},Eu=(d,p,h)=>new Promise(async(y,x)=>{let{requesterAppId:N}=p||{};if(!a||!s){F(L,"sendTransaction","onError","must_be_authenticated"),x(new Error("User must be authenticated before signing with a Privy wallet"));return}let $=d.from,te=$?s?.linkedAccounts.find(Qe=>Qe.type==="wallet"&&Qe.walletClientType==="privy"&&Oo(Qe.address)===Oo($)):ye(s);if(!te){F(L,"sendTransaction","onError","embedded_wallet_not_found"),x(new Error("Must have a Privy wallet before signing"));return}X(!0);let oe=t.connectors?.findWalletConnector("embedded","privy")?.proxyProvider,Ve=d.chainId?Number(d.chainId):oe.chainId;VC(Ve);let Be=Object.assign({},d,{chainId:Ve}),et=async()=>{let Qe=await Ee();if(!Qe||!O){F(L,"sendTransaction","onError","embedded_wallet_not_found"),x(new Error("Must have valid access token and Privy wallet to send transaction"));return}try{if(!await re.recoverEmbeddedEthereumWallet()){F(L,"sendTransaction","onError","unknown_connect_wallet_error"),x(new Error("Unable to connect to wallet"));return}let ai=qt(Be.chainId,W.chains,W.rpcConfig,{appId:e.appId}),Jr=await O_(te.address,Be,ai);if(W.embeddedWallets.noPromptOnSignature){let{totalGasEstimate:zC}=await W_(Jr,ai),{hasSufficientFunds:$C}=await Yi(te.address,Jr,zC,ai);if(!$C)throw new wt(new Pr("Wallet has insufficient funds for this transaction.",M_.E32603_DEFAULT_INTERNAL_ERROR.eipCode))}let Au=await lc(Qe,te.address,O,Jr,ai,N);F(L,"sendTransaction","onSuccess",Au),y(Au)}catch(bs){F(L,"sendTransaction","onError","transaction_failure"),x(bs)}};if(W.embeddedWallets.noPromptOnSignature)p&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config"),et();else{let Qe={transactionRequest:Be,onSuccess:Jr=>{F(L,"sendTransaction","onSuccess",Jr),y(Jr)},onFailure:Jr=>{F(L,"sendTransaction","onError","transaction_failure"),x(Jr)},uiOptions:p||{},fundWalletConfig:h,requesterAppId:N},bs={onCompleteNavigateTo:"EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN",onFailure:Jr=>{F(L,"sendTransaction","onError","unknown_connect_wallet_error"),x(Jr)}},ai=_u({address:te.address,fundWalletConfig:h,chainIdOverride:Be.chainId,comingFromSendTransactionScreen:!0});ee({connectWallet:bs,sendTransaction:Qe,funding:ai}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}});function Tu(){return new Promise(async(d,p)=>{let h=await Ee();if(!h||!O)throw new Error("Must have valid access token to enroll in MFA");try{await O.verifyMfa({accessToken:h}),d()}catch(y){p(y)}})}let Su=d=>d?.linkedAccounts.filter(p=>p.latestVerifiedAt!==null&&!(p.type==="wallet"&&p.walletClientType==="privy")).sort((p,h)=>h.latestVerifiedAt.getTime()-p.latestVerifiedAt.getTime())[0],Vt=d=>{let p=s?.linkedAccounts.filter(x=>x.type===d).length??0,{displayName:h,loginMethod:y}=sn(d);if(d==="passkey"&&p>=5||d!=="passkey"&&p>=1)throw F(L,"linkAccount","onError","cannot_link_more_of_type",{linkMethod:y}),new w(`User already has an account of type ${h} linked.`)},_u=({address:d,fundWalletConfig:p,methodScreen:h,chainIdOverride:y=null,comingFromSendTransactionScreen:x=!1})=>{if(!W.fundingConfig||W.fundingConfig.methods.length===0)return;let N=_c(p)&&p.amount?p.amount:W.fundingConfig.defaultRecommendedAmount,$=_c(p)&&p.chain?p.chain.id:ji(W.fundingConfig.defaultRecommendedCurrency.chain),te=_c(p)&&p.chain?p.chain:W.chains.find(oe=>oe.id===$);if(y&&W.chains.find(oe=>oe.id===y)&&(te=W.chains.find(oe=>oe.id===y)),!te)throw new w("Funding chain is not in PrivyProvider chains list");return{address:d,amount:N,chain:te,methodScreen:h,comingFromSendTransactionScreen:x,...w1(p)?{moonpayConfigOverride:p.config}:{}}};async function Pu({showAutomaticRecovery:d=!1,legacySetWalletPasswordFlow:p=!1}){k(null);let h=p?"setWalletPassword":"setWalletRecovery";if(!a||!s)throw F(L,h,"onError","must_be_authenticated"),new Error("User must be authenticated before adding recovery method to Privy wallet");let y=ye(s);if(!y||!O)throw F(L,h,"onError","embedded_wallet_not_found"),new Error("Must have a Privy wallet to add a recovery method");if(kn(s))throw new Error("Cannot set user-controlled recovery for user with Solana.");try{await Tu()}catch(N){throw F(L,h,"onError","missing_or_invalid_mfa"),N}return new Promise((N,$)=>{X(!0);let te={onSuccess:et=>{F(L,h,"onSuccess","user-passcode",et),N(et)},onFailure:et=>{F(L,h,"onError","user_exited_set_password_flow"),$(et)},callAuthOnSuccessOnClose:!1},oe=y.recoveryMethod==="user-passcode",Be={onCompleteNavigateTo:Fi({walletAction:"update",availableRecoveryMethods:W.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:p,isResettingPassword:oe,showAutomaticRecovery:d}),shouldForceMFA:!1,onFailure:et=>{F(L,h,"onError","unknown_connect_wallet_error"),$(et)}};ee({setWalletPassword:te,createWallet:te,connectWallet:Be,recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:oe}}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")})}async function ws({appId:d}){nt(`privy:${d}`),G.current=`privy:${d}`,V.current="link";let p=window.open(void 0,void 0,Va({w:440,h:680}));return t.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{appId:d}}),new Promise(async(h,y)=>{let{name:x,logoUrl:N}=await mc({api:t.api,providerAppId:d,requesterAppId:W.id});ee({crossAppAuth:{appId:d,name:x,logoUrl:N,popup:p,onSuccess:h,onError:y}}),dt("CROSS_APP_AUTH_SCREEN")})}let ii={ready:n,authenticated:a,user:s,walletConnectors:t.connectors||null,connectWallet:GC,importWallet:async({privateKey:d})=>{nt("siwe");let[p,h]=await Promise.all([re.initializeWalletProxy(15e3),Ee()]);if(p&&h){await p.import({privateKey:d,accessToken:h});let y=await re.refreshUser(),x=sl(y);if(!x)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to import wallet");return F(L,"createWallet","onSuccess",x),x}else throw new w("User is not authenticated")},linkWallet:bu,linkCrossAppAccount:ws,linkEmail:()=>{nt("email"),Vt("email"),G.current="email",V.current="link",se("LINK_EMAIL_SCREEN")},linkPhone:()=>{nt("sms"),Vt("phone"),G.current="sms",V.current="link",se("LINK_PHONE_SCREEN")},linkGoogle:async()=>{nt("google"),Vt("google_oauth"),V.current="link",await re.initLoginWithOAuth("google")},linkTwitter:async()=>{nt("twitter"),Vt("twitter_oauth"),V.current="link",await re.initLoginWithOAuth("twitter")},linkDiscord:async()=>{nt("discord"),Vt("discord_oauth"),V.current="link",await re.initLoginWithOAuth("discord")},linkGithub:async()=>{nt("github"),Vt("github_oauth"),V.current="link",await re.initLoginWithOAuth("github")},linkSpotify:async()=>{nt("spotify"),Vt("spotify_oauth"),V.current="link",await re.initLoginWithOAuth("spotify")},linkInstagram:async()=>{nt("instagram"),Vt("instagram_oauth"),V.current="link",await re.initLoginWithOAuth("instagram")},linkTiktok:async()=>{nt("tiktok"),Vt("tiktok_oauth"),V.current="link",await re.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{nt("linkedin"),Vt("linkedin_oauth"),V.current="link",await re.initLoginWithOAuth("linkedin")},linkApple:async()=>{nt("apple"),Vt("apple_oauth"),V.current="link",await re.initLoginWithOAuth("apple")},linkPasskey:async()=>{nt("passkey"),Vt("passkey"),await re.initLinkWithPasskey(),se("LINK_PASSKEY_SCREEN")},linkTelegram:async()=>{nt("telegram"),Vt("telegram"),V.current="link",G.current="telegram",await re.initLoginWithTelegram(),se("TELEGRAM_AUTH_SCREEN")},linkFarcaster:async()=>{nt("farcaster"),Vt("farcaster"),await re.initLoginWithFarcaster(),V.current="link",G.current="farcaster",se("AWAITING_FARCASTER_CONNECTION")},updateEmail:()=>{if(nt("email"),!s?.email)throw new w("User does not have an email linked to their account.");V.current="link",G.current="email",se("UPDATE_EMAIL_SCREEN")},updatePhone:()=>{if(nt("sms"),!s?.phone)throw new w("User does not have a phone number linked to their account.");V.current="link",G.current="sms",se("UPDATE_PHONE_SCREEN")},login:async d=>{d&&"target"in d&&d&&(d=void 0);let p="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!n){let h=await new Promise(y=>{xe(x=>y.bind(x))});if(xe(null),h){console.warn(p);return}}if(s&&!s.isGuest){console.warn(p);return}V.current="login",ee({login:d}),dt("LANDING")},connectOrCreateWallet:async()=>{if(n||(await new Promise(d=>{xe(()=>d)}),xe(null)),a){console.warn("User must be unauthenticated to `connectOrCreateWallet`");return}dt("CONNECT_OR_CREATE")},logout:async()=>{if(s&&t.clearProviderAcccessTokens(s),k(null),await t.logout(),s&&O)try{await O.clearMfa({userId:s.id})}catch{}c(null),l(!1),F(L,"logout","onSuccess"),V.current=null,G.current=null,o(!1),j.del(fa),j.del(qs(W.id))},getAccessToken:()=>t.getAccessToken(),getEthereumProvider:()=>{if(!s||!s.wallet)return new Ke;let d=m.find(h=>s.wallet&&h.address===s.wallet.address),p=t.connectors?.walletConnectors.find(h=>h.wallets.find(y=>y.address===d?.address));return!d||!p?new Ke:p.proxyProvider},getEthersProvider:()=>{if(!s||!s.wallet)return new Cu(new to(new Ke));let d=m.find(h=>s.wallet&&h.address===s.wallet.address),p=t.connectors?.walletConnectors.find(h=>h.wallets.find(y=>y.address===d?.address));return!d||!p?new Cu(new to(new Ke)):new Cu(new to(p.proxyProvider))},getWeb3jsProvider:()=>{if(!s||!s.wallet)return new Fo(new Ke);let d=m.find(h=>s.wallet&&h.address===s.wallet.address),p=t.connectors?.walletConnectors.find(h=>h.wallets.find(y=>y.address===d?.address));return!d||!p?new Fo(new Ke):new Fo(p.proxyProvider)},unlinkWallet:async d=>{let p=await t.unlinkWallet(d);return c(p),p},unlinkEmail:async d=>{let p=await t.unlinkEmail(d);return c(p),p},unlinkPhone:async d=>{let p=await t.unlinkPhone(d);return c(p),p},unlinkGoogle:async d=>{let p=await t.unlinkOAuth("google",d);return c(p),p},unlinkTwitter:async d=>{let p=await t.unlinkOAuth("twitter",d);return c(p),p},unlinkDiscord:async d=>{let p=await t.unlinkOAuth("discord",d);return c(p),p},unlinkGithub:async d=>{let p=await t.unlinkOAuth("github",d);return c(p),p},unlinkSpotify:async d=>{let p=await t.unlinkOAuth("spotify",d);return c(p),p},unlinkInstagram:async d=>{let p=await t.unlinkOAuth("instagram",d);return c(p),p},unlinkTiktok:async d=>{let p=await t.unlinkOAuth("tiktok",d);return c(p),p},unlinkLinkedIn:async d=>{let p=await t.unlinkOAuth("linkedin",d);return c(p),p},unlinkApple:async d=>{let p=await t.unlinkOAuth("apple",d);return c(p),p},unlinkFarcaster:async d=>{let p=await t.unlinkFarcaster(d);return c(p),p},unlinkTelegram:async d=>{let p=await t.unlinkTelegram(d);return c(p),p},unlinkPasskey:async d=>{let p=await t.unlinkPasskey(d);return c(p),p},unlinkCrossAppAccount:async({subject:d})=>{let p=s?.linkedAccounts.find(y=>y.type==="cross_app"&&y.subject===d)?.providerApp;if(!p)throw new w("Invalid subject");t.storeProviderAccessToken(p.id,null);let h=await t.unlinkOAuth(`privy:${p.id}`,d);return c(h),h},setActiveWallet:async d=>{let p=m.find(y=>Oo(y.address)===Oo(d)),h=s?.linkedAccounts.find(y=>y.type==="wallet"&&Oo(y.address)===Oo(d));if(!p||!await p.isConnected())Y(d),bu();else if(!p.linked)p.loginOrLink();else{let y=Object.assign({},s);y.wallet=h&&{address:h.address,chainType:h.chainType,chainId:h.chainId,walletClient:h.walletClient,walletClientType:h.walletClientType,connectorType:h.connectorType,imported:h.imported},c(y)}},forkSession:()=>t.forkSession(),createWallet:async()=>{if(!a||!s)throw F(L,"createWallet","onError","must_be_authenticated"),new Error("User must be authenticated before creating a Privy wallet");return fd(s,15e3)},setWalletRecovery:async d=>Pu({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:d?.showAutomaticRecovery??!1}),setWalletPassword:async()=>Pu({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(d,p,h)=>new Promise(async(y,x)=>{let{requesterAppId:N}=p||{};if(!a||!s){F(L,"signMessage","onError","must_be_authenticated"),x(new Error("User must be authenticated before signing with a Privy wallet"));return}let $=h?s?.linkedAccounts.find(oe=>oe.type==="wallet"&&oe.walletClientType==="privy"&&Oo(oe.address)===Oo(h)):ye(s);if(!$){F(L,"signMessage","onError","embedded_wallet_not_found"),x(new Error("Must have a Privy wallet before signing"));return}if(typeof d!="string"||d.length<1){F(L,"signMessage","onError","invalid_message"),x(new Error("Message must be a non-empty string"));return}X(!0);let te=async()=>{if(!a)throw new Error("User must be authenticated before signing with a Privy wallet");let oe=await Ee();if(!O||!oe)throw new Error("Unable to connect to wallet");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:$.address,requesterAppId:N}});let{response:Be}=await O.rpc({accessToken:oe,address:$.address,requesterAppId:N,request:{method:"personal_sign",params:[d,$.address]}}),et=Be.data;return t.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:$.address,requesterAppId:N}}),et};if(W.embeddedWallets.noPromptOnSignature){p&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let oe=await te();F(L,"signMessage","onSuccess",oe),y(oe)}catch(oe){F(L,"signMessage","onError","unable_to_sign"),x(oe??new wt("Unable to sign message"))}}else{let Be={method:"personal_sign",data:d,confirmAndSign:te,onSuccess:Qe=>{F(L,"signMessage","onSuccess",Qe),y(Qe)},onFailure:Qe=>{F(L,"signMessage","onError","unable_to_sign"),x(Qe)},uiOptions:p||{}},et={onCompleteNavigateTo:"EMBEDDED_WALLET_SIGN_REQUEST_SCREEN",onFailure:Qe=>{F(L,"signMessage","onError","unknown_connect_wallet_error"),x(Qe)},address:$.address};ee({signMessage:Be,connectWallet:et}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}}),signTypedData:(d,p)=>new Promise(async(h,y)=>{let{requesterAppId:x}=p||{};if(!a||!s){F(L,"signTypedData","onError","must_be_authenticated"),y(new Error("User must be authenticated before signing with a Privy wallet"));return}let N=ye(s);if(!N){F(L,"signTypedData","onError","embedded_wallet_not_found"),y(new Error("Must have a Privy wallet before signing"));return}X(!0);let $=pa(d),te=async()=>{if(!a)throw new Error("User must be authenticated before signing with a Privy wallet");let oe=await Ee();if(!O||!oe)throw new Error("Unable to connect to wallet");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:N.address,requesterAppId:x}});let{response:Be}=await O.rpc({accessToken:oe,address:N.address,requesterAppId:x,request:{method:"eth_signTypedData_v4",params:[N.address,$]}}),et=Be.data;return t.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:N.address,requesterAppId:x}}),et};if(W.embeddedWallets.noPromptOnSignature||(W.legacyWalletUiConfig??!1)){p&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let oe=await te();F(L,"signTypedData","onSuccess",oe),h(oe)}catch(oe){F(L,"signTypedData","onError","unable_to_sign"),y(oe??new wt("Unable to sign message"))}}else{let Be={method:"eth_signTypedData_v4",data:$,confirmAndSign:te,onSuccess:Qe=>{F(L,"signTypedData","onSuccess",Qe),h(Qe)},onFailure:Qe=>{F(L,"signTypedData","onError","unable_to_sign"),y(Qe)},uiOptions:p||{}},et={onCompleteNavigateTo:"EMBEDDED_WALLET_SIGN_REQUEST_SCREEN",onFailure:Qe=>{F(L,"signMessage","onError","unknown_connect_wallet_error"),y(Qe)}};ee({signMessage:Be,connectWallet:et}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}}),sendTransaction:async(d,p,h)=>{let x=await(await Eu(d,p,h)).wait();return cc(x)},exportWallet:()=>new Promise(async(d,p)=>{if(!a||!s){p(new Error("User must be authenticated before exporting their Privy wallet"));return}if(!ye(s)){p(new Error("Must have a Privy wallet before exporting"));return}X(!0);let y={onCompleteNavigateTo:"EMBEDDED_WALLET_KEY_EXPORT_SCREEN",onFailure:p,shouldForceMFA:!0};if(ee(ne),!await Ee()||!O){p(new Error("Must have valid access token to enroll in MFA"));return}if(!O){p(new Error("Must have a Privy wallet before exporting"));return}let N={appId:e.appId,appClientId:e.clientId,origin:t.apiUrl,onSuccess:d,onFailure:p};ee({keyExport:N,connectWallet:y}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}),promptMfa:Tu,async init(d){switch(d){case"sms":await t.initMfaSmsVerification();return;case"passkey":return await t.initMfaPasskeyVerification();case"totp":return;default:throw new Error(`Unsupported MFA method: ${d}`)}},async submit(d,p){switch(d){case"totp":case"sms":if(typeof p!="string")throw new w("Invalid MFA code");Lr.current?.resolve({mfaMethod:d,mfaCode:p,relyingParty:window.origin}),await new Promise((N,$)=>{Qr.current={resolve:N,reject:$}});break;case"passkey":if(typeof p=="string")throw new w("Invalid authenticator response");let y=await(await import("@simplewebauthn/browser")).startAuthentication(p),x=_C(y);Lr.current?.resolve({mfaMethod:d,mfaCode:x,relyingParty:window.origin}),await new Promise((N,$)=>{Qr.current={resolve:N,reject:$}});break;default:throw Lr.current?.reject(new w("Unsupported MFA method")),new w(`Unsupported MFA method: ${d}`)}},cancel(){Lr.current?.reject(new w("MFA canceled"))},async initEnrollmentWithSms(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.initEnrollMfa({method:"sms",accessToken:p,phoneNumber:d.phoneNumber})},enrollInMfa(d){return new Promise((p,h)=>{if(!d){re.closePrivyModal(),p();return}W.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."),ee({mfaEnrollmentFlow:{mfaMethods:W.mfa.methods,onSuccess:p,onFailure:h}}),se("MFA_ENROLLMENT_FLOW_SCREEN")})},async initEnrollmentWithTotp(){let d=await Ee();if(!d||!O)throw new Error("Must have valid access token to enroll in MFA");let p=await O.initEnrollMfa({method:"totp",accessToken:d});return{secret:p.secret,authUrl:p.authUrl}},async submitEnrollmentWithSms(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.submitEnrollMfa({method:"sms",accessToken:p,phoneNumber:d.phoneNumber,code:d.mfaCode});let h=await t.getAuthenticatedUser();c(h)},async submitEnrollmentWithTotp(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.submitEnrollMfa({method:"totp",accessToken:p,code:d.mfaCode});let h=await t.getAuthenticatedUser();c(h)},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:d}){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.submitEnrollMfa({method:"passkey",accessToken:p,credentialIds:d});let h=await t.getAuthenticatedUser();c(h)},async unenroll(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to remove MFA");d==="passkey"?await O.submitEnrollMfa({method:"passkey",accessToken:p,credentialIds:[]}):await O.unenrollMfa({method:d,accessToken:p});let h=await t.getAuthenticatedUser();c(h)},requestFarcasterSignerFromWarpcast:async()=>{let d=await Ee(),p=s?.linkedAccounts.find(x=>x.type==="wallet"&&x.walletClientType==="privy");if(!d)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!p)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");let y=await O.initFarcasterSigner({address:p.address,hdWalletIndex:null,accessToken:d,mfaCode:null,mfaMethod:null,relyingParty:window.origin});if(y.status==="approved"){let x=await t.getAuthenticatedUser();c(x||s||null)}ee({farcasterSigner:y}),se("AWAITING_FARCASTER_SIGNER")},getFarcasterSignerPublicKey:async()=>{let d=await Ee(),p=s?.linkedAccounts.find(x=>x.type==="wallet"&&x.walletClientType==="privy");if(!d)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!p)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");if(!s.farcaster?.signerPublicKey)throw new Error("Must have a Farcaster signer public key to sign");return(x=>Uint8Array.from(x.match(/.{1,2}/g).map(N=>parseInt(N,16))))(s.farcaster.signerPublicKey.slice(2))},signFarcasterMessage:async d=>{let p=await Ee(),h=s?.linkedAccounts.find($=>$.type==="wallet"&&$.walletClientType==="privy");if(!p)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!h)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");if(!s.farcaster?.signerPublicKey)throw new Error("Must have a Farcaster signer public key to sign");let x=await import("@simplewebauthn/browser"),N=await O.signFarcasterMessage({address:h.address,hdWalletIndex:null,accessToken:p,mfaCode:null,mfaMethod:null,payload:{hash:x.bufferToBase64URLString(d)},fid:BigInt(s.farcaster.fid),relyingParty:window.origin});return new Uint8Array(x.base64URLStringToBuffer(N.signature))},createGuestAccount:async()=>{if(s&&!s.isGuest)throw new Error("User cannot already be authenticated to create a guest account");return s?.isGuest?s:re.loginWithGuestAccountFlow()},isHeadlessOAuthLoading:_,loginWithCode(d){return re.loginWithCode(d)},initLoginWithEmail(d){return re.initLoginWithEmail(d)},initLoginWithSms(d){return re.initLoginWithSms(d)},otpState:D,fundWallet(d,p){return re.fundWallet(d,p)},initLoginWithHeadlessOAuth(d,p){return re.initLoginWithHeadlessOAuth(d,p)},loginWithHeadlessOAuth(d){return re.loginWithHeadlessOAuth(d)},generateSiweMessage({address:d,chainId:p}){return re.generateSiweMessage({address:d,chainId:p})},linkWithSiwe({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x}){return nt("siwe"),re.linkWithSiwe({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x})},signMessageWithCrossAppWallet(d,{address:p}){return fc({user:s,client:t,address:p,requesterAppId:W.id,request:{method:"personal_sign",params:[d,p]},reconnect:ws})},signTypedDataWithCrossAppWallet(d,{address:p}){let h=pa(d);return fc({user:s,client:t,address:p,requesterAppId:W.id,request:{method:"eth_signTypedData_v4",params:[p,h]},reconnect:ws})},sendTransactionWithCrossAppWallet(d,{address:p}){return fc({user:s,client:t,address:p,requesterAppId:W.id,request:{method:"eth_sendTransaction",params:[d]},reconnect:ws})},isModalOpen:r,mfaMethods:W.mfa.methods};AC=ii.signMessage,xC=ii.signTypedData,kC=async(...d)=>{let p=await Eu(...d);return W.embeddedWallets.waitForTransactionConfirmation&&await p.wait(),p};let re=(()=>({isNewUserThisSession:g,linkingOrConnectingHint:K,pendingTransaction:null,walletConnectionStatus:R,connectors:t.connectors?.walletConnectors??[],rpcConfig:W.rpcConfig,chains:W.chains,appId:e.appId,showFiatPrices:W.embeddedWallets.priceDisplay.primary!=="native-token",clientAnalyticsId:t.clientAnalyticsId,nativeTokenSymbolForChainId:d=>W.chains.find(p=>p.id===Number(d))?.nativeCurrency.symbol,initializeWalletProxy:async d=>{if(O)return O;let p=new Promise(x=>{Fe(()=>N=>x(N))}),h=new Promise(x=>setTimeout(()=>x(null),d)),y=await Promise.race([p,h]);return Fe(null),y},getAuthFlow:()=>t.authFlow,getAuthMeta:()=>t.authFlow?.meta,closePrivyModal:async(d={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let p=n&&a&&s,h;if(p&&G.current&&(h=Su(s)),V.current==="login"?d.shouldCallAuthOnSuccess&&p&&G.current?(F(L,"login","onComplete",s,g,!1,G.current,h??null),e.onSuccess?.(s,g)):F(L,"login","onError","exited_auth_flow"):V.current==="link"&&h&&(d.isSuccess&&p&&G.current?F(L,"linkAccount","onSuccess",s,G.current,h):G.current&&F(L,"linkAccount","onError","exited_link_flow",{linkMethod:G.current})),E&&Sv.includes(E)&&ne.funding){let y=_v[E]??null,x=qt(ne.funding.chain.id,W.chains,W.rpcConfig,{appId:e.appId}),N;try{N=(await x.getBalance(ne.funding.address)).toBigInt()}catch{console.error("Unable to pull wallet balance")}F(L,"fundWallet","onUserExited",{address:ne.funding.address,chain:ne.funding.chain,fundingMethod:y,balance:N})}Y(null),V.current=null,G.current=null,b(!1),o(!1),setTimeout(()=>{t.authFlow=void 0},200),t.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:async({message:d})=>new Promise(async(p,h)=>{let y=async()=>{let x=await t.getAccessToken();if(!x)throw new Error("User must be authenticated to use their embedded wallet.");if(!u)throw new Error("User must have an embedded Solana wallet to sign messages for Solana.");let N=re.walletProxy??await re.initializeWalletProxy(15e3);if(!N)throw new Error("Failed to initialize embedded wallet proxy.");let{response:$}=await N.rpcSolana({accessToken:x,publicKey:u.address,request:{method:"signMessage",params:{message:d}}});return $.data.signature};if(W.embeddedWallets.noPromptOnSignature)try{let x=await y();p({signature:x})}catch(x){h(x)}else ee({signMessage:{method:"solana_signMessage",data:d,confirmAndSign:y,onSuccess:te=>{p({signature:te})},onFailure:te=>{h(te)},uiOptions:{}}}),dt("EMBEDDED_WALLET_SIGN_REQUEST_SCREEN")}),openPrivyModal:se,connectWallet:gs,initLoginWithWallet:async(d,p)=>{G.current="siwe",vs(d,p)},loginWithWallet:async()=>{if(!n)throw new Eo;if(!(t.authFlow instanceof So))throw new w("Must initialize SIWE flow first.");let d,p;if(a)try{({user:d}=await t.link()),G.current="siwe"}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"failed_to_link_account",{linkMethod:"siwe"}),h}else try{({user:d,isNewUser:p}=await t.authenticate()),G.current="siwe"}catch(h){throw F(L,"login","onError",h.privyErrorCode||"generic_connect_wallet_error"),h}c(d||s||null),b(p||!1),l(!0)},initLoginWithFarcaster:async d=>{let p=new ua(d);t.startAuthFlow(p);try{G.current="farcaster",await p.initializeFarcasterConnect()}catch(h){throw V.current==="login"?F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",h.privyErrorCode||"unknown_auth_error",{linkMethod:"farcaster"}),h}},loginWithFarcaster:async()=>{if(!n)throw new Eo;if(!(t.authFlow instanceof ua))throw new w("Must initialize Farcaster flow first.");let d,p;if(a)try{({user:d}=await t.link()),G.current="farcaster"}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"failed_to_link_account",{linkMethod:"farcaster"}),h}else try{({user:d,isNewUser:p}=await t.authenticate()),G.current="farcaster"}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}c(d||null),b(p||!1),l(!0)},async loginWithGuestAccountFlow(){let d=new di(this.appId);t.startAuthFlow(d);try{V.current="login",G.current="guest";let p=await t.authenticate(),{user:h,isNewUser:y}=p;if(y=y||!1,!h)throw new w("Unable to authenticate guest account");if(Lt(h,W.embeddedWallets.createOnLogin))try{await fd(h,15e3),h=await re.refreshUser()}catch{c(h),console.warn("Unable to create embedded wallet for guest account")}else c(h);return b(y),l(!0),F(L,"login","onComplete",h,y,!1,"guest",null),h}catch(p){throw F(L,"login","onError",p.privyErrorCode||"unknown_auth_error"),p}},async crossAppAuthFlow({appId:d,popup:p}){let h=`privy:${d}`;G.current=h;let{url:y,stateCode:x,codeVerifier:N}=await Dg({api:t.api,appId:d});if(!y)throw t.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:d}}),new w("No authorization URL returned for cross-app auth.");try{let $=await SC({url:y,popup:p,provider:h}),te=$.stateCode,oe=$.authorizationCode;if(te!==x)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:h,storedStateCode:x??"",returnedStateCode:te??""}}),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected");let Ve=await Ug({api:bo.api,appId:d,codeVerifier:N,stateCode:te,authorizationCode:oe});Ve&&t.storeProviderAccessToken(d,Ve);let Be=await re.refreshUser();if(!Be)throw new w("Unable to update user");return t.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{appId:d}}),Be}catch($){throw t.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:$.toString(),provider:h}}),$}},async initLoginWithOAuth(d,p){if(G.current=d,la()){if(d==="google"&&Wi(window.navigator.userAgent)){dt("IN_APP_BROWSER_LOGIN_NOT_POSSIBLE");return}}else{dt("IN_APP_BROWSER_LOGIN_NOT_POSSIBLE");return}d==="twitter"&&window.opener&&window.opener.postMessage({type:"PRIVY_OAUTH_USE_BROADCAST_CHANNEL"},"*"),j.del(Sn);let h=new Xr({provider:d});p&&h.addCaptchaToken(p),t.startAuthFlow(h);let y=await t.authFlow.getAuthorizationUrl();y&&y.url&&(d==="twitter"&&I_&&(y.url=y.url.replace("x.com","twitter.com")),window.location.assign(y.url))},async initLoginWithTelegram(d){if(!n)throw new Eo;G.current="telegram";let p=new mi(d);t.startAuthFlow(p),p.meta.telegramWebAppData=void 0,p.meta.telegramAuthResult=await new Promise((h,y)=>{if(!W.loginConfig.telegramAuthConfiguration)return y(new w("Telegram Auth configuration is not loaded"));if(!window.Telegram)return y(new w("Telegram was not initialized"));window.Telegram.Login.auth({bot_id:W.loginConfig.telegramAuthConfiguration.botId,request_access:!0},x=>x?h(x):y(new w("Telegram auth failed or was canceled by the client")))})},async loginWithTelegram(){if(!(t.authFlow instanceof mi))throw new w("Must initialize Telegram flow before calling loginWithTelegram");let d,p;if(V.current==="login")try{let h=await t.authenticate();d=h.user,p=h.isNewUser,G.current="telegram"}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}else if(V.current==="link")try{d=(await t.link()).user,G.current="telegram"}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"failed_to_link_account",{linkMethod:"telegram"}),h}else throw new w("Unknown auth intent");c(d),b(p||!1),l(!0)},async recoveryOAuthFlow(d,p,h){let y,x;function N($){if(!$)throw t.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:d}}),new w("Recovery OAuth failed")}switch(d){case"google-drive":{let{url:$,codeVerifier:te,stateCode:oe}=await up({api:bo.api,provider:d});N($);let Ve,Be;try{let et=await vu({url:$,popup:h,provider:d});if(Ve=et.stateCode,Be=et.authorizationCode,Ve!==oe)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:d,storedStateCode:oe??"",returnedStateCode:Ve??""}}),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected")}catch(et){throw t.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:et.toString(),provider:d}}),new w("Recovery OAuth failed")}[y,x]=await Promise.all([Ee(),Ay({api:bo.api,provider:d,codeVerifier:te,stateCode:Ve,authorizationCode:Be})]);break}case"icloud":{let{url:$}=await up({api:bo.api,provider:d});N($);let{ckWebAuthToken:te}=await vu({url:$,popup:h,provider:d});x=te,y=await Ee();break}}if(!O)throw new w("Cannot connect to wallet proxy");if(!y)throw new w("Unable to authorize user");switch(p){case"recover":let $=ne.recoverWallet?.privyWallet?.address;if(!$)throw new w("Recovery OAuth failed");t.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:$,recoveryMethod:d}}),await O.recover({address:$,accessToken:y,recoveryAccessToken:x,recoveryMethod:d}),t.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:$,recoveryMethod:d}});break;case"create-wallet":t.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await O.create({accessToken:y,recoveryAccessToken:x,recoveryMethod:d});let te=await re.refreshUser(),oe=ye(te);if(!oe)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to create wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:oe.address}}),F(L,"createWallet","onSuccess",oe);break;case"set-recovery":let Ve=ye(s);if(!Ve)throw F(L,"setWalletRecovery","onError","embedded_wallet_not_found"),new Error("Embedded wallet not found");t.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:Ve.address,existingRecoveryMethod:Ve.recoveryMethod,targetRecoveryMethod:d}}),await O.setRecovery({address:Ve.address,accessToken:y,recoveryAccessToken:x,recoveryMethod:d});let Be=ye(await re.refreshUser());if(!Be)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to set recovery on wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:Ve.address,existingRecoveryMethod:Ve.recoveryMethod,targetRecoveryMethod:d}}),F(L,"setWalletRecovery","onSuccess",d,Be);break;default:throw new w("Unsupported recovery action")}},async loginWithOAuth(d){if(!(t.authFlow instanceof Xr))throw new w("Must initialize OAuth flow before calling loginWithOAuth");let p=j.get(En),h=t.authFlow.meta.stateCode;if(p!==h)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:d,storedStateCode:p??"",returnedStateCode:h??""}}),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected");let y=await t.getAccessToken({disableAutoRefresh:!0}),x,N,$;if(a||y!==null)try{let te=await t.link();x=te.user,$=te.oAuthTokens,G.current=d}catch(te){throw F(L,"linkAccount","onError",te.privyErrorCode||"failed_to_link_account",{linkMethod:d}),te}else try{let te=await t.authenticate();x=te.user,N=te.isNewUser,$=te.oAuthTokens,G.current=d}catch(te){throw V.current==="login"?F(L,"login","onError",te.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",te.privyErrorCode||"failed_to_link_account",{linkMethod:d}),te}return c(x),b(N||!1),l(!0),$&&x&&F(L,"oAuthAuthorization","onOAuthTokenGrant",$,{user:x}),$},async initLoginWithPasskey(d){let p=new xn(d);t.startAuthFlow(p),V.current="login";try{G.current="passkey",await p.initAuthenticationFlow()}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}},async loginWithPasskey(){if(!n)throw new Eo;if(!(t.authFlow instanceof xn))throw new w("Must initialize Passkey flow first.");if(G.current!=="passkey")throw new w("Must init login with Passkey flow first.");let d,p;try{G.current="passkey",{user:d,isNewUser:p}=await t.authenticate()}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}c(d),b(p||!1),l(!0)},async initLinkWithPasskey(d){let p=new xn(d);t.startAuthFlow(p),V.current="link",G.current="passkey";try{await p.initLinkFlow()}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"unknown_auth_error",{linkMethod:"passkey"}),h}},async linkWithPasskey(){if(!n)throw new Eo;if(!(t.authFlow instanceof xn))throw new w("Must initialize Passkey flow first.");if(G.current!=="passkey")throw new w("Must init login with Passkey flow first.");let d;try{G.current="passkey",{user:d}=await t.link()}catch(p){throw F(L,"linkAccount","onError",p.privyErrorCode||"failed_to_link_account",{linkMethod:"passkey"}),p}return c(d||s||null),d},async initLoginWithHeadlessOAuth(d,p){if(la()){if(d==="google"&&Wi(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.")}else throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let h=new Xr({provider:d,headless:!0});p&&h.addCaptchaToken(p);let y=await t.startAuthFlow(h).getAuthorizationUrl();y?.url&&window.location.assign(y.url)},async loginWithHeadlessOAuth(d){S(!0),t.startAuthFlow(new Xr(d));let p=j.get(En),h=d.stateCode;if(p!==h)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:d.provider,storedStateCode:p??"",returnedStateCode:h??""}}),S(!1),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected");let y,x;if(a)try{({user:y}=await t.link()),G.current=d.provider}catch(N){throw F(L,"linkAccount","onError",N.privyErrorCode||"failed_to_link_account",{linkMethod:d.provider}),N}else try{({user:y,isNewUser:x}=await t.authenticate()),G.current=d.provider}catch(N){throw V.current==="login"?F(L,"login","onError",N.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",N.privyErrorCode||"failed_to_link_account",{linkMethod:d.provider}),N}return c(y),b(x||!1),l(!0),S(!1),y??void 0},initLoginWithEmail:async(d,p)=>{let h=new Lo(d,p);t.startAuthFlow(h);try{G.current="email",await h.sendCodeEmail()}catch(y){throw V.current==="login"?F(L,"login","onError",y.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",y.privyErrorCode||"failed_to_link_account",{linkMethod:"email"}),y}},initUpdateEmail:async(d,p,h)=>{let y=new Is(d,p,h);t.startAuthFlow(y),await y.sendCodeEmail()},initUpdatePhone:async(d,p,h)=>{let y=new al(d,p,h);t.startAuthFlow(y),await y.sendSmsCode()},initLoginWithSms:async(d,p)=>{H({status:"sending-code"});let h=new Do(d,p);t.startAuthFlow(h);try{G.current="sms",await h.sendSmsCode(),H({status:"awaiting-code-input"})}catch(y){throw H({status:"error",error:y}),V.current==="login"?F(L,"login","onError",y.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",y.privyErrorCode||"failed_to_link_account",{linkMethod:"sms"}),y}},resendEmailCode:async()=>{await t.authFlow?.sendCodeEmail()},resendSmsCode:async()=>{await t.authFlow?.sendSmsCode()},loginWithCode:async d=>{if(H({status:"submitting-code"}),!n){let y=new Eo;throw H({status:"error",error:y}),y}if(t.authFlow instanceof Lo)t.authFlow.meta.emailCode=d.trim();else if(t.authFlow instanceof Do)t.authFlow.meta.smsCode=d.trim();else{let y=new w("Must initialize a passwordless code flow first");throw H({status:"error",error:y}),y}await Ee();let p,h;if(V.current==="link")try{({user:p}=await t.link())}catch(y){throw H({status:"error",error:y}),F(L,"linkAccount","onError",y.privyErrorCode||"failed_to_link_account",{linkMethod:G.current}),y}else try{({user:p,isNewUser:h}=await t.authenticate())}catch(y){throw H({status:"error",error:y}),F(L,"login","onError",y.privyErrorCode||"unknown_auth_error"),y}c(p||s||null),b(h||!1),l(!0),H({status:"done"})},generateSiweMessage:async({address:d,chainId:p,captchaToken:h})=>{V.current="link",G.current="siwe";let y=await t.generateSiweNonce({address:d,captchaToken:h}),x=p.replace("eip155:","");return il({address:d,chainId:x,nonce:y})},linkWithSiwe:async({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x})=>{let N;try{N=await t.linkWithSiwe({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x}),N=await re.refreshUser()??N;let $=Su(N);$&&F(L,"linkAccount","onSuccess",N,"siwe",$)}catch($){throw F(L,"linkAccount","onError",$.privyErrorCode||"failed_to_link_account",{linkMethod:"siwe"}),V.current=null,G.current=null,$}c(N||s||null),V.current=null,G.current=null},refreshUser:async()=>{let d=await t.getAuthenticatedUser();return c(d),d},walletProxy:O,createAnalyticsEvent:({eventName:d,payload:p,timestamp:h})=>t.createAnalyticsEvent({eventName:d,payload:p,timestamp:h}),acceptTerms:async()=>{let d=await t.acceptTerms();return c(d),d},getUsdTokenPrice:d=>t.getUsdTokenPrice(d),recoverEmbeddedEthereumWallet:async d=>new Promise(async(p,h)=>{let y=ye(d?.user??s)||sl(d?.user??s),x=await Ee();if(!x||!O||!y){h(new Error("Must have valid access token and Privy wallet to recover wallet"));return}X(!0);try{await O.connect({accessToken:x,address:y.address}),p(!0)}catch(N){if(Hn(N)&&y.recoveryMethod==="privy")t.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:y.address}}),(await O.recover({address:y.address,accessToken:x,recoveryMethod:y.recoveryMethod})).address||h(new Error("Unable to recover wallet")),t.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:y.address}}),p(!0);else if(Hn(N)&&y.recoveryMethod!=="privy"){ee({recoverWallet:{privyWallet:y,onFailure:h,onSuccess:()=>p(!0)},recoveryOAuthStatus:{provider:y.recoveryMethod,action:"recover"}});let $=zl(y.recoveryMethod);se($)}else h(N)}}),embeddedSolanaWallet:u,createEmbeddedSolanaWallet:async()=>{X(!0);let d=await Ee(),p=await re.refreshUser(),h=kn(p),y=ye(p);if(!p||!d)throw new w("User must be logged in to create a Solana wallet");if(h)throw new w("User already has an embedded Solana wallet.");if(y)if(y.recoveryMethod==="privy")await re.recoverEmbeddedEthereumWallet({user:p});else throw new w("Cannot create an embedded Solana wallet for a user with an existing Ethereum wallet with user-controlled recovery.");let x=await re.initializeWalletProxy(15e3);if(!x)throw new w("Unable to initialize wallet proxy");t.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_started"});try{await x.createSolana({accessToken:d,ethereumAddress:y?.address});let N=await re.refreshUser(),$=kn(N);if(!$)throw new w("Could not get Solana wallet for user");return t.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_completed",payload:{walletAddress:$.address}}),$}catch(N){throw t.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_failed"}),new w("Failed to create Solana embedded wallet with error ",N)}},recoverEmbeddedSolanaWallet:async()=>new Promise(async(d,p)=>{let h=kn(s),y=await Ee();if(!y||!O||!h){p(new Error("Must have valid access token and Privy wallet to recover wallet"));return}X(!0);try{await O.connectSolana({accessToken:y,publicKey:h.address}),d(!0)}catch(x){Hn(x)&&h.recoveryMethod==="privy"?(t.createAnalyticsEvent({eventName:"embedded_solana_wallet_pinless_recovery_started",payload:{walletAddress:h.address}}),(await O.recoverSolana({publicKey:h.address,accessToken:y})).publicKey||p(new Error("Unable to recover wallet")),t.createAnalyticsEvent({eventName:"embedded_solana_wallet_recovery_completed",payload:{walletAddress:h.address}}),d(!0)):p(x)}}),getMoonpaySignedUrl:HC,initCoinbaseOnRamp:t.initCoinbaseOnRamp.bind(t),getCoinbaseOnRampStatus:t.getCoinbaseOnRampStatus.bind(t),setReadyToTrue:d=>{i(!0),_e?.(d)},updateWallets:()=>Cs(),fundWallet:async(d,p)=>{if(!W.fundingConfig||W.fundingConfig.methods.length===0)throw new Error("Wallet funding is not enabled");let h=ld({fundingMethods:W.fundingConfig.methods});ee({funding:_u({address:d,fundWalletConfig:p,methodScreen:h})}),se(h)},requestFarcasterSignerStatus:async d=>{let p=await Ee(),h=s?.linkedAccounts.find(x=>x.type==="wallet"&&x.walletClientType==="privy");if(!p)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!h)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");let y=await t.requestFarcasterSignerStatus(d);if(y.status==="approved"){let x=await t.getAuthenticatedUser();c(x||s||null)}return y},connectCoinbaseSmartWallet:async()=>{W.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let d=t.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||t.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(d)return d.updateConnectionPreference("smartWalletOnly"),gs(d);await wu("coinbase_wallet","coinbase_smart_wallet")}}))();RC=re.recoverEmbeddedEthereumWallet,IC=re.recoverEmbeddedSolanaWallet,MC=re.solanaSignMessage;let qC=R_(()=>({wallets:m,ready:ft&&ot}),[m,ft,ot]);return Er(we.Provider,{value:ii,children:Er(Gd.Provider,{value:L,children:Er(xp.Provider,{value:qC,children:Er(ph,{...W,children:PC(Hd.Provider,{value:re,children:[Er(ly,{children:PC(nh,{data:ne,setModalData:ee,setInitialScreen:k,initialScreen:E,authenticated:a,open:r,children:[e.children,!W.headless&&W.captchaEnabled&&n&&!a&&Er(Bd,{delayedExecution:!1}),Er(sC,{theme:{...W.appearance.palette||{}}}),!W.render.standalone&&Er(yu,{open:r})]})}),ce&&be?Er(bC,{appId:e.appId,appClientId:e.clientId,clientAnalyticsId:t.clientAnalyticsId,origin:t.apiUrl,mfaMethods:s?.mfaMethods,mfaPromise:Lr,mfaSubmitPromise:Qr,onLoad:U,onLoadFailed:()=>null}):null,W.loginConfig.telegramAuthConfiguration&&Er(Hr,{if:!0,children:Er(vC,{scriptHost:e.apiUrl||Bs,botUsername:W.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};import{useContext as F_}from"react";function B_(e){let{login:t}=F_(we);return Pe("login",e),{login:t}}import{useContext as H_}from"react";function G_(e){let{logout:t}=H_(we);return Pe("logout",e),{logout:t}}import{useCallback as WC,useEffect as V_}from"react";function q_(){let e=Te(),t=hl(),{initLoginWithHeadlessOAuth:r,loginWithHeadlessOAuth:o,isHeadlessOAuthLoading:n,ready:i,user:a}=q(),l=WC(async c=>{if(e.enabled&&e.status!=="success")throw new ar(e.error,null,"captcha_failure");return r(c.provider,e.token)},[r,e]),s=WC(async()=>{let c=Ca();if(a)return console.warn("Cannot login with OAuth when already logged in"),a;if(!c.inProgress)throw new Error("Cannot login with OAuth because no OAuth flow is in progress");if(!c.popupFlow)try{return await o(c)}catch(m){throw m}finally{An()}},[o]);return V_(()=>{let c=Ca();i&&t&&c.inProgress&&c.headless&&!c.popupFlow&&s()},[i,t]),{initOAuth:l,loginWithOAuth:s,loading:n}}import{useCallback as OC}from"react";var z_=()=>{let e=Te(),{initLoginWithEmail:t,loginWithCode:r}=q(),o=OC(async({email:i})=>{if(!i)throw new Error("Email required to send OTP code");return t(i)},[t]),n=OC(async({code:i})=>{if(e.enabled&&e.status==="error")throw new ar(e.error,null,"captcha_failure");return r(i)},[r,e.status]);return{sendCode:o,loginWithCode:n}};import{useCallback as LC}from"react";var $_=()=>{let e=Te(),{initLoginWithSms:t,loginWithCode:r,otpState:o}=q(),n=LC(async({phoneNumber:a})=>{if(!a)throw new Error("SMS required to send OTP code");return t(a)},[t]),i=LC(async({code:a})=>{if(e.enabled&&e.status!=="success")throw new ar(e.error,null,"captcha_failure");return r(a)},[r,e.status]);return{sendCode:n,loginWithCode:i,state:o}};import{useCallback as NC}from"react";var K_=()=>{let e=Te(),{generateSiweMessage:t,linkWithSiwe:r}=q(),o=NC(async({address:i,chainId:a})=>{if(!i||!a)throw new Error("wallet address and chainId required to generate nonce");return t({address:i,chainId:a}).then(l=>l)},[t]),n=NC(async({signature:i,message:a,chainId:l,walletClientType:s,connectorType:c})=>{if(e.enabled&&e.status!=="success")throw new ar(e.error,null,"captcha_failure");return r({message:a,signature:i,chainId:l,walletClientType:s,connectorType:c})},[r,e.status]);return{generateSiweMessage:o,linkWithSiwe:n}};import{useContext as Y_}from"react";function j_(e){let{linkEmail:t,linkPhone:r,linkWallet:o,linkGoogle:n,linkApple:i,linkTwitter:a,linkDiscord:l,linkGithub:s,linkLinkedIn:c,linkTiktok:m,linkSpotify:f,linkInstagram:u,linkTelegram:C,linkFarcaster:v}=Y_(we);return Pe("linkAccount",e),{linkEmail:t,linkPhone:r,linkWallet:o,linkGoogle:n,linkApple:i,linkTwitter:a,linkDiscord:l,linkGithub:s,linkLinkedIn:c,linkTiktok:m,linkSpotify:f,linkInstagram:u,linkFarcaster:v,linkTelegram:C}}import{useContext as Z_}from"react";function Q_(e){let{connectWallet:t}=Z_(we);return Pe("connectWallet",e),{connectWallet:t}}import{useContext as J_}from"react";function X_(e){let{createWallet:t}=J_(we);return Pe("createWallet",e),{createWallet:t}}var eP=e=>{Pe("fundWallet",e);let{fundWallet:t}=q();return{fundWallet:t}};var tP=()=>{let{embeddedSolanaWallet:e,createEmbeddedSolanaWallet:t}=I();return{createWallet:t,wallets:e?[e]:[]}};var rP=()=>{let{connectCoinbaseSmartWallet:e}=I();return{connectCoinbaseSmartWallet:e}};var oP=()=>{let{linkCrossAppAccount:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:o,sendTransactionWithCrossAppWallet:n}=q();return{linkCrossAppAccount:e,unlinkCrossAppAccount:t,signMessage:r,signTypedData:o,sendTransaction:n}};import{useContext as nP}from"react";function iP(e){let{sendTransaction:t}=nP(we);return Pe("sendTransaction",e),{sendTransaction:t}}import{useContext as aP}from"react";function sP(e){let{setWalletPassword:t}=aP(we);return Pe("setWalletPassword",e),{setWalletPassword:t}}import{useContext as lP}from"react";function cP(){let{createGuestAccount:e}=lP(we);return{createGuestAccount:e}}import{useContext as dP}from"react";function pP(e){let{setWalletRecovery:t}=dP(we);return Pe("setWalletRecovery",e),{setWalletRecovery:t}}import{useContext as uP}from"react";function mP(e){let{signMessage:t}=uP(we);return Pe("signMessage",e),{signMessage:t}}import{useContext as fP}from"react";function hP(e){let{signTypedData:t}=fP(we);return Pe("signTypedData",e),{signTypedData:t}}import{useContext as yP}from"react";var gP=()=>{let{isModalOpen:e}=yP(we);return{isOpen:e}};import{useContext as vP}from"react";function CP(e){let{getAccessToken:t}=vP(we);return Pe("accessToken",e),{getAccessToken:t}}function wP(e){let{authenticated:t,user:r}=q(),{initLoginWithOAuth:o}=I(),n=Ti();return Pe("oAuthAuthorization",e),{reauthorize:i=>bP(t,r,o,n,i.provider)}}var bP=async(e,t,r,o,n)=>{if(!e)throw o("linkAccount","onError","must_be_authenticated",{linkMethod:n}),new w("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some(a=>a.type.includes(n)))throw new w(`OAuth account of type ${n} not linked to the account.`);await r(n)};var EP=DC;function DC(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=q();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}}function TP(e,t){return{...e,rpcUrls:{...e.rpcUrls,privyWalletOverride:{http:[t]}}}}function SP(e){return e.find(r=>r.walletClientType==="privy"&&r.connectorType==="embedded"&&!r.imported)??null}export{to as AsExternalProvider,Bd as Captcha,Sa as ConnectorManager,yu as LoginModal,_a as PrivyClient,D_ as PrivyProvider,Ke as PrivyProxyProvider,Ea as SUPPORTED_CHAINS,Ed as VERSION,Kt as WalletConnector,TP as addRpcUrlOverrideToChain,dp as errorIndicatesMaxMfaRetries,Gn as errorIndicatesMfaTimeout,Vn as errorIndicatesMfaVerificationFailed,Ee as getAccessToken,SP as getEmbeddedConnectedWallet,rP as useConnectCoinbaseSmartWallet,Q_ as useConnectWallet,X_ as useCreateWallet,oP as useCrossAppAccounts,EP as useExperimentalFarcasterSigner,DC as useFarcasterSigner,eP as useFundWallet,cP as useGuestAccounts,j_ as useLinkAccount,K_ as useLinkWithSiwe,B_ as useLogin,z_ as useLoginWithEmail,q_ as useLoginWithOAuth,$_ as useLoginWithSms,G_ as useLogout,es as useMfa,Kr as useMfaEnrollment,gP as useModalStatus,wP as useOAuthTokens,q as usePrivy,Vd as useRegisterMfaListener,iP as useSendTransaction,sP as useSetWalletPassword,pP as useSetWalletRecovery,mP as useSignMessage,hP as useSignTypedData,tP as useSolanaWallets,CP as useToken,$r as useWallets};
3322
+ `;import{useRef as gC,useEffect as v_}from"react";import{jsx as w_}from"react/jsx-runtime";function C_({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:o}=new URL(t);return r.async=!0,r.src=`${o}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}function vC(e){let t=gC(null),r=gC();return v_(()=>{r.current?.remove(),r.current=C_(e),t.current?.after(r.current)},[e]),w_("div",{ref:t,hidden:!0})}import{useState as b_}from"react";import{useEffect as CC,useRef as wC}from"react";var ud=class{constructor(){this.callbacks={}}enqueue(t,r){this.callbacks[t]=r}dequeue(t,r){let o=this.callbacks[r];if(!o)throw new Error(`cannot dequeue ${t} event: no event found for id ${r}`);switch(delete this.callbacks[r],t){case"privy:iframe:ready":return o;case"privy:wallet:create":return o;case"privy:wallet:import":return o;case"privy:wallet:connect":return o;case"privy:wallet:recover":return o;case"privy:wallet:rpc":return o;case"privy:wallet:set-recovery":return o;case"privy:mfa:verify":return o;case"privy:mfa:init-enrollment":return o;case"privy:mfa:submit-enrollment":return o;case"privy:mfa:unenroll":return o;case"privy:mfa:clear":return o;case"privy:farcaster:init-signer":return o;case"privy:farcaster:sign":return o;case"privy:solana-wallet:create":return o;case"privy:solana-wallet:connect":return o;case"privy:solana-wallet:recover":return o;case"privy:solana-wallet:rpc":return o;default:throw new Error(`invalid wallet event type ${t}`)}}};async function Cn(e,t,r,o,n,i=!1){let a=i,l=async m=>{if(a&&t&&t.length>0){m===(i?0:1)?n("configureMfa","onMfaRequired",t):o.current?.reject(new We("missing_or_invalid_mfa","MFA verification failed, retry."));let f=await new Promise((u,C)=>{r.current={resolve:u,reject:C};let v=1e3*60*5;setTimeout(()=>{let g=new We("mfa_timeout","Timed out waiting for MFA code");o.current?.reject(g),C(g)},v)});return await e(f)}return await e()},s=4,c=null;for(let m=0;m<s;m++)try{c=await l(m),o.current?.resolve(void 0);break}catch(f){if(f.type==="missing_or_invalid_mfa")a=!0;else throw o.current?.resolve(void 0),f}if(c===null){let m=new We("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw o.current?.reject(m),m}return c}import{jsx as A_}from"react/jsx-runtime";var E_=function(e){return()=>`id-${e++}`}(0);function T_(e){return typeof e.event=="string"&&/^privy:.+/.test(e.event)}function vt(e){return e.error!==void 0}var mt=new ud,gu=new Map,S_=(e,t)=>typeof t=="bigint"?t.toString():t,__=(e,t)=>`${e}${JSON.stringify(t,S_)}`;function Ct(e,t,r,o){let n=r.contentWindow;if(!n)throw new Error("iframe not initialized");let i=__(e,t);if(e==="privy:wallet:create"){let l=gu.get(i);if(l)return l}let a=new Promise((l,s)=>{let c=E_();mt.enqueue(c,{resolve:l,reject:s}),n.postMessage({id:c,event:e,data:t},o)}).finally(()=>{gu.delete(i)});return gu.set(i,a),a}function P_(e){switch(e.event){case"privy:iframe:ready":let t=mt.dequeue(e.event,e.id);return vt(e)?t.reject(new We(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":let r=mt.dequeue(e.event,e.id);return vt(e)?r.reject(new We(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:import":let o=mt.dequeue(e.event,e.id);return vt(e)?o.reject(new We(e.error.type,e.error.message)):o.resolve(e.data);case"privy:wallet:connect":let n=mt.dequeue(e.event,e.id);return vt(e)?n.reject(new We(e.error.type,e.error.message)):n.resolve(e.data);case"privy:wallet:recover":let i=mt.dequeue(e.event,e.id);return vt(e)?i.reject(new We(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:rpc":let a=mt.dequeue(e.event,e.id);return vt(e)?a.reject(new We(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:set-recovery":let l=mt.dequeue(e.event,e.id);return vt(e)?l.reject(new We(e.error.type,e.error.message)):l.resolve(e.data);case"privy:mfa:verify":let s=mt.dequeue(e.event,e.id);return vt(e)?s.reject(new We(e.error.type,e.error.message)):s.resolve(e.data);case"privy:mfa:init-enrollment":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:mfa:submit-enrollment":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:mfa:unenroll":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:mfa:clear":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:farcaster:init-signer":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:farcaster:sign":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}case"privy:solana-wallet:create":let c=mt.dequeue(e.event,e.id);return vt(e)?c.reject(new We(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:connect":let m=mt.dequeue(e.event,e.id);return vt(e)?m.reject(new We(e.error.type,e.error.message)):m.resolve(e.data);case"privy:solana-wallet:recover":let f=mt.dequeue(e.event,e.id);return vt(e)?f.reject(new We(e.error.type,e.error.message)):f.resolve(e.data);case"privy:solana-wallet:rpc":{let u=mt.dequeue(e.event,e.id);return vt(e)?u.reject(new We(e.error.type,e.error.message)):u.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}function bC(e){let t=wC(null),r=wC(e.mfaMethods),o=Ti(),[n,i]=b_(!1);return CC(()=>{r.current=e.mfaMethods},[e.mfaMethods]),CC(()=>{if(!n)return;let a=t.current;if(!a)return;function l(u){u&&u.origin===e.origin&&T_(u.data)&&P_(u.data)}let s={create(u){return Ct("privy:wallet:create",u,a,e.origin)},import(u){return Ct("privy:wallet:import",u,a,e.origin)},connect(u){return Ct("privy:wallet:connect",u,a,e.origin)},recover(u){return Cn(C=>Ct("privy:wallet:recover",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o,!u.recoveryMethod||u.recoveryMethod==="privy")},rpc(u){return Cn(C=>Ct("privy:wallet:rpc",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},createSolana(u){return Ct("privy:solana-wallet:create",u,a,e.origin)},connectSolana(u){return Ct("privy:solana-wallet:connect",u,a,e.origin)},recoverSolana(u){return Ct("privy:solana-wallet:recover",u,a,e.origin)},rpcSolana(u){return Ct("privy:solana-wallet:rpc",u,a,e.origin)},setRecovery(u){return Cn(C=>Ct("privy:wallet:set-recovery",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},verifyMfa(u){return Cn(C=>Ct("privy:mfa:verify",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o,!0)},initEnrollMfa(u){return Cn(C=>Ct("privy:mfa:init-enrollment",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},submitEnrollMfa(u){return Cn(C=>Ct("privy:mfa:submit-enrollment",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o)},unenrollMfa(u){return Cn(C=>Ct("privy:mfa:unenroll",{...u,...C},a,e.origin),r.current,e.mfaPromise,e.mfaSubmitPromise,o,!0)},clearMfa(u){return Ct("privy:mfa:clear",u,a,e.origin)},initFarcasterSigner(u){return Ct("privy:farcaster:init-signer",u,a,e.origin)},signFarcasterMessage(u){return Ct("privy:farcaster:sign",u,a,e.origin)}};window.addEventListener("message",l);let c=()=>e.onLoad(s),m=(...u)=>{console.warn("Privy iframe failed to load: ",...u),e.onLoadFailed()},f=new AbortController;return da(()=>Ct("privy:iframe:ready",{},a,e.origin),{abortSignal:f.signal}).then(c,m),()=>{window.removeEventListener("message",l),f.abort()}},[n]),A_("iframe",{ref:t,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>i(!0),src:Ns(e.origin,`/apps/${e.appId}/embedded-wallets`,{caid:e.clientAnalyticsId,client_id:e.appClientId})})}var md=class{constructor(t,r){this.walletProxy=t,this.address=r}async handleSignMessage(t){if(!t.params||typeof t.params.message!="string")throw new Error("Message must be provided as a string for Solana signMessage RPC");return await TC({message:t.params.message})}async request(t){if(console.debug("EmbeddedSolanaProvider.request() called with args",t),!await Ee())throw new Error("User must be authenticated to use embedded Solana wallet");if(!await EC())throw new w("Unable to connect to Solana embedded wallet");switch(t.method){case"signMessage":return await this.handleSignMessage(t);default:throw new Error("Embedded Solana provider does not yet support this RPC method.")}}};async function SC({url:e,popup:t}){return t.location=e,new Promise((o,n)=>{let a=setTimeout(()=>{n(new w("Authorization request timed out after 2 minutes.")),l()},12e4);function l(){t?.close(),window.removeEventListener("message",m)}let s,c=setInterval(()=>{t?.closed&&!s&&(l(),clearInterval(c),clearTimeout(a),n(new w("User rejected request")))},300);function m(f){f.data&&(f.data.type==="PRIVY_OAUTH_RESPONSE"&&f.data.stateCode&&f.data.authorizationCode&&(clearTimeout(a),o(f.data),l()),f.data.type==="PRIVY_OAUTH_ERROR"&&(clearTimeout(a),n(new w(f.data.error)),l()),f.data.type==="PRIVY_OAUTH_USE_BROADCAST_CHANNEL"&&(s=new BroadcastChannel("popup-privy-oauth"),s.onmessage=m))}window.addEventListener("message",m)})}var x_="https://cdn.apple-cloudkit.com";async function vu({url:e,popup:t,provider:r}){return t.location=e,new Promise((n,i)=>{function a(){t?.close(),window.removeEventListener("message",l)}function l(s){s.data&&(s.data.type==="PRIVY_OAUTH_RESPONSE"&&s.data.stateCode&&s.data.authorizationCode&&(n(s.data),a()),s.origin===x_&&s.data.ckSession&&(n({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:s.data.ckSession}),a()),s.data.type==="PRIVY_OAUTH_ERROR"&&(i(s.data.error),a()))}window.addEventListener("message",l)})}var _C=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});import{jsx as Er,jsxs as PC}from"react/jsx-runtime";var bo;function L_(e){return typeof e=="string"&&e.length===25}function Ee(){if(!bo){let e=j.get(bn);return Promise.resolve(e||null)}return bo.getAccessToken()}var AC,nf=(e,t,r)=>AC(e,t,r),xC,af=(e,t)=>xC(e,t),kC,sf=(e,t)=>kC(e,t),RC,lf=()=>RC(),IC,EC=()=>IC(),MC,TC=({message:e})=>MC({message:e}),N_=()=>{let t=new URLSearchParams(window.location.search).get("privy_token");if(!t)return;j.put(ma,t);let r=new URL(window.location.href);r.searchParams.delete("privy_token"),window.history.pushState({},"",r)},D_=({config:e,...t})=>{if(typeof window<"u"&&["localhost","127.0.0.1"].indexOf(window.location.hostname)<0&&window.location.protocol!=="https:")throw new w("Embedded wallet is only available over HTTPS");if(!L_(t.appId))throw new w("Cannot initialize the Privy provider with an invalid Privy app ID");bo||(bo=new _a({appId:t.appId,appClientId:t.clientId,apiUrl:t.apiUrl}));let r=Object.assign({},e);return t.createPrivyWalletOnLogin!==void 0&&r.embeddedWallets?.createOnLogin===void 0&&(r.embeddedWallets||(r.embeddedWallets={}),r.embeddedWallets.createOnLogin=t.createPrivyWalletOnLogin?"users-without-wallets":"off"),t.createPrivyWalletOnLogin!==void 0&&e?.embeddedWallets?.createOnLogin&&console.warn("Both `createPrivyWalletOnLogin` and `config.embeddedWallets.createOnLogin` are set. `createPrivyWalletOnLogin` is deprecated and should be removed."),Er(rh,{client:bo,clientConfig:r,legacyCreateEmbeddedWalletFlag:t.createPrivyWalletOnLogin,children:Er(U_,{...t,client:bo})})},U_=e=>{let t=e.client,[r,o]=ct(!1),[n,i]=ct(!1),[a,l]=ct(!1),[s,c]=ct(null),[m,f]=ct([]),[u,C]=ct(null),v=aa(m),[g,b]=ct(!1),[E,k]=ct(null),[_,S]=ct(!1),[R,M]=ct({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:T}),[D,H]=ct({status:"initial"}),[K,Y]=ct(null),[O,U]=ct(null),W=Ne(),be=hl(),[ce,X]=ct(!0),[ne,ee]=ct({}),[_e,xe]=ct(null),[je,Fe]=ct(null),[ft,Ze]=ct(!1),[de,Tr]=ct(!1),Lr=aa(null),Qr=aa(null),L=aa(fh),[ot,Nr]=ct(!1);t.onStoreToken=d=>{d&&F(L,"accessToken","onAccessTokenGranted",d)},t.onDeleteToken=()=>{c(null),l(!1),F(L,"accessToken","onAccessTokenRemoved")};let G=aa(null),V=aa(null),se=d=>{k(d),setTimeout(()=>{o(!0)},15),t.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:d}})},dt=d=>{W.embeddedWallets.createOnLogin!=="off"&&X(!0),se(d)};Zr(()=>{let d=kn(s);if(!d||!O){C(null);return}let p={address:d.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",meta:{name:"Privy Wallet",icon:Bo,id:"io.privy.solana.wallet"},getProvider:async()=>new md(O,d.address)};C(p)},[O,s]),Zr(()=>{if(!s){t.connectors?.removeEmbeddedWalletConnector();return}let d=ye(s),p=sl(s);if(d||t.connectors?.removeEmbeddedWalletConnector(),p||t.connectors?.removeImportedWalletConnector(),!t.connectors){console.debug("Failed to add embedded wallet connector: Client connectors not initialized");return}if(!O){console.debug("Failed to add embedded wallet connector: Wallet proxy not initialized");return}d&&t.connectors.addEmbeddedWalletConnector(O,d.address,W.defaultChain,e.appId),p&&t.connectors.addImportedWalletConnector(O,p.address,W.defaultChain,e.appId)},[O,s]),Zr(()=>{O&&je?.(O)},[O]),Zr(()=>{(async()=>{if(!W.customAuth?.enabled)return;X(!0);let{getCustomAccessToken:p,isLoading:h}=W.customAuth;if(!(!n||h))try{let y=await p();if(!y&&a){await ii.logout();return}if(!y||a)return;t.startAuthFlow(new si(y));let{user:x,isNewUser:N}=await t.authenticate();if(!x){await ii.logout();return}c(x||null),b(N||!1),l(!0),Tr(!0)}catch(y){console.warn(y),a&&await ii.logout()}})()},[W.customAuth?.enabled,W.customAuth?.getCustomAccessToken,W.customAuth?.isLoading,n,a]),Zr(()=>{de&&O&&s&&Lt(s,W.embeddedWallets.createOnLogin)&&(Tr(!1),fd(s,ci).catch(console.error))},[de&&O&&s]),Zr(()=>{async function d(){let p=sa(),h=ys();N_();let y=k_();t.initializeConnectorManager({walletConnectCloudProjectId:W.walletConnectCloudProjectId,rpcConfig:W.rpcConfig,chains:W.chains,defaultChain:W.defaultChain,store:y,walletList:W.appearance.walletList,shouldEnforceDefaultChainOnConnect:W.shouldEnforceDefaultChainOnConnect,externalWalletConfig:W.externalWallets,appName:W.name??"Privy"});let x;t.connectors?.on("connectorInitialized",()=>{x&&clearTimeout(x);let te=t.connectors.walletConnectors.length,oe=t.connectors.walletConnectors.reduce((Ve,Be)=>Ve+(Be.initialized?1:0),0);oe===te?Nr(!0):x=setTimeout(()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:oe,expected:te}),Nr(!0)},1500)}),t.connectors?.initialize().then(()=>{UC()});let N=await t.getAuthenticatedUser(),$=!!N;if(W.customAuth?.enabled||(l(!!N),N&&F(L,"login","onComplete",N,!1,!0,null,null),c(N)),p){V.current=$?"link":"login";return}if(h&&!$){V.current="login",dt("TELEGRAM_AUTH_SCREEN");return}re.setReadyToTrue(!!N)}!n&&be&&d()},[t,_e,n,be]),Zr(()=>{if(!n)return;if(!s){Ze(!0);return}if(!!!s.linkedAccounts.find(h=>h.type==="wallet"&&h.walletClientType==="privy")){Ze(!0);return}let p=!!m.find(h=>h.walletClientType==="privy");Ze(p)},[n,s,m]);let sa=()=>{let d=Ca();if(d.inProgress&&d.popupFlow){if(window.opener.location.origin!==window.location.origin){window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Origins between parent and child windows do not match."});return}if(d.authorizationCode==="error"){window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Something went wrong. Try again."});return}window.opener.postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:d.stateCode,authorizationCode:d.authorizationCode});return}let p="privy:";function h(y){return y.startsWith(p)}return d.inProgress&&h(d.provider)&&!d.popupFlow&&(new BroadcastChannel("popup-privy-oauth").postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:d.stateCode,authorizationCode:d.authorizationCode}),window.close()),!d.inProgress||d.headless?!1:(t.startAuthFlow(new Xr(d)),dt("AWAITING_OAUTH_SCREEN"),!0)},ys=()=>{let d=tf();if(!d||!W.loginMethods.telegram||!W.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let p=new mi;return t.startAuthFlow(p),d.flowType==="login-url"&&(p.meta.telegramWebAppData=void 0,p.meta.telegramAuthResult={id:d.id,first_name:d.first_name,last_name:d.last_name,auth_date:d.auth_date,username:d.username,photo_url:d.photo_url,hash:d.hash}),d.flowType==="web-app"&&(p.meta.telegramAuthResult=void 0,p.meta.telegramWebAppData={query_id:d.query_id,user:d.user,auth_date:d.auth_date,hash:d.hash}),!0},wu=async(d,p,h,y)=>{let x=await t.connectors?.createWalletConnector(d,p)||null;gs(x,p,h,y)};async function gs(d,p,h,y){if(d)M({status:"disconnected",connectedWallet:null,connectError:null,connector:d,connectRetry:T});else return M({status:"disconnected",connectedWallet:null,connectError:new pe("Unable to connect to wallet."),connector:null,connectRetry:T}),y?.(null,h);d instanceof Fr&&p&&await d.resetConnection(p),M({connector:d,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>gs(d,p,h,y)});try{let x=await d.connect({showPrompt:!0});if(W.shouldEnforceDefaultChainOnConnect&&!W.chains.find(N=>N.id===Number(x?.chainId.replace("eip155:","")))&&!(x?.connectorType==="wallet_connect_v2"&&x?.walletClientType==="metamask")){M(N=>({...N,connector:d,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:T}));try{await x?.switchChain(W.defaultChain.id),x&&(x.chainId=li(wn(W.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${W.defaultChain.id}`)}}return M(N=>({...N,status:"connected",connectedWallet:x,connectError:null,connectRetry:T})),x&&F(L,"connectWallet","onSuccess",x),y?.(x,h)}catch(x){return x instanceof tt?(console.warn(x.cause?x.cause:x.message),F(L,"connectWallet","onError",x.privyErrorCode||"generic_connect_wallet_error")):(console.warn(x),F(L,"connectWallet","onError","unknown_connect_wallet_error")),M(N=>({...N,status:"disconnected",connectedWallet:null,connectError:x})),y?.(null,h)}}let vs=async(d,p)=>{if(d===null)return;let h=new So(d,t,p);t.startAuthFlow(h)},UC=()=>{let d=new URLSearchParams(window.location.search),p=d.get("privy_connector"),h=d.get("privy_wallet_client");if(!p||!h)return;if(h==="phantom"&&!No()&&dt("LOGIN_FAILED_SCREEN"),!t.connectors)throw new w("Connector not initialized");se("AWAITING_CONNECTION");let y=new URL(window.location.href);y.searchParams.delete("privy_connector"),y.searchParams.delete("privy_wallet_client"),window.history.pushState({},"",y),wu(p,h,void 0,vs)};Zr(()=>{n&&a&&s===null&&t.getAuthenticatedUser().then(c)},[n,a,s,t]);let nt=d=>{if(!a)throw F(L,"linkAccount","onError","must_be_authenticated",{linkMethod:d}),new w("User must be authenticated before linking an account.")},bu=()=>{nt("siwe"),G.current="siwe",V.current="link",se("LINK_WALLET_SCREEN")},FC=d=>{if(!a||!s)return!1;if(d.walletClientType==="privy")return!0;for(let p of s.linkedAccounts)if(p.type==="wallet"&&p.address===d.address&&p.walletClientType!=="privy")return!0;return!1},BC=async d=>{if(!t.connectors)throw new w("Connector not initialized");let p=t.connectors.findWalletConnector(d.connectorType,d.walletClientType)||null;if(M(h=>({...h,connector:p,status:"connected",connectedWallet:d,connectError:null,connectRetry:T})),W.captchaEnabled&&!a){let h={callback:y=>vs(d,y),userIntentRequired:!1,onSuccessNavigateTo:"AWAITING_CONNECTION",onErrorNavigateTo:"ERROR_SCREEN"};ee({captchaModalData:h}),dt("CAPTCHA_SCREEN")}else await vs(d),dt("AWAITING_CONNECTION")},HC=async(d,p)=>{let{signedUrl:h,externalTransactionId:y}=await b1(t,d,p??{},W.appearance.palette,W.fundingMethodConfig?.moonpay.useSandbox??!1);return{signedUrl:h,externalTransactionId:y}},Cs=()=>{f(d=>{let p=t.connectors?.wallets.map(h=>({...h,linked:FC(h),loginOrLink:async()=>{if(!await h.isConnected())throw new w("Wallet is not connected");if(h.connectorType==="embedded"&&h.walletClientType==="privy")throw new w("Cannot link or login with embedded wallet");BC(h)},fund:async y=>{await re.fundWallet(h.address,y)},unlink:async()=>{if(!a)throw new w("User is not authenticated.");if(h.connectorType==="embedded"&&h.walletClientType==="privy")throw new w("Cannot unlink an embedded wallet");let y=await t.unlinkWallet(h.address);c(y)}}))||[];return ll(d,p)?d:p})};Zr(()=>{Cs()},[s?.linkedAccounts,a,n]),Zr(()=>{if(n){if(!t.connectors)throw new w("Connector not initialized");Cs(),t.connectors.on("walletsUpdated",Cs)}},[n]);let GC=d=>{if(d&&"suggestedAddress"in d&&d.suggestedAddress){let p=Oo(d.suggestedAddress);Y(p)}se(a?"CONNECT_ONLY_AUTHENTICATED_SCREEN":"CONNECT_ONLY_LANDING_SCREEN")};Zr(()=>{if(!m[0])return;let d=m[0],p=v.current.find(y=>y.address===d.address),h;if(d.walletClientType==="privy"?h=s?.linkedAccounts.find(y=>y.type==="wallet"&&y.address===d.address&&y.walletClientType==="privy"):h=s?.linkedAccounts.find(y=>y.type==="wallet"&&y.address===d.address&&y.walletClientType!=="privy"),!p&&h){let y=Object.assign({},s);y.wallet=h&&{address:h.address,chainType:h.chainType,chainId:h.chainId,walletClient:h.walletClient,walletClientType:h.walletClientType,connectorType:h.connectorType,imported:h.imported},c(y)}v.current=m},[m]);let fd=async(d,p)=>{if(ye(d))throw F(L,"createWallet","onError","embedded_wallet_already_exists"),new Error("Only one Privy wallet per user is currently allowed");let[y,x]=await Promise.all([re.initializeWalletProxy(p),Ee()]);if(!y&&W.customAuth?.enabled)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to connect to wallet proxy");if(!y||!x||W.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return new Promise((N,$)=>{X(!0),ee({createWallet:{onSuccess:oe=>{F(L,"createWallet","onSuccess",oe),N(oe)},onFailure:oe=>{F(L,"createWallet","onError","unknown_embedded_wallet_error"),$(oe)},callAuthOnSuccessOnClose:!1}}),se("EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN")});{await y.create({accessToken:x});let N=await re.refreshUser(),$=ye(N);if(!$)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to create wallet");return F(L,"createWallet","onSuccess",$),$}},VC=d=>{if(!W.chains.map(p=>p.id).includes(d))throw new pe(`Chain ID ${d} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,"unsupported_chain_id")},Eu=(d,p,h)=>new Promise(async(y,x)=>{let{requesterAppId:N}=p||{};if(!a||!s){F(L,"sendTransaction","onError","must_be_authenticated"),x(new Error("User must be authenticated before signing with a Privy wallet"));return}let $=d.from,te=$?s?.linkedAccounts.find(Qe=>Qe.type==="wallet"&&Qe.walletClientType==="privy"&&Oo(Qe.address)===Oo($)):ye(s);if(!te){F(L,"sendTransaction","onError","embedded_wallet_not_found"),x(new Error("Must have a Privy wallet before signing"));return}X(!0);let oe=t.connectors?.findWalletConnector("embedded","privy")?.proxyProvider,Ve=d.chainId?Number(d.chainId):oe.chainId;VC(Ve);let Be=Object.assign({},d,{chainId:Ve}),et=async()=>{let Qe=await Ee();if(!Qe||!O){F(L,"sendTransaction","onError","embedded_wallet_not_found"),x(new Error("Must have valid access token and Privy wallet to send transaction"));return}try{if(!await re.recoverEmbeddedEthereumWallet()){F(L,"sendTransaction","onError","unknown_connect_wallet_error"),x(new Error("Unable to connect to wallet"));return}let ai=qt(Be.chainId,W.chains,W.rpcConfig,{appId:e.appId}),Jr=await O_(te.address,Be,ai);if(W.embeddedWallets.noPromptOnSignature){let{totalGasEstimate:zC}=await W_(Jr,ai),{hasSufficientFunds:$C}=await Yi(te.address,Jr,zC,ai);if(!$C)throw new wt(new Pr("Wallet has insufficient funds for this transaction.",M_.E32603_DEFAULT_INTERNAL_ERROR.eipCode))}let Au=await lc(Qe,te.address,O,Jr,ai,N);F(L,"sendTransaction","onSuccess",Au),y(Au)}catch(bs){F(L,"sendTransaction","onError","transaction_failure"),x(bs)}};if(W.embeddedWallets.noPromptOnSignature)p&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config"),et();else{let Qe={transactionRequest:Be,onSuccess:Jr=>{F(L,"sendTransaction","onSuccess",Jr),y(Jr)},onFailure:Jr=>{F(L,"sendTransaction","onError","transaction_failure"),x(Jr)},uiOptions:p||{},fundWalletConfig:h,requesterAppId:N},bs={onCompleteNavigateTo:"EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN",onFailure:Jr=>{F(L,"sendTransaction","onError","unknown_connect_wallet_error"),x(Jr)}},ai=_u({address:te.address,fundWalletConfig:h,chainIdOverride:Be.chainId,comingFromSendTransactionScreen:!0});ee({connectWallet:bs,sendTransaction:Qe,funding:ai}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}});function Tu(){return new Promise(async(d,p)=>{let h=await Ee();if(!h||!O)throw new Error("Must have valid access token to enroll in MFA");try{await O.verifyMfa({accessToken:h}),d()}catch(y){p(y)}})}let Su=d=>d?.linkedAccounts.filter(p=>p.latestVerifiedAt!==null&&!(p.type==="wallet"&&p.walletClientType==="privy")).sort((p,h)=>h.latestVerifiedAt.getTime()-p.latestVerifiedAt.getTime())[0],Vt=d=>{let p=s?.linkedAccounts.filter(x=>x.type===d).length??0,{displayName:h,loginMethod:y}=sn(d);if(d==="passkey"&&p>=5||d!=="passkey"&&p>=1)throw F(L,"linkAccount","onError","cannot_link_more_of_type",{linkMethod:y}),new w(`User already has an account of type ${h} linked.`)},_u=({address:d,fundWalletConfig:p,methodScreen:h,chainIdOverride:y=null,comingFromSendTransactionScreen:x=!1})=>{if(!W.fundingConfig||W.fundingConfig.methods.length===0)return;let N=_c(p)&&p.amount?p.amount:W.fundingConfig.defaultRecommendedAmount,$=_c(p)&&p.chain?p.chain.id:ji(W.fundingConfig.defaultRecommendedCurrency.chain),te=_c(p)&&p.chain?p.chain:W.chains.find(oe=>oe.id===$);if(y&&W.chains.find(oe=>oe.id===y)&&(te=W.chains.find(oe=>oe.id===y)),!te)throw new w("Funding chain is not in PrivyProvider chains list");return{address:d,amount:N,chain:te,methodScreen:h,comingFromSendTransactionScreen:x,...w1(p)?{moonpayConfigOverride:p.config}:{}}};async function Pu({showAutomaticRecovery:d=!1,legacySetWalletPasswordFlow:p=!1}){k(null);let h=p?"setWalletPassword":"setWalletRecovery";if(!a||!s)throw F(L,h,"onError","must_be_authenticated"),new Error("User must be authenticated before adding recovery method to Privy wallet");let y=ye(s);if(!y||!O)throw F(L,h,"onError","embedded_wallet_not_found"),new Error("Must have a Privy wallet to add a recovery method");if(kn(s))throw new Error("Cannot set user-controlled recovery for user with Solana.");try{await Tu()}catch(N){throw F(L,h,"onError","missing_or_invalid_mfa"),N}return new Promise((N,$)=>{X(!0);let te={onSuccess:et=>{F(L,h,"onSuccess","user-passcode",et),N(et)},onFailure:et=>{F(L,h,"onError","user_exited_set_password_flow"),$(et)},callAuthOnSuccessOnClose:!1},oe=y.recoveryMethod==="user-passcode",Be={onCompleteNavigateTo:Fi({walletAction:"update",availableRecoveryMethods:W.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:p,isResettingPassword:oe,showAutomaticRecovery:d}),shouldForceMFA:!1,onFailure:et=>{F(L,h,"onError","unknown_connect_wallet_error"),$(et)}};ee({setWalletPassword:te,createWallet:te,connectWallet:Be,recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:oe}}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")})}async function ws({appId:d}){nt(`privy:${d}`),G.current=`privy:${d}`,V.current="link";let p=window.open(void 0,void 0,Va({w:440,h:680}));return t.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{appId:d}}),new Promise(async(h,y)=>{let{name:x,logoUrl:N}=await mc({api:t.api,providerAppId:d,requesterAppId:W.id});ee({crossAppAuth:{appId:d,name:x,logoUrl:N,popup:p,onSuccess:h,onError:y}}),dt("CROSS_APP_AUTH_SCREEN")})}let ii={ready:n,authenticated:a,user:s,walletConnectors:t.connectors||null,connectWallet:GC,importWallet:async({privateKey:d})=>{nt("siwe");let[p,h]=await Promise.all([re.initializeWalletProxy(15e3),Ee()]);if(p&&h){await p.import({privateKey:d,accessToken:h});let y=await re.refreshUser(),x=sl(y);if(!x)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to import wallet");return F(L,"createWallet","onSuccess",x),x}else throw new w("User is not authenticated")},linkWallet:bu,linkCrossAppAccount:ws,linkEmail:()=>{nt("email"),Vt("email"),G.current="email",V.current="link",se("LINK_EMAIL_SCREEN")},linkPhone:()=>{nt("sms"),Vt("phone"),G.current="sms",V.current="link",se("LINK_PHONE_SCREEN")},linkGoogle:async()=>{nt("google"),Vt("google_oauth"),V.current="link",await re.initLoginWithOAuth("google")},linkTwitter:async()=>{nt("twitter"),Vt("twitter_oauth"),V.current="link",await re.initLoginWithOAuth("twitter")},linkDiscord:async()=>{nt("discord"),Vt("discord_oauth"),V.current="link",await re.initLoginWithOAuth("discord")},linkGithub:async()=>{nt("github"),Vt("github_oauth"),V.current="link",await re.initLoginWithOAuth("github")},linkSpotify:async()=>{nt("spotify"),Vt("spotify_oauth"),V.current="link",await re.initLoginWithOAuth("spotify")},linkInstagram:async()=>{nt("instagram"),Vt("instagram_oauth"),V.current="link",await re.initLoginWithOAuth("instagram")},linkTiktok:async()=>{nt("tiktok"),Vt("tiktok_oauth"),V.current="link",await re.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{nt("linkedin"),Vt("linkedin_oauth"),V.current="link",await re.initLoginWithOAuth("linkedin")},linkApple:async()=>{nt("apple"),Vt("apple_oauth"),V.current="link",await re.initLoginWithOAuth("apple")},linkPasskey:async()=>{nt("passkey"),Vt("passkey"),await re.initLinkWithPasskey(),se("LINK_PASSKEY_SCREEN")},linkTelegram:async()=>{nt("telegram"),Vt("telegram"),V.current="link",G.current="telegram",await re.initLoginWithTelegram(),se("TELEGRAM_AUTH_SCREEN")},linkFarcaster:async()=>{nt("farcaster"),Vt("farcaster"),await re.initLoginWithFarcaster(),V.current="link",G.current="farcaster",se("AWAITING_FARCASTER_CONNECTION")},updateEmail:()=>{if(nt("email"),!s?.email)throw new w("User does not have an email linked to their account.");V.current="link",G.current="email",se("UPDATE_EMAIL_SCREEN")},updatePhone:()=>{if(nt("sms"),!s?.phone)throw new w("User does not have a phone number linked to their account.");V.current="link",G.current="sms",se("UPDATE_PHONE_SCREEN")},login:async d=>{d&&"target"in d&&d&&(d=void 0);let p="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!n){let h=await new Promise(y=>{xe(x=>y.bind(x))});if(xe(null),h){console.warn(p);return}}if(s&&!s.isGuest){console.warn(p);return}V.current="login",ee({login:d}),dt("LANDING")},connectOrCreateWallet:async()=>{if(n||(await new Promise(d=>{xe(()=>d)}),xe(null)),a){console.warn("User must be unauthenticated to `connectOrCreateWallet`");return}dt("CONNECT_OR_CREATE")},logout:async()=>{if(s&&t.clearProviderAcccessTokens(s),k(null),await t.logout(),s&&O)try{await O.clearMfa({userId:s.id})}catch{}c(null),l(!1),F(L,"logout","onSuccess"),V.current=null,G.current=null,o(!1),j.del(fa),j.del(qs(W.id))},getAccessToken:()=>t.getAccessToken(),getEthereumProvider:()=>{if(!s||!s.wallet)return new Ke;let d=m.find(h=>s.wallet&&h.address===s.wallet.address),p=t.connectors?.walletConnectors.find(h=>h.wallets.find(y=>y.address===d?.address));return!d||!p?new Ke:p.proxyProvider},getEthersProvider:()=>{if(!s||!s.wallet)return new Cu(new to(new Ke));let d=m.find(h=>s.wallet&&h.address===s.wallet.address),p=t.connectors?.walletConnectors.find(h=>h.wallets.find(y=>y.address===d?.address));return!d||!p?new Cu(new to(new Ke)):new Cu(new to(p.proxyProvider))},getWeb3jsProvider:()=>{if(!s||!s.wallet)return new Fo(new Ke);let d=m.find(h=>s.wallet&&h.address===s.wallet.address),p=t.connectors?.walletConnectors.find(h=>h.wallets.find(y=>y.address===d?.address));return!d||!p?new Fo(new Ke):new Fo(p.proxyProvider)},unlinkWallet:async d=>{let p=await t.unlinkWallet(d);return c(p),p},unlinkEmail:async d=>{let p=await t.unlinkEmail(d);return c(p),p},unlinkPhone:async d=>{let p=await t.unlinkPhone(d);return c(p),p},unlinkGoogle:async d=>{let p=await t.unlinkOAuth("google",d);return c(p),p},unlinkTwitter:async d=>{let p=await t.unlinkOAuth("twitter",d);return c(p),p},unlinkDiscord:async d=>{let p=await t.unlinkOAuth("discord",d);return c(p),p},unlinkGithub:async d=>{let p=await t.unlinkOAuth("github",d);return c(p),p},unlinkSpotify:async d=>{let p=await t.unlinkOAuth("spotify",d);return c(p),p},unlinkInstagram:async d=>{let p=await t.unlinkOAuth("instagram",d);return c(p),p},unlinkTiktok:async d=>{let p=await t.unlinkOAuth("tiktok",d);return c(p),p},unlinkLinkedIn:async d=>{let p=await t.unlinkOAuth("linkedin",d);return c(p),p},unlinkApple:async d=>{let p=await t.unlinkOAuth("apple",d);return c(p),p},unlinkFarcaster:async d=>{let p=await t.unlinkFarcaster(d);return c(p),p},unlinkTelegram:async d=>{let p=await t.unlinkTelegram(d);return c(p),p},unlinkPasskey:async d=>{let p=await t.unlinkPasskey(d);return c(p),p},unlinkCrossAppAccount:async({subject:d})=>{let p=s?.linkedAccounts.find(y=>y.type==="cross_app"&&y.subject===d)?.providerApp;if(!p)throw new w("Invalid subject");t.storeProviderAccessToken(p.id,null);let h=await t.unlinkOAuth(`privy:${p.id}`,d);return c(h),h},setActiveWallet:async d=>{let p=m.find(y=>Oo(y.address)===Oo(d)),h=s?.linkedAccounts.find(y=>y.type==="wallet"&&Oo(y.address)===Oo(d));if(!p||!await p.isConnected())Y(d),bu();else if(!p.linked)p.loginOrLink();else{let y=Object.assign({},s);y.wallet=h&&{address:h.address,chainType:h.chainType,chainId:h.chainId,walletClient:h.walletClient,walletClientType:h.walletClientType,connectorType:h.connectorType,imported:h.imported},c(y)}},forkSession:()=>t.forkSession(),createWallet:async()=>{if(!a||!s)throw F(L,"createWallet","onError","must_be_authenticated"),new Error("User must be authenticated before creating a Privy wallet");return fd(s,15e3)},setWalletRecovery:async d=>Pu({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:d?.showAutomaticRecovery??!1}),setWalletPassword:async()=>Pu({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(d,p,h)=>new Promise(async(y,x)=>{let{requesterAppId:N}=p||{};if(!a||!s){F(L,"signMessage","onError","must_be_authenticated"),x(new Error("User must be authenticated before signing with a Privy wallet"));return}let $=h?s?.linkedAccounts.find(oe=>oe.type==="wallet"&&oe.walletClientType==="privy"&&Oo(oe.address)===Oo(h)):ye(s);if(!$){F(L,"signMessage","onError","embedded_wallet_not_found"),x(new Error("Must have a Privy wallet before signing"));return}if(typeof d!="string"||d.length<1){F(L,"signMessage","onError","invalid_message"),x(new Error("Message must be a non-empty string"));return}X(!0);let te=async()=>{if(!a)throw new Error("User must be authenticated before signing with a Privy wallet");let oe=await Ee();if(!O||!oe)throw new Error("Unable to connect to wallet");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:$.address,requesterAppId:N}});let{response:Be}=await O.rpc({accessToken:oe,address:$.address,requesterAppId:N,request:{method:"personal_sign",params:[d,$.address]}}),et=Be.data;return t.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:$.address,requesterAppId:N}}),et};if(W.embeddedWallets.noPromptOnSignature){p&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let oe=await te();F(L,"signMessage","onSuccess",oe),y(oe)}catch(oe){F(L,"signMessage","onError","unable_to_sign"),x(oe??new wt("Unable to sign message"))}}else{let Be={method:"personal_sign",data:d,confirmAndSign:te,onSuccess:Qe=>{F(L,"signMessage","onSuccess",Qe),y(Qe)},onFailure:Qe=>{F(L,"signMessage","onError","unable_to_sign"),x(Qe)},uiOptions:p||{}},et={onCompleteNavigateTo:"EMBEDDED_WALLET_SIGN_REQUEST_SCREEN",onFailure:Qe=>{F(L,"signMessage","onError","unknown_connect_wallet_error"),x(Qe)},address:$.address};ee({signMessage:Be,connectWallet:et}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}}),signTypedData:(d,p)=>new Promise(async(h,y)=>{let{requesterAppId:x}=p||{};if(!a||!s){F(L,"signTypedData","onError","must_be_authenticated"),y(new Error("User must be authenticated before signing with a Privy wallet"));return}let N=ye(s);if(!N){F(L,"signTypedData","onError","embedded_wallet_not_found"),y(new Error("Must have a Privy wallet before signing"));return}X(!0);let $=pa(d),te=async()=>{if(!a)throw new Error("User must be authenticated before signing with a Privy wallet");let oe=await Ee();if(!O||!oe)throw new Error("Unable to connect to wallet");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:N.address,requesterAppId:x}});let{response:Be}=await O.rpc({accessToken:oe,address:N.address,requesterAppId:x,request:{method:"eth_signTypedData_v4",params:[N.address,$]}}),et=Be.data;return t.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:N.address,requesterAppId:x}}),et};if(W.embeddedWallets.noPromptOnSignature||(W.legacyWalletUiConfig??!1)){p&&console.warn("uiOptions defined with `noPromptOnSignature` set to true in app config");try{let oe=await te();F(L,"signTypedData","onSuccess",oe),h(oe)}catch(oe){F(L,"signTypedData","onError","unable_to_sign"),y(oe??new wt("Unable to sign message"))}}else{let Be={method:"eth_signTypedData_v4",data:$,confirmAndSign:te,onSuccess:Qe=>{F(L,"signTypedData","onSuccess",Qe),h(Qe)},onFailure:Qe=>{F(L,"signTypedData","onError","unable_to_sign"),y(Qe)},uiOptions:p||{}},et={onCompleteNavigateTo:"EMBEDDED_WALLET_SIGN_REQUEST_SCREEN",onFailure:Qe=>{F(L,"signMessage","onError","unknown_connect_wallet_error"),y(Qe)}};ee({signMessage:Be,connectWallet:et}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}}),sendTransaction:async(d,p,h)=>{let x=await(await Eu(d,p,h)).wait();return cc(x)},exportWallet:()=>new Promise(async(d,p)=>{if(!a||!s){p(new Error("User must be authenticated before exporting their Privy wallet"));return}if(!ye(s)){p(new Error("Must have a Privy wallet before exporting"));return}X(!0);let y={onCompleteNavigateTo:"EMBEDDED_WALLET_KEY_EXPORT_SCREEN",onFailure:p,shouldForceMFA:!0};if(ee(ne),!await Ee()||!O){p(new Error("Must have valid access token to enroll in MFA"));return}if(!O){p(new Error("Must have a Privy wallet before exporting"));return}let N={appId:e.appId,appClientId:e.clientId,origin:t.apiUrl,onSuccess:d,onFailure:p};ee({keyExport:N,connectWallet:y}),se("EMBEDDED_WALLET_CONNECTING_SCREEN")}),promptMfa:Tu,async init(d){switch(d){case"sms":await t.initMfaSmsVerification();return;case"passkey":return await t.initMfaPasskeyVerification();case"totp":return;default:throw new Error(`Unsupported MFA method: ${d}`)}},async submit(d,p){switch(d){case"totp":case"sms":if(typeof p!="string")throw new w("Invalid MFA code");Lr.current?.resolve({mfaMethod:d,mfaCode:p,relyingParty:window.origin}),await new Promise((N,$)=>{Qr.current={resolve:N,reject:$}});break;case"passkey":if(typeof p=="string")throw new w("Invalid authenticator response");let y=await(await import("@simplewebauthn/browser")).startAuthentication(p),x=_C(y);Lr.current?.resolve({mfaMethod:d,mfaCode:x,relyingParty:window.origin}),await new Promise((N,$)=>{Qr.current={resolve:N,reject:$}});break;default:throw Lr.current?.reject(new w("Unsupported MFA method")),new w(`Unsupported MFA method: ${d}`)}},cancel(){Lr.current?.reject(new w("MFA canceled"))},async initEnrollmentWithSms(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.initEnrollMfa({method:"sms",accessToken:p,phoneNumber:d.phoneNumber})},enrollInMfa(d){return new Promise((p,h)=>{if(!d){re.closePrivyModal(),p();return}W.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."),ee({mfaEnrollmentFlow:{mfaMethods:W.mfa.methods,onSuccess:p,onFailure:h}}),se("MFA_ENROLLMENT_FLOW_SCREEN")})},async initEnrollmentWithTotp(){let d=await Ee();if(!d||!O)throw new Error("Must have valid access token to enroll in MFA");let p=await O.initEnrollMfa({method:"totp",accessToken:d});return{secret:p.secret,authUrl:p.authUrl}},async submitEnrollmentWithSms(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.submitEnrollMfa({method:"sms",accessToken:p,phoneNumber:d.phoneNumber,code:d.mfaCode});let h=await t.getAuthenticatedUser();c(h)},async submitEnrollmentWithTotp(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.submitEnrollMfa({method:"totp",accessToken:p,code:d.mfaCode});let h=await t.getAuthenticatedUser();c(h)},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:d}){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to enroll in MFA");await O.submitEnrollMfa({method:"passkey",accessToken:p,credentialIds:d});let h=await t.getAuthenticatedUser();c(h)},async unenroll(d){let p=await Ee();if(!p||!O)throw new Error("Must have valid access token to remove MFA");d==="passkey"?await O.submitEnrollMfa({method:"passkey",accessToken:p,credentialIds:[]}):await O.unenrollMfa({method:d,accessToken:p});let h=await t.getAuthenticatedUser();c(h)},requestFarcasterSignerFromWarpcast:async()=>{let d=await Ee(),p=s?.linkedAccounts.find(x=>x.type==="wallet"&&x.walletClientType==="privy");if(!d)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!p)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");let y=await O.initFarcasterSigner({address:p.address,hdWalletIndex:null,accessToken:d,mfaCode:null,mfaMethod:null,relyingParty:window.origin});if(y.status==="approved"){let x=await t.getAuthenticatedUser();c(x||s||null)}ee({farcasterSigner:y}),se("AWAITING_FARCASTER_SIGNER")},getFarcasterSignerPublicKey:async()=>{let d=await Ee(),p=s?.linkedAccounts.find(x=>x.type==="wallet"&&x.walletClientType==="privy");if(!d)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!p)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");if(!s.farcaster?.signerPublicKey)throw new Error("Must have a Farcaster signer public key to sign");return(x=>Uint8Array.from(x.match(/.{1,2}/g).map(N=>parseInt(N,16))))(s.farcaster.signerPublicKey.slice(2))},signFarcasterMessage:async d=>{let p=await Ee(),h=s?.linkedAccounts.find($=>$.type==="wallet"&&$.walletClientType==="privy");if(!p)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!h)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");if(!await re.recoverEmbeddedEthereumWallet())throw new Error("Unable to connect to wallet");if(!s.farcaster?.signerPublicKey)throw new Error("Must have a Farcaster signer public key to sign");let x=await import("@simplewebauthn/browser"),N=await O.signFarcasterMessage({address:h.address,hdWalletIndex:null,accessToken:p,mfaCode:null,mfaMethod:null,payload:{hash:x.bufferToBase64URLString(d)},fid:BigInt(s.farcaster.fid),relyingParty:window.origin});return new Uint8Array(x.base64URLStringToBuffer(N.signature))},createGuestAccount:async()=>{if(s&&!s.isGuest)throw new Error("User cannot already be authenticated to create a guest account");return s?.isGuest?s:re.loginWithGuestAccountFlow()},isHeadlessOAuthLoading:_,loginWithCode(d){return re.loginWithCode(d)},initLoginWithEmail(d){return re.initLoginWithEmail(d)},initLoginWithSms(d){return re.initLoginWithSms(d)},otpState:D,fundWallet(d,p){return re.fundWallet(d,p)},initLoginWithHeadlessOAuth(d,p){return re.initLoginWithHeadlessOAuth(d,p)},loginWithHeadlessOAuth(d){return re.loginWithHeadlessOAuth(d)},generateSiweMessage({address:d,chainId:p}){return re.generateSiweMessage({address:d,chainId:p})},linkWithSiwe({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x}){return nt("siwe"),re.linkWithSiwe({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x})},signMessageWithCrossAppWallet(d,{address:p}){return fc({user:s,client:t,address:p,requesterAppId:W.id,request:{method:"personal_sign",params:[d,p]},reconnect:ws})},signTypedDataWithCrossAppWallet(d,{address:p}){let h=pa(d);return fc({user:s,client:t,address:p,requesterAppId:W.id,request:{method:"eth_signTypedData_v4",params:[p,h]},reconnect:ws})},sendTransactionWithCrossAppWallet(d,{address:p}){return fc({user:s,client:t,address:p,requesterAppId:W.id,request:{method:"eth_sendTransaction",params:[d]},reconnect:ws})},isModalOpen:r,mfaMethods:W.mfa.methods};AC=ii.signMessage,xC=ii.signTypedData,kC=async(...d)=>{let p=await Eu(...d);return W.embeddedWallets.waitForTransactionConfirmation&&await p.wait(),p};let re=(()=>({isNewUserThisSession:g,linkingOrConnectingHint:K,pendingTransaction:null,walletConnectionStatus:R,connectors:t.connectors?.walletConnectors??[],rpcConfig:W.rpcConfig,chains:W.chains,appId:e.appId,showFiatPrices:W.embeddedWallets.priceDisplay.primary!=="native-token",clientAnalyticsId:t.clientAnalyticsId,nativeTokenSymbolForChainId:d=>W.chains.find(p=>p.id===Number(d))?.nativeCurrency.symbol,initializeWalletProxy:async d=>{if(O)return O;let p=new Promise(x=>{Fe(()=>N=>x(N))}),h=new Promise(x=>setTimeout(()=>x(null),d)),y=await Promise.race([p,h]);return Fe(null),y},getAuthFlow:()=>t.authFlow,getAuthMeta:()=>t.authFlow?.meta,closePrivyModal:async(d={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let p=n&&a&&s,h;if(p&&G.current&&(h=Su(s)),V.current==="login"?d.shouldCallAuthOnSuccess&&p&&G.current?(F(L,"login","onComplete",s,g,!1,G.current,h??null),e.onSuccess?.(s,g)):F(L,"login","onError","exited_auth_flow"):V.current==="link"&&h&&(d.isSuccess&&p&&G.current?F(L,"linkAccount","onSuccess",s,G.current,h):G.current&&F(L,"linkAccount","onError","exited_link_flow",{linkMethod:G.current})),E&&Sv.includes(E)&&ne.funding){let y=_v[E]??null,x=qt(ne.funding.chain.id,W.chains,W.rpcConfig,{appId:e.appId}),N;try{N=(await x.getBalance(ne.funding.address)).toBigInt()}catch{console.error("Unable to pull wallet balance")}F(L,"fundWallet","onUserExited",{address:ne.funding.address,chain:ne.funding.chain,fundingMethod:y,balance:N})}Y(null),V.current=null,G.current=null,b(!1),o(!1),setTimeout(()=>{t.authFlow=void 0},200),t.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:async({message:d})=>new Promise(async(p,h)=>{let y=async()=>{let x=await t.getAccessToken();if(!x)throw new Error("User must be authenticated to use their embedded wallet.");if(!u)throw new Error("User must have an embedded Solana wallet to sign messages for Solana.");let N=re.walletProxy??await re.initializeWalletProxy(15e3);if(!N)throw new Error("Failed to initialize embedded wallet proxy.");let{response:$}=await N.rpcSolana({accessToken:x,publicKey:u.address,request:{method:"signMessage",params:{message:d}}});return $.data.signature};if(W.embeddedWallets.noPromptOnSignature)try{let x=await y();p({signature:x})}catch(x){h(x)}else ee({signMessage:{method:"solana_signMessage",data:d,confirmAndSign:y,onSuccess:te=>{p({signature:te})},onFailure:te=>{h(te)},uiOptions:{}}}),dt("EMBEDDED_WALLET_SIGN_REQUEST_SCREEN")}),openPrivyModal:se,connectWallet:gs,initLoginWithWallet:async(d,p)=>{G.current="siwe",vs(d,p)},loginWithWallet:async()=>{if(!n)throw new Eo;if(!(t.authFlow instanceof So))throw new w("Must initialize SIWE flow first.");let d,p;if(a)try{({user:d}=await t.link()),G.current="siwe"}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"failed_to_link_account",{linkMethod:"siwe"}),h}else try{({user:d,isNewUser:p}=await t.authenticate()),G.current="siwe"}catch(h){throw F(L,"login","onError",h.privyErrorCode||"generic_connect_wallet_error"),h}c(d||s||null),b(p||!1),l(!0)},initLoginWithFarcaster:async d=>{let p=new ua(d);t.startAuthFlow(p);try{G.current="farcaster",await p.initializeFarcasterConnect()}catch(h){throw V.current==="login"?F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",h.privyErrorCode||"unknown_auth_error",{linkMethod:"farcaster"}),h}},loginWithFarcaster:async()=>{if(!n)throw new Eo;if(!(t.authFlow instanceof ua))throw new w("Must initialize Farcaster flow first.");let d,p;if(a)try{({user:d}=await t.link()),G.current="farcaster"}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"failed_to_link_account",{linkMethod:"farcaster"}),h}else try{({user:d,isNewUser:p}=await t.authenticate()),G.current="farcaster"}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}c(d||null),b(p||!1),l(!0)},async loginWithGuestAccountFlow(){let d=new di(this.appId);t.startAuthFlow(d);try{V.current="login",G.current="guest";let p=await t.authenticate(),{user:h,isNewUser:y}=p;if(y=y||!1,!h)throw new w("Unable to authenticate guest account");if(Lt(h,W.embeddedWallets.createOnLogin))try{await fd(h,15e3),h=await re.refreshUser()}catch{c(h),console.warn("Unable to create embedded wallet for guest account")}else c(h);return b(y),l(!0),F(L,"login","onComplete",h,y,!1,"guest",null),h}catch(p){throw F(L,"login","onError",p.privyErrorCode||"unknown_auth_error"),p}},async crossAppAuthFlow({appId:d,popup:p}){let h=`privy:${d}`;G.current=h;let{url:y,stateCode:x,codeVerifier:N}=await Dg({api:t.api,appId:d});if(!y)throw t.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:d}}),new w("No authorization URL returned for cross-app auth.");try{let $=await SC({url:y,popup:p,provider:h}),te=$.stateCode,oe=$.authorizationCode;if(te!==x)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:h,storedStateCode:x??"",returnedStateCode:te??""}}),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected");let Ve=await Ug({api:bo.api,appId:d,codeVerifier:N,stateCode:te,authorizationCode:oe});Ve&&t.storeProviderAccessToken(d,Ve);let Be=await re.refreshUser();if(!Be)throw new w("Unable to update user");return t.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{appId:d}}),Be}catch($){throw t.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:$.toString(),provider:h}}),$}},async initLoginWithOAuth(d,p){if(G.current=d,la()){if(d==="google"&&Wi(window.navigator.userAgent)){dt("IN_APP_BROWSER_LOGIN_NOT_POSSIBLE");return}}else{dt("IN_APP_BROWSER_LOGIN_NOT_POSSIBLE");return}d==="twitter"&&window.opener&&window.opener.postMessage({type:"PRIVY_OAUTH_USE_BROADCAST_CHANNEL"},"*"),j.del(Sn);let h=new Xr({provider:d});p&&h.addCaptchaToken(p),t.startAuthFlow(h);let y=await t.authFlow.getAuthorizationUrl();y&&y.url&&(d==="twitter"&&I_&&(y.url=y.url.replace("x.com","twitter.com")),window.location.assign(y.url))},async initLoginWithTelegram(d){if(!n)throw new Eo;G.current="telegram";let p=new mi(d);t.startAuthFlow(p),p.meta.telegramWebAppData=void 0,p.meta.telegramAuthResult=await new Promise((h,y)=>{if(!W.loginConfig.telegramAuthConfiguration)return y(new w("Telegram Auth configuration is not loaded"));if(!window.Telegram)return y(new w("Telegram was not initialized"));window.Telegram.Login.auth({bot_id:W.loginConfig.telegramAuthConfiguration.botId,request_access:!0},x=>x?h(x):y(new w("Telegram auth failed or was canceled by the client")))})},async loginWithTelegram(){if(!(t.authFlow instanceof mi))throw new w("Must initialize Telegram flow before calling loginWithTelegram");let d,p;if(V.current==="login")try{let h=await t.authenticate();d=h.user,p=h.isNewUser,G.current="telegram"}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}else if(V.current==="link")try{d=(await t.link()).user,G.current="telegram"}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"failed_to_link_account",{linkMethod:"telegram"}),h}else throw new w("Unknown auth intent");c(d),b(p||!1),l(!0)},async recoveryOAuthFlow(d,p,h){let y,x;function N($){if(!$)throw t.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:d}}),new w("Recovery OAuth failed")}switch(d){case"google-drive":{let{url:$,codeVerifier:te,stateCode:oe}=await up({api:bo.api,provider:d});N($);let Ve,Be;try{let et=await vu({url:$,popup:h,provider:d});if(Ve=et.stateCode,Be=et.authorizationCode,Ve!==oe)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:d,storedStateCode:oe??"",returnedStateCode:Ve??""}}),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected")}catch(et){throw t.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:et.toString(),provider:d}}),new w("Recovery OAuth failed")}[y,x]=await Promise.all([Ee(),Ay({api:bo.api,provider:d,codeVerifier:te,stateCode:Ve,authorizationCode:Be})]);break}case"icloud":{let{url:$}=await up({api:bo.api,provider:d});N($);let{ckWebAuthToken:te}=await vu({url:$,popup:h,provider:d});x=te,y=await Ee();break}}if(!O)throw new w("Cannot connect to wallet proxy");if(!y)throw new w("Unable to authorize user");switch(p){case"recover":let $=ne.recoverWallet?.privyWallet?.address;if(!$)throw new w("Recovery OAuth failed");t.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:$,recoveryMethod:d}}),await O.recover({address:$,accessToken:y,recoveryAccessToken:x,recoveryMethod:d}),t.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:$,recoveryMethod:d}});break;case"create-wallet":t.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await O.create({accessToken:y,recoveryAccessToken:x,recoveryMethod:d});let te=await re.refreshUser(),oe=ye(te);if(!oe)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to create wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:oe.address}}),F(L,"createWallet","onSuccess",oe);break;case"set-recovery":let Ve=ye(s);if(!Ve)throw F(L,"setWalletRecovery","onError","embedded_wallet_not_found"),new Error("Embedded wallet not found");t.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:Ve.address,existingRecoveryMethod:Ve.recoveryMethod,targetRecoveryMethod:d}}),await O.setRecovery({address:Ve.address,accessToken:y,recoveryAccessToken:x,recoveryMethod:d});let Be=ye(await re.refreshUser());if(!Be)throw F(L,"createWallet","onError","unknown_embedded_wallet_error"),new Error("Failed to set recovery on wallet");t.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:Ve.address,existingRecoveryMethod:Ve.recoveryMethod,targetRecoveryMethod:d}}),F(L,"setWalletRecovery","onSuccess",d,Be);break;default:throw new w("Unsupported recovery action")}},async loginWithOAuth(d){if(!(t.authFlow instanceof Xr))throw new w("Must initialize OAuth flow before calling loginWithOAuth");let p=j.get(En),h=t.authFlow.meta.stateCode;if(p!==h)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:d,storedStateCode:p??"",returnedStateCode:h??""}}),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected");let y=await t.getAccessToken({disableAutoRefresh:!0}),x,N,$;if(a||y!==null)try{let te=await t.link();x=te.user,$=te.oAuthTokens,G.current=d}catch(te){throw F(L,"linkAccount","onError",te.privyErrorCode||"failed_to_link_account",{linkMethod:d}),te}else try{let te=await t.authenticate();x=te.user,N=te.isNewUser,$=te.oAuthTokens,G.current=d}catch(te){throw V.current==="login"?F(L,"login","onError",te.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",te.privyErrorCode||"failed_to_link_account",{linkMethod:d}),te}return c(x),b(N||!1),l(!0),$&&x&&F(L,"oAuthAuthorization","onOAuthTokenGrant",$,{user:x}),$},async initLoginWithPasskey(d){let p=new xn(d);t.startAuthFlow(p),V.current="login";try{G.current="passkey",await p.initAuthenticationFlow()}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}},async loginWithPasskey(){if(!n)throw new Eo;if(!(t.authFlow instanceof xn))throw new w("Must initialize Passkey flow first.");if(G.current!=="passkey")throw new w("Must init login with Passkey flow first.");let d,p;try{G.current="passkey",{user:d,isNewUser:p}=await t.authenticate()}catch(h){throw F(L,"login","onError",h.privyErrorCode||"unknown_auth_error"),h}c(d),b(p||!1),l(!0)},async initLinkWithPasskey(d){let p=new xn(d);t.startAuthFlow(p),V.current="link",G.current="passkey";try{await p.initLinkFlow()}catch(h){throw F(L,"linkAccount","onError",h.privyErrorCode||"unknown_auth_error",{linkMethod:"passkey"}),h}},async linkWithPasskey(){if(!n)throw new Eo;if(!(t.authFlow instanceof xn))throw new w("Must initialize Passkey flow first.");if(G.current!=="passkey")throw new w("Must init login with Passkey flow first.");let d;try{G.current="passkey",{user:d}=await t.link()}catch(p){throw F(L,"linkAccount","onError",p.privyErrorCode||"failed_to_link_account",{linkMethod:"passkey"}),p}return c(d||s||null),d},async initLoginWithHeadlessOAuth(d,p){if(la()){if(d==="google"&&Wi(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.")}else throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let h=new Xr({provider:d,headless:!0});p&&h.addCaptchaToken(p);let y=await t.startAuthFlow(h).getAuthorizationUrl();y?.url&&window.location.assign(y.url)},async loginWithHeadlessOAuth(d){S(!0),t.startAuthFlow(new Xr(d));let p=j.get(En),h=d.stateCode;if(p!==h)throw t.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:d.provider,storedStateCode:p??"",returnedStateCode:h??""}}),S(!1),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,"oauth_unexpected");let y,x;if(a)try{({user:y}=await t.link()),G.current=d.provider}catch(N){throw F(L,"linkAccount","onError",N.privyErrorCode||"failed_to_link_account",{linkMethod:d.provider}),N}else try{({user:y,isNewUser:x}=await t.authenticate()),G.current=d.provider}catch(N){throw V.current==="login"?F(L,"login","onError",N.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",N.privyErrorCode||"failed_to_link_account",{linkMethod:d.provider}),N}return c(y),b(x||!1),l(!0),S(!1),y??void 0},initLoginWithEmail:async(d,p)=>{let h=new Lo(d,p);t.startAuthFlow(h);try{G.current="email",await h.sendCodeEmail()}catch(y){throw V.current==="login"?F(L,"login","onError",y.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",y.privyErrorCode||"failed_to_link_account",{linkMethod:"email"}),y}},initUpdateEmail:async(d,p,h)=>{let y=new Is(d,p,h);t.startAuthFlow(y),await y.sendCodeEmail()},initUpdatePhone:async(d,p,h)=>{let y=new al(d,p,h);t.startAuthFlow(y),await y.sendSmsCode()},initLoginWithSms:async(d,p)=>{H({status:"sending-code"});let h=new Do(d,p);t.startAuthFlow(h);try{G.current="sms",await h.sendSmsCode(),H({status:"awaiting-code-input"})}catch(y){throw H({status:"error",error:y}),V.current==="login"?F(L,"login","onError",y.privyErrorCode||"unknown_auth_error"):V.current==="link"&&F(L,"linkAccount","onError",y.privyErrorCode||"failed_to_link_account",{linkMethod:"sms"}),y}},resendEmailCode:async()=>{await t.authFlow?.sendCodeEmail()},resendSmsCode:async()=>{await t.authFlow?.sendSmsCode()},loginWithCode:async d=>{if(H({status:"submitting-code"}),!n){let y=new Eo;throw H({status:"error",error:y}),y}if(t.authFlow instanceof Lo)t.authFlow.meta.emailCode=d.trim();else if(t.authFlow instanceof Do)t.authFlow.meta.smsCode=d.trim();else{let y=new w("Must initialize a passwordless code flow first");throw H({status:"error",error:y}),y}await Ee();let p,h;if(V.current==="link")try{({user:p}=await t.link())}catch(y){throw H({status:"error",error:y}),F(L,"linkAccount","onError",y.privyErrorCode||"failed_to_link_account",{linkMethod:G.current}),y}else try{({user:p,isNewUser:h}=await t.authenticate())}catch(y){throw H({status:"error",error:y}),F(L,"login","onError",y.privyErrorCode||"unknown_auth_error"),y}c(p||s||null),b(h||!1),l(!0),H({status:"done"})},generateSiweMessage:async({address:d,chainId:p,captchaToken:h})=>{V.current="link",G.current="siwe";let y=await t.generateSiweNonce({address:d,captchaToken:h}),x=p.replace("eip155:","");return il({address:d,chainId:x,nonce:y})},linkWithSiwe:async({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x})=>{let N;try{N=await t.linkWithSiwe({message:d,signature:p,chainId:h,walletClientType:y,connectorType:x}),N=await re.refreshUser()??N;let $=Su(N);$&&F(L,"linkAccount","onSuccess",N,"siwe",$)}catch($){throw F(L,"linkAccount","onError",$.privyErrorCode||"failed_to_link_account",{linkMethod:"siwe"}),V.current=null,G.current=null,$}c(N||s||null),V.current=null,G.current=null},refreshUser:async()=>{let d=await t.getAuthenticatedUser();return c(d),d},walletProxy:O,createAnalyticsEvent:({eventName:d,payload:p,timestamp:h})=>t.createAnalyticsEvent({eventName:d,payload:p,timestamp:h}),acceptTerms:async()=>{let d=await t.acceptTerms();return c(d),d},getUsdTokenPrice:d=>t.getUsdTokenPrice(d),recoverEmbeddedEthereumWallet:async d=>new Promise(async(p,h)=>{let y=ye(d?.user??s)||sl(d?.user??s),x=await Ee();if(!x||!O||!y){h(new Error("Must have valid access token and Privy wallet to recover wallet"));return}X(!0);try{await O.connect({accessToken:x,address:y.address}),p(!0)}catch(N){if(Hn(N)&&y.recoveryMethod==="privy")t.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:y.address}}),(await O.recover({address:y.address,accessToken:x,recoveryMethod:y.recoveryMethod})).address||h(new Error("Unable to recover wallet")),t.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:y.address}}),p(!0);else if(Hn(N)&&y.recoveryMethod!=="privy"){ee({recoverWallet:{privyWallet:y,onFailure:h,onSuccess:()=>p(!0)},recoveryOAuthStatus:{provider:y.recoveryMethod,action:"recover"}});let $=zl(y.recoveryMethod);se($)}else h(N)}}),embeddedSolanaWallet:u,createEmbeddedSolanaWallet:async()=>{X(!0);let d=await Ee(),p=await re.refreshUser(),h=kn(p),y=ye(p);if(!p||!d)throw new w("User must be logged in to create a Solana wallet");if(h)throw new w("User already has an embedded Solana wallet.");if(y)if(y.recoveryMethod==="privy")await re.recoverEmbeddedEthereumWallet({user:p});else throw new w("Cannot create an embedded Solana wallet for a user with an existing Ethereum wallet with user-controlled recovery.");let x=await re.initializeWalletProxy(15e3);if(!x)throw new w("Unable to initialize wallet proxy");t.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_started"});try{await x.createSolana({accessToken:d,ethereumAddress:y?.address});let N=await re.refreshUser(),$=kn(N);if(!$)throw new w("Could not get Solana wallet for user");return t.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_completed",payload:{walletAddress:$.address}}),$}catch(N){throw t.createAnalyticsEvent({eventName:"embedded_solana_wallet_creation_failed"}),new w("Failed to create Solana embedded wallet with error ",N)}},recoverEmbeddedSolanaWallet:async()=>new Promise(async(d,p)=>{let h=kn(s),y=await Ee();if(!y||!O||!h){p(new Error("Must have valid access token and Privy wallet to recover wallet"));return}X(!0);try{await O.connectSolana({accessToken:y,publicKey:h.address}),d(!0)}catch(x){Hn(x)&&h.recoveryMethod==="privy"?(t.createAnalyticsEvent({eventName:"embedded_solana_wallet_pinless_recovery_started",payload:{walletAddress:h.address}}),(await O.recoverSolana({publicKey:h.address,accessToken:y})).publicKey||p(new Error("Unable to recover wallet")),t.createAnalyticsEvent({eventName:"embedded_solana_wallet_recovery_completed",payload:{walletAddress:h.address}}),d(!0)):p(x)}}),getMoonpaySignedUrl:HC,initCoinbaseOnRamp:t.initCoinbaseOnRamp.bind(t),getCoinbaseOnRampStatus:t.getCoinbaseOnRampStatus.bind(t),setReadyToTrue:d=>{i(!0),_e?.(d)},updateWallets:()=>Cs(),fundWallet:async(d,p)=>{if(!W.fundingConfig||W.fundingConfig.methods.length===0)throw new Error("Wallet funding is not enabled");let h=ld({fundingMethods:W.fundingConfig.methods});ee({funding:_u({address:d,fundWalletConfig:p,methodScreen:h})}),se(h)},requestFarcasterSignerStatus:async d=>{let p=await Ee(),h=s?.linkedAccounts.find(x=>x.type==="wallet"&&x.walletClientType==="privy");if(!p)throw new Error("Must have valid access token to connect with Farcaster");if(!O||!h)throw new Error("Must have an embedded wallet to use Farcaster signers");if(!s?.farcaster?.fid)throw new Error("Must have Farcaster account to use Farcaster signers");let y=await t.requestFarcasterSignerStatus(d);if(y.status==="approved"){let x=await t.getAuthenticatedUser();c(x||s||null)}return y},connectCoinbaseSmartWallet:async()=>{W.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let d=t.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||t.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(d)return d.updateConnectionPreference("smartWalletOnly"),gs(d);await wu("coinbase_wallet","coinbase_smart_wallet")}}))();RC=re.recoverEmbeddedEthereumWallet,IC=re.recoverEmbeddedSolanaWallet,MC=re.solanaSignMessage;let qC=R_(()=>({wallets:m,ready:ft&&ot}),[m,ft,ot]);return Er(we.Provider,{value:ii,children:Er(Gd.Provider,{value:L,children:Er(xp.Provider,{value:qC,children:Er(ph,{...W,children:PC(Hd.Provider,{value:re,children:[Er(ly,{children:PC(nh,{data:ne,setModalData:ee,setInitialScreen:k,initialScreen:E,authenticated:a,open:r,children:[e.children,!W.headless&&W.captchaEnabled&&n&&!a&&Er(Bd,{delayedExecution:!1}),Er(sC,{theme:{...W.appearance.palette||{}}}),!W.render.standalone&&Er(yu,{open:r})]})}),ce&&be?Er(bC,{appId:e.appId,appClientId:e.clientId,clientAnalyticsId:t.clientAnalyticsId,origin:t.apiUrl,mfaMethods:s?.mfaMethods,mfaPromise:Lr,mfaSubmitPromise:Qr,onLoad:U,onLoadFailed:()=>null}):null,W.loginConfig.telegramAuthConfiguration&&Er(Hr,{if:!0,children:Er(vC,{scriptHost:e.apiUrl||Bs,botUsername:W.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};import{useContext as F_}from"react";function B_(e){let{login:t}=F_(we);return Pe("login",e),{login:t}}import{useContext as H_}from"react";function G_(e){let{logout:t}=H_(we);return Pe("logout",e),{logout:t}}import{useCallback as WC,useEffect as V_}from"react";function q_(){let e=Te(),t=hl(),{initLoginWithHeadlessOAuth:r,loginWithHeadlessOAuth:o,isHeadlessOAuthLoading:n,ready:i,user:a}=q(),l=WC(async c=>{if(e.enabled&&e.status!=="success")throw new ar(e.error,null,"captcha_failure");return r(c.provider,e.token)},[r,e]),s=WC(async()=>{let c=Ca();if(a)return console.warn("Cannot login with OAuth when already logged in"),a;if(!c.inProgress)throw new Error("Cannot login with OAuth because no OAuth flow is in progress");if(!c.popupFlow)try{return await o(c)}catch(m){throw m}finally{An()}},[o]);return V_(()=>{let c=Ca();i&&t&&c.inProgress&&c.headless&&!c.popupFlow&&s()},[i,t]),{initOAuth:l,loginWithOAuth:s,loading:n}}import{useCallback as OC}from"react";var z_=()=>{let e=Te(),{initLoginWithEmail:t,loginWithCode:r}=q(),o=OC(async({email:i})=>{if(!i)throw new Error("Email required to send OTP code");return t(i)},[t]),n=OC(async({code:i})=>{if(e.enabled&&e.status==="error")throw new ar(e.error,null,"captcha_failure");return r(i)},[r,e.status]);return{sendCode:o,loginWithCode:n}};import{useCallback as LC}from"react";var $_=()=>{let e=Te(),{initLoginWithSms:t,loginWithCode:r,otpState:o}=q(),n=LC(async({phoneNumber:a})=>{if(!a)throw new Error("SMS required to send OTP code");return t(a)},[t]),i=LC(async({code:a})=>{if(e.enabled&&e.status!=="success")throw new ar(e.error,null,"captcha_failure");return r(a)},[r,e.status]);return{sendCode:n,loginWithCode:i,state:o}};import{useCallback as NC}from"react";var K_=()=>{let e=Te(),{generateSiweMessage:t,linkWithSiwe:r}=q(),o=NC(async({address:i,chainId:a})=>{if(!i||!a)throw new Error("wallet address and chainId required to generate nonce");return t({address:i,chainId:a}).then(l=>l)},[t]),n=NC(async({signature:i,message:a,chainId:l,walletClientType:s,connectorType:c})=>{if(e.enabled&&e.status!=="success")throw new ar(e.error,null,"captcha_failure");return r({message:a,signature:i,chainId:l,walletClientType:s,connectorType:c})},[r,e.status]);return{generateSiweMessage:o,linkWithSiwe:n}};import{useContext as Y_}from"react";function j_(e){let{linkEmail:t,linkPhone:r,linkWallet:o,linkGoogle:n,linkApple:i,linkTwitter:a,linkDiscord:l,linkGithub:s,linkLinkedIn:c,linkTiktok:m,linkSpotify:f,linkInstagram:u,linkTelegram:C,linkFarcaster:v}=Y_(we);return Pe("linkAccount",e),{linkEmail:t,linkPhone:r,linkWallet:o,linkGoogle:n,linkApple:i,linkTwitter:a,linkDiscord:l,linkGithub:s,linkLinkedIn:c,linkTiktok:m,linkSpotify:f,linkInstagram:u,linkFarcaster:v,linkTelegram:C}}import{useContext as Z_}from"react";function Q_(e){let{connectWallet:t}=Z_(we);return Pe("connectWallet",e),{connectWallet:t}}import{useContext as J_}from"react";function X_(e){let{createWallet:t}=J_(we);return Pe("createWallet",e),{createWallet:t}}var eP=e=>{Pe("fundWallet",e);let{fundWallet:t}=q();return{fundWallet:t}};var tP=()=>{let{embeddedSolanaWallet:e,createEmbeddedSolanaWallet:t}=I();return{createWallet:t,wallets:e?[e]:[]}};var rP=()=>{let{connectCoinbaseSmartWallet:e}=I();return{connectCoinbaseSmartWallet:e}};var oP=()=>{let{linkCrossAppAccount:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:o,sendTransactionWithCrossAppWallet:n}=q();return{linkCrossAppAccount:e,unlinkCrossAppAccount:t,signMessage:r,signTypedData:o,sendTransaction:n}};import{useContext as nP}from"react";function iP(e){let{sendTransaction:t}=nP(we);return Pe("sendTransaction",e),{sendTransaction:t}}import{useContext as aP}from"react";function sP(e){let{setWalletPassword:t}=aP(we);return Pe("setWalletPassword",e),{setWalletPassword:t}}import{useContext as lP}from"react";function cP(){let{createGuestAccount:e}=lP(we);return{createGuestAccount:e}}import{useContext as dP}from"react";function pP(e){let{setWalletRecovery:t}=dP(we);return Pe("setWalletRecovery",e),{setWalletRecovery:t}}import{useContext as uP}from"react";function mP(e){let{signMessage:t}=uP(we);return Pe("signMessage",e),{signMessage:t}}import{useContext as fP}from"react";function hP(e){let{signTypedData:t}=fP(we);return Pe("signTypedData",e),{signTypedData:t}}import{useContext as yP}from"react";var gP=()=>{let{isModalOpen:e}=yP(we);return{isOpen:e}};import{useContext as vP}from"react";function CP(e){let{getAccessToken:t}=vP(we);return Pe("accessToken",e),{getAccessToken:t}}function wP(e){let{authenticated:t,user:r}=q(),{initLoginWithOAuth:o}=I(),n=Ti();return Pe("oAuthAuthorization",e),{reauthorize:i=>bP(t,r,o,n,i.provider)}}var bP=async(e,t,r,o,n)=>{if(!e)throw o("linkAccount","onError","must_be_authenticated",{linkMethod:n}),new w("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some(a=>a.type.includes(n)))throw new w(`OAuth account of type ${n} not linked to the account.`);await r(n)};var EP=DC;function DC(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=q();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}}function TP(e,t){return{...e,rpcUrls:{...e.rpcUrls,privyWalletOverride:{http:[t]}}}}function SP(e){return e.find(r=>r.walletClientType==="privy"&&r.connectorType==="embedded"&&!r.imported)??null}export{to as AsExternalProvider,Bd as Captcha,Sa as ConnectorManager,yu as LoginModal,_a as PrivyClient,D_ as PrivyProvider,Ke as PrivyProxyProvider,Ea as SUPPORTED_CHAINS,Ed as VERSION,Kt as WalletConnector,TP as addRpcUrlOverrideToChain,dp as errorIndicatesMaxMfaRetries,Gn as errorIndicatesMfaTimeout,Vn as errorIndicatesMfaVerificationFailed,Ee as getAccessToken,SP as getEmbeddedConnectedWallet,rP as useConnectCoinbaseSmartWallet,Q_ as useConnectWallet,X_ as useCreateWallet,oP as useCrossAppAccounts,EP as useExperimentalFarcasterSigner,DC as useFarcasterSigner,eP as useFundWallet,cP as useGuestAccounts,j_ as useLinkAccount,K_ as useLinkWithSiwe,B_ as useLogin,z_ as useLoginWithEmail,q_ as useLoginWithOAuth,$_ as useLoginWithSms,G_ as useLogout,es as useMfa,Kr as useMfaEnrollment,gP as useModalStatus,wP as useOAuthTokens,q as usePrivy,Vd as useRegisterMfaListener,iP as useSendTransaction,sP as useSetWalletPassword,pP as useSetWalletRecovery,mP as useSignMessage,hP as useSignTypedData,tP as useSolanaWallets,CP as useToken,$r as useWallets};