@privy-io/js-sdk-core 0.79.3 → 0.79.4

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.
@@ -1,4 +1,4 @@
1
- import{encoding as e}from"@privy-io/encoding";import{AcceptCardConsents as t,AcceptTermsOnUser as n,AnalyticsEvent as r,AppConfig as i,CoinbaseOnRampInit as a,CoinbaseOnRampStatus as o,CreateCard as s,CreateCryptoDepositAccount as c,CreateCryptoDepositAccountQuote as l,CreateDepositAddressQuote as u,CustomJWTAuthenticate as d,CustomJWTLink as f,DownloadCardStatement as p,FarcasterAuthenticate as m,FarcasterInit as h,FarcasterLink as ee,FarcasterStatus as te,FarcasterUnlink as ne,FarcasterV2Authenticate as re,FarcasterV2Init as ie,GetCardCustomer as ae,GetCardEphemeralKey as oe,GetCardsConfig as se,GetCrossAppConnections as ce,GetCryptoDepositAccountNextOrder as le,GetCryptoDepositAccountOrder as ue,GetDepositAddressOrder as de,GetDepositConfig as fe,GetNextDepositAddressOrder as pe,GetSmartWalletConfig as me,GuestAuthenticate as he,ListCardTransactions as ge,ListCards as _e,Logout as ve,MfaPasskeyInit as ye,MfaPasswordlessSmsInit as be,MoonpayOnRampSign as xe,OAuthAuthenticate as Se,OAuthInit as Ce,OAuthLink as we,OAuthUnlink as Te,PasskeyAuthenticate as Ee,PasskeyAuthenticateInit as De,PasskeyLink as Oe,PasskeyLinkInit as ke,PasskeyRegister as Ae,PasskeyRegisterInit as je,PasswordlessAuthenticate as Me,PasswordlessInit as Ne,PasswordlessLink as Pe,PasswordlessSmsAuthenticate as Fe,PasswordlessSmsInit as Ie,PasswordlessSmsLink as Le,PasswordlessSmsUnlink as Re,PasswordlessSmsUpdate as ze,PasswordlessUnlink as Be,PasswordlessUpdate as Ve,RecoveryConfigurationICloud as He,RecoveryKeyMaterial as Ue,RecoveryOAuthAuthenticate as We,RecoveryOAuthInit as Ge,RecoveryOAuthInitICloud as Ke,RefreshSession as qe,RefreshUser as Je,ReplaceCard as Ye,SearchCryptoDepositAccountConfig as Xe,SiweAuthenticate as Ze,SiweInit as Qe,SiweLink as $e,SiweLinkSmartWallet as et,SiweUnlink as tt,SiwsAuthenticate as nt,SiwsInit as rt,SiwsLink as it,SiwsUnlink as at,TelegramAuthenticate as ot,TelegramLink as st,TelegramUnlink as ct,UpdateCard as lt,UpdateCardPin as ut,UpsertCardCustomer as dt,WalletCreate as ft,WalletGet as pt,WalletGetAction as mt,WalletListActions as ht,WalletRawSign as gt,WalletRpc as _t,WalletTransfer as vt,WalletUpdate as yt,WalletsRevoke as bt,getPathWithParams as xt}from"@privy-io/routes";import*as St from"jose";import{DEFAULT_SUPPORTED_CHAINS as Ct,arbitrum as g,arbitrumSepolia as wt,avalanche as _,avalancheFuji as Tt,base as v,baseSepolia as Et,celo as Dt,dedupeSupportedChains as Ot,mainnet as y,monadMainnet as b,optimism as x,optimismSepolia as kt,polygon as S,polygonAmoy as At,sepolia as jt,tempo as Mt,tempoTestnet as Nt}from"@privy-io/chains";import{base58 as Pt}from"@scure/base";import Ft from"eventemitter3";import{concat as It,createPublicClient as Lt,decodeAbiParameters as Rt,decodeFunctionResult as zt,encodeFunctionData as Bt,erc20Abi as Vt,formatEther as Ht,formatUnits as Ut,http as Wt,isAddress as Gt,isHex as Kt,maxUint256 as qt,stringToHex as Jt,toHex as Yt,zeroAddress as Xt}from"viem";import{STRING_TO_NUMBER_TXN_TYPE as Zt,TEMPO_TXN_TYPE_NUMBER as Qt,isTempoTransactionRequest as C,normalizeViemPreparedTempoTransaction as $t,toViemTempoTransactionSerializable as en,toViemTransactionSerializable as tn}from"@privy-io/ethereum";import nn from"canonicalize";import{PrivyErrorCode as rn}from"@privy-io/api-base";import{retryFetch as an}from"@privy-io/std/retry-fetch";import on from"js-cookie";import sn from"fetch-retry";import cn from"libphonenumber-js/examples.mobile.json";import{AsYouType as ln,getCountries as un,getCountryCallingCode as dn,getExampleNumber as fn,isPossiblePhoneNumber as pn,parsePhoneNumberFromString as mn}from"libphonenumber-js/min";export*from"@privy-io/chains";var hn=Object.defineProperty,w=(e,t)=>{let n={};for(var r in e)hn(n,r,{get:e[r],enumerable:!0});return t||hn(n,Symbol.toStringTag,{value:`Module`}),n};function gn(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}const _n=e=>/^0x[0-9a-fA-F]*$/.test(e),vn=t=>`0x${e.hex.fromBytes(t)}`,yn=t=>_n(t)?t:vn(e.utf8.toBytes(t)),bn=Symbol(`data-suffix-plugin`);function xn(e=[]){return e.find(e=>e.id===bn)}function Sn(e){let t=e.startsWith(`0x`)?e:`0x${e}`;if(!_n(t))throw Error(`[Privy] dataSuffix: Invalid suffix "${e}" is not valid hex`);let n=t.slice(2);return{id:bn,suffix:t,appendDataSuffix:({data:e})=>!e||e===`0x`?t:`${e}${n}`}}var Cn=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(me,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},T=class extends Error{name=`PrivyApiError`;error;code;status;constructor({error:e,code:t,status:n}){super(e),this.error=e,this.code=t,this.status=n}},E=class extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}},wn=class extends Error{error;code;response;constructor({error:e,code:t,response:n}){super(e),this.code=t,this.error=e,this.response=n}};function Tn(e){return e instanceof T||e instanceof E?e.code:`unknown_error`}const En=e=>t=>e[Tn(t)]??e.default;function Dn(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}var D=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=St.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=(this.expiration-e)*1e3}},On=class e{_storage;_privyInternal;constructor(e,t){this._privyInternal=e,this._storage=t}static providerAccessTokenStorageKey=e=>`privy:cross-app:${e}`;async updateOnCrossAppAuthentication(t,n){let r=n.access_token,i=D.parse(r);if(!i||i.issuer!==`privy:${t}`)throw new E({code:`cross_app_invalid_app`,error:`Cross-app token issuer does not match the provider app.`});let a=e.providerAccessTokenStorageKey(t);await this._storage.put(a,r)}async getProviderAccessToken(t){let n=e.providerAccessTokenStorageKey(t),r=await this._storage.get(n);if(typeof r!=`string`)return null;try{let e=new D(r);return e.isExpired()||e.issuer!==`privy:${t}`?(await this._storage.del(n),null):r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(ce,{params:{app_id:this._privyInternal.appId}})}},kn=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(bt,{})}};const O=e=>!!e.id&&e.recovery_method===`privy-v2`;var An=class{_proxy;_privyInternal;_account;_entropyId;_entropyIdVerifier;constructor({proxy:e,privyInternal:t,account:n,entropyId:r,entropyIdVerifier:i}){this._proxy=e,this._privyInternal=t,this._account=n,this._entropyId=r,this._entropyIdVerifier=i}async sign({message:e}){return await this.request({method:`sign`,params:{message:new TextDecoder(`utf8`).decode(e)}})}async signTransaction({psbt:e}){return await this.request({method:`signTransaction`,params:{psbt:e}})}async request(e){if(O(this._account))throw new E({code:`unsupported_wallet_type`,error:`Bitcoin wallet providers are only supported for on-device execution and this app uses TEE execution. Use the useSignRawHash hook from @privy-io/expo/extended-chains to sign over a hash with this wallet. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide`});if(!await this._privyInternal.getAccessTokenInternal())throw new E({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return this.handleIFrameRpc(e)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing access token. User must be authenticated.`);return(await this._proxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:this._account.chain_type})).response.data}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedBitcoinProvider { address: '${this._account.address}', request: [Function] }`}},jn=class{callbacks={};enqueue(e,t){this.callbacks[e]=t}flush(e){let t=Object.values(this.callbacks);this.callbacks={};for(let{reject:n}of t)n(e)}dequeue(e,t){let n=this.callbacks[t];if(!n)return console.warn(`[Privy] No callback found for "${e}" (id: ${t})`),null;switch(delete this.callbacks[t],e){case`privy:iframe:ready`:return n;case`privy:wallets:create`:return n;case`privy:user-signer:sign`:return n;case`privy:wallets:add`:return n;case`privy:wallets:set-recovery`:return n;case`privy:wallets:connect`:return n;case`privy:wallets:recover`:return n;case`privy:wallets:rpc`:return n;case`privy:wallets:import`:return n;case`privy:wallet:create`:return n;case`privy:wallet:connect`:return n;case`privy:wallet:recover`:return n;case`privy:wallet:rpc`:return n;case`privy:solana-wallet:create`:return n;case`privy:solana-wallet:create-additional`:return n;case`privy:solana-wallet:connect`:return n;case`privy:solana-wallet:recover`:return n;case`privy:solana-wallet:rpc`:return n;case`privy:delegated-actions:consent`:return n;case`privy:mfa:verify`:return n;case`privy:mfa:init-enrollment`:return n;case`privy:mfa:submit-enrollment`:return n;case`privy:mfa:unenroll`:return n;case`privy:mfa:clear`:return n;case`privy:auth:unlink-passkey`:return n;default:throw Error(`invalid wallet event type ${e}`)}}};const Mn=[`error`,`invalid_request_arguments`,`wallet_not_on_device`,`invalid_recovery_pin`,`insufficient_funds`,`mfa_timeout`,`missing_or_invalid_mfa`,`mfa_verification_max_attempts_reached`];let Nn=function(e){return e.MISSING_OR_INVALID_PRIVY_APP_ID=`missing_or_invalid_privy_app_id`,e.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID=`missing_or_invalid_privy_account_id`,e.INVALID_DATA=`invalid_data`,e.LINKED_TO_ANOTHER_USER=`linked_to_another_user`,e.ALLOWLIST_REJECTED=`allowlist_rejected`,e.OAUTH_USER_DENIED=`oauth_user_denied`,e.UNKNOWN_AUTH_ERROR=`unknown_auth_error`,e.USER_EXITED_AUTH_FLOW=`exited_auth_flow`,e.MUST_BE_AUTHENTICATED=`must_be_authenticated`,e.UNKNOWN_CONNECT_WALLET_ERROR=`unknown_connect_wallet_error`,e.GENERIC_CONNECT_WALLET_ERROR=`generic_connect_wallet_error`,e.CLIENT_REQUEST_TIMEOUT=`client_request_timeout`,e.INVALID_CREDENTIALS=`invalid_credentials`,e}({});var Pn=class extends Error{cause;privyErrorCode;constructor(e,t,n){super(e),t instanceof Error&&(this.cause=t),this.privyErrorCode=n}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:``}: ${this.message}${this.cause?` [cause: ${this.cause}]`:``}`}},Fn=class extends Pn{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},In=class extends Error{type;constructor(e,t){super(t),this.type=e}},Ln=class extends Pn{type=`connector_error`;constructor(e,t,n){super(e,t,n)}},Rn=class extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}};const k={UNKNOWN_ERROR:{eipCode:0,message:`Unknown error`,detail:`Unknown error`,retryable:!0},E4001_DEFAULT_USER_REJECTED_REQUEST:{eipCode:4001,message:`User Rejected Request`,detail:`The user rejected the request.`,default:!0,retryable:!0},E4100_DEFAULT_UNAUTHORIZED:{eipCode:4100,message:`Unauthorized`,detail:`The requested method and/or account has not been authorized by the user.`,default:!0,retryable:!1},E4200_DEFAULT_UNSUPPORTED_METHOD:{eipCode:4200,message:`Unsupported Method`,detail:`The Provider does not support the requested method.`,default:!0,retryable:!1},E4900_DEFAULT_DISCONNECTED:{eipCode:4900,message:`Disconnected`,detail:`The Provider is disconnected from all chains.`,default:!0,retryable:!0},E4901_DEFAULT_CHAIN_DISCONNECTED:{eipCode:4901,message:`Chain Disconnected`,detail:`The Provider is not connected to the requested chain.`,default:!0,retryable:!0},E32700_DEFAULT_PARSE_ERROR:{eipCode:-32700,message:`Parse error`,detail:`Invalid JSON`,default:!0,retryable:!1},E32600_DEFAULT_INVALID_REQUEST:{eipCode:-32600,message:`Invalid request`,detail:`JSON is not a valid request object`,default:!0,retryable:!1},E32601_DEFAULT_METHOD_NOT_FOUND:{eipCode:-32601,message:`Method not found`,detail:`Method does not exist`,default:!0,retryable:!1},E32602_DEFAULT_INVALID_PARAMS:{eipCode:-32602,message:`Invalid params`,detail:`Invalid method parameters`,default:!0,retryable:!1},E32603_DEFAULT_INTERNAL_ERROR:{eipCode:-32603,message:`Internal error`,detail:`Internal JSON-RPC error`,default:!0,retryable:!0},E32000_DEFAULT_INVALID_INPUT:{eipCode:-32e3,message:`Invalid input`,detail:`Missing or invalid parameters`,default:!0,retryable:!1},E32001_DEFAULT_RESOURCE_NOT_FOUND:{eipCode:-32001,message:`Resource not found`,detail:`Requested resource not found`,default:!0,retryable:!1},E32002_DEFAULT_RESOURCE_UNAVAILABLE:{eipCode:-32002,message:`Resource unavailable`,detail:`Requested resource not available`,default:!0,retryable:!0},E32003_DEFAULT_TRANSACTION_REJECTED:{eipCode:-32003,message:`Transaction rejected`,detail:`Transaction creation failed`,default:!0,retryable:!0},E32004_DEFAULT_METHOD_NOT_SUPPORTED:{eipCode:-32004,message:`Method not supported`,detail:`Method is not implemented`,default:!0,retryable:!1},E32005_DEFAULT_LIMIT_EXCEEDED:{eipCode:-32005,message:`Limit exceeded`,detail:`Request exceeds defined limit`,default:!0,retryable:!1},E32006_DEFAULT_JSON_RPC_VERSION_NOT_SUPPORTED:{eipCode:-32006,message:`JSON-RPC version not supported`,detail:`Version of JSON-RPC protocol is not supported`,default:!0,retryable:!1},E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:`Connection request already pending`,detail:`Don’t see your wallet? Check your other browser windows.`,retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:`Resource request already pending`,detail:`Don’t see your wallet? Check your other browser windows.`,retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:`Wallet might be locked`,detail:`Unlock your wallet and try again.`,retryable:!0},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:`Signature rejected`,detail:`Please try signing again.`,retryable:!0}};function A(e){let t=e.type;return typeof t==`string`&&Mn.includes(t)}function zn(e){return A(e)&&e.type===`wallet_not_on_device`}function Bn(e){return A(e)&&e.type===`mfa_timeout`}function Vn(e){return A(e)&&e.type===`missing_or_invalid_mfa`}function Hn(e){return A(e)&&e.type===`mfa_verification_max_attempts_reached`}function Un(e){return A(e)&&e.message.includes(`code 429`)}var Wn=class extends Fn{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(k).find(e=>e.eipCode===t.code);this.details=n||k.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=k.E32002_CONNECTION_ALREADY_PENDING:this.details=k.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=k.E32002_WALLET_LOCKED))}};async function Gn(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new In(`missing_or_invalid_mfa`,`MFA verification failed, retry.`)),await e(await new Promise((e,r)=>{t.current={resolve:e,reject:r},setTimeout(()=>{let e=new In(`mfa_timeout`,`Timed out waiting for MFA code`);n.current?.reject(e),r(e)},o)}))):await e(),l=null;for(let e=0;e<a;e++)try{l=await c(e),n.current?.resolve(void 0);break}catch(e){if(e.type===`missing_or_invalid_mfa`)s=!0;else throw n.current?.resolve(void 0),e}if(l===null){let e=new In(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function Kn(e){return e.error!==void 0}const qn=(function(e){return()=>`id-${e++}`})(0),Jn=(e,t)=>typeof t==`bigint`?t.toString():t,Yn=(e,t)=>`${e}${JSON.stringify(t,Jn)}`,j=async(e,{ms:t,msg:n})=>{let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t??15e3)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}},Xn=new jn;var Zn=class{ready;_waitForReadyPromise=null;cache;_embeddedWalletMessagePoster;mfa;constructor(e,t){this.ready=!1,this.cache=new Map,this._embeddedWalletMessagePoster=e,this.mfa=t}invokeWithMfa(e,t){return j(Gn(n=>j(this.waitForReady().then(()=>e(n)),{msg:t.timeoutMsg,ms:t.timeoutMs}),this.mfa.rootPromise,this.mfa.submitPromise,()=>this.mfa.emit(`mfaRequired`),t.mfaAlwaysRequired??!1,4,3e5),{msg:`Operation reached timeout: MFA verification`,ms:126e4})}reload(){return this.ready=!1,this._waitForReadyPromise=null,Xn.flush(Error(`Embedded wallet WebView was reloaded`)),this.cache.clear(),this._embeddedWalletMessagePoster.reload()}retarget(e){e!==this._embeddedWalletMessagePoster&&(this._embeddedWalletMessagePoster=e,this.ready=!1)}onBackground(){this.ready=!1}ping(e=15e3){return j(this.invoke(`privy:iframe:ready`,{}),{msg:`Ping reached timeout`,ms:e})}create(e){return j(this.waitForReady().then(()=>this.invoke(`privy:wallet:create`,e)),{msg:`Operation reached timeout: create`})}rpc(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallet:rpc`,{...t,...e}),{timeoutMsg:`Operation reached timeout: rpc`})}createSolana(e){return this.invokeWithMfa(t=>this.invoke(`privy:solana-wallet:create`,{...t,...e}),{timeoutMsg:`Operation reached timeout: create`,timeoutMs:6e4})}createAdditionalSolana(e){return j(this.waitForReady().then(()=>this.invoke(`privy:solana-wallet:create-additional`,e)),{msg:`Operation reached timeout: create`})}solanaRpc(e){return this.invokeWithMfa(t=>this.invoke(`privy:solana-wallet:rpc`,{...t,...e}),{timeoutMsg:`Operation reached timeout: solana-rpc`})}delegateWallets(e){return this.invokeWithMfa(t=>this.invoke(`privy:delegated-actions:consent`,{...t,...e}),{timeoutMsg:`Operation reached timeout: delegated-actions:consent`})}verifyMfa(e){return this.invokeWithMfa(t=>this.invoke(`privy:mfa:verify`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:verify`,mfaAlwaysRequired:!0})}initEnrollMfa(e){return this.invokeWithMfa(t=>this.invoke(`privy:mfa:init-enrollment`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:init-enrollment`})}submitEnrollMfa(e){return e.method===`passkey`?this.invokeWithMfa(t=>this.invoke(`privy:mfa:submit-enrollment`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:submit-enrollment`}):j(this.waitForReady().then(()=>this.invoke(`privy:mfa:submit-enrollment`,e)),{msg:`Operation reached timeout: mfa:submit-enrollment`})}unenrollMfa(e){return this.invokeWithMfa(t=>this.invoke(`privy:mfa:unenroll`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:unenroll`,mfaAlwaysRequired:!0})}unlinkPasskey(e){return this.invokeWithMfa(t=>this.invoke(`privy:auth:unlink-passkey`,{...t,...e}),{timeoutMsg:`Operation reached timeout: auth:unlink-passkey`,mfaAlwaysRequired:!0})}clearMfa(e){return j(this.waitForReady().then(()=>this.invoke(`privy:mfa:clear`,e)),{msg:`Operation reached timeout: mfa:clear`})}createWallet(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:create`,{...t,...e}),{timeoutMsg:`Operation reached timeout: create`,timeoutMs:6e4})}signWithUserSigner(e){return this.invokeWithMfa(t=>this.invoke(`privy:user-signer:sign`,{...t,...e}),{timeoutMsg:`Operation reached timeout: user-signer:sign`})}addWallet(e){return j(this.waitForReady().then(()=>this.invoke(`privy:wallets:add`,e)),{msg:`Operation reached timeout: wallets:add`})}importWallet(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:import`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:import`,timeoutMs:6e4})}setRecovery(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:set-recovery`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:set-recovery`,timeoutMs:6e4})}connect(e){return j(this.waitForReady().then(()=>this.invoke(`privy:wallets:connect`,e)),{msg:`Operation reached timeout: wallets:connect`})}recover(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:recover`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:recover`,timeoutMs:6e4})}rpcWallet(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:rpc`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:rpc`})}handleEmbeddedWalletMessages(e){if(!e.event.startsWith(`privy:`)){console.warn(`Unsupported event type: ${e.event}`);return}let t=Xn.dequeue(e.event,e.id);if(t)return Kn(e)?t.reject(new In(e.error.type,e.error.message)):t.resolve(e.data)}waitForReady(){return this.ready?Promise.resolve():(this._waitForReadyPromise||=new Promise((e,t)=>{(async()=>{for(let t=0;t<100&&!this.ready;t++)this.invoke(`privy:iframe:ready`,{}).then(()=>{this.ready=!0,this._waitForReadyPromise=null,e()}).catch(()=>{}),await new Promise(e=>setTimeout(e,150));this.ready||(this._waitForReadyPromise=null,t(Error(`Embedded wallet WebView failed to become ready`)))})()}),this._waitForReadyPromise)}invoke(e,t){let n=Yn(e,t);if(e===`privy:wallet:create`||e===`privy:solana-wallet:create`){let e=this.cache.get(n);if(e)return e}let r=new Promise((n,r)=>{let i=qn();Xn.enqueue(i,{resolve:n,reject:r}),this._embeddedWalletMessagePoster.postMessage(JSON.stringify({id:i,event:e,data:t}),`*`)}).finally(()=>{this.cache.delete(n)});return this.cache.set(n,r),r}};function Qn({transaction:e,address:t}){let{messageBytes:n,signerAddresses:r}=er(e),i=r.indexOf(t);if(i===-1)throw Error(`Transaction does not require a signature from ${t}`);return{messageBytes:new Uint8Array(n),signerIndex:i}}function $n({transaction:e,signerIndex:t,signature:n}){if(n.length!==64)throw Error(`Solana signatures must be 64 bytes`);let{signaturesOffset:r,signerAddresses:i}=er(e);if(!Number.isInteger(t)||t<0||t>=i.length)throw Error(`Invalid signer index ${t}`);let a=new Uint8Array(e);return a.set(n,r+t*64),a}function er(e){if(e.length===0)throw Error(`Cannot decode an empty Solana transaction`);return e[0]===129?tr(e):nr(e)}function tr(e){let t=M(e,1),n=e.length-t*64;if(n<=41)throw Error(`Malformed V1 Solana transaction`);let r=e.subarray(0,n);if(M(r,41)<t)throw Error(`Malformed V1 Solana transaction`);return{messageBytes:r,signaturesOffset:n,signerAddresses:ir(r,42,t)}}function nr(e){let[t,n]=rr(e,0),r=n+t*64,i=M(e,r),a=r;if(i&128){let e=i&-129;if(e!==0)throw Error(`Unsupported Solana transaction version ${e}`);a+=1}let o=M(e,a);if(o!==t)throw Error(`Solana transaction signature count does not match its message header`);let[s,c]=rr(e,a+3);if(s<o)throw Error(`Malformed Solana transaction`);return{messageBytes:e.subarray(r),signaturesOffset:n,signerAddresses:ir(e,c,o)}}function M(e,t){let n=e[t];if(n===void 0)throw Error(`Malformed Solana transaction`);return n}function rr(e,t){let n=0;for(let r=0;r<3;r++){let i=M(e,t+r);if(n|=(i&127)<<7*r,!(i&128))return[n,t+r+1]}throw Error(`Malformed Solana transaction`)}function ir(e,t,n){if(t+n*32>e.length)throw Error(`Malformed Solana transaction`);return Array.from({length:n},(n,r)=>Pt.encode(e.subarray(t+r*32,t+(r+1)*32)))}function ar(e){return`version`in e}function or(e,t){let n=(ar(e)?e.message:e.compileMessage()).staticAccountKeys.find(e=>e.toBase58()===t);if(!n)throw Error(`Transaction does not contain public key ${t}`);return n}var sr=class{_privyInternal;_account;constructor({privyInternal:e,account:t}){this._privyInternal=e,this._account=t}async request(e){if(!await this._privyInternal.getAccessTokenInternal())throw new E({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});switch(e.method){case`signAndSendTransaction`:return await this.handleSignAndSendTransaction(e);case`signTransaction`:return await this.handleSignTransaction(e);default:return await this.handleIFrameRpc(e)}}get _publicKey(){return this._account.address}async signTransactionObject(t,n){if(ar(t)&&t.version===1)throw Error(`V1 transactions cannot be serialized by web3.js. Pass the serialized transaction as a Uint8Array instead.`);let r=or(t,this._account.address),i=ar(t)?t.message.serialize():t.serializeMessage(),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:e.base64.fromBytes(i)}},n);t.addSignature(r,e.base64.toBytes(a))}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.prepare(t),await this.signMessageRpc(e,t)}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n})}}async handleSignAndSendTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.prepare(t);let{transaction:n,connection:r,options:i}=e.params,a;return n instanceof Uint8Array?a=await this.signSerializedTransaction(n,t):(await this.signTransactionObject(n,t),a=n.serialize()),{signature:await r.sendRawTransaction(a,i)}}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n})}}async handleSignTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.prepare(t);let{transaction:n}=e.params;return n instanceof Uint8Array?{signedTransaction:await this.signSerializedTransaction(n,t)}:(await this.signTransactionObject(n,t),{signedTransaction:n})}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},cr=class extends sr{_proxy;_entropyId;_entropyIdVerifier;_onNeedsRecovery;constructor({proxy:e,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:r,...i}){super(i),this._proxy=e,this._entropyId=t,this._entropyIdVerifier=n,this._onNeedsRecovery=r}async prepare(e){try{await this._proxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:e})}catch(t){let n=zn(t);if(n&&this._account.recovery_method===`privy`)await this._proxy.recover({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:e});else if(n&&this._onNeedsRecovery){let e;await new Promise(async(t,n)=>{e=setTimeout(()=>n(new E({code:`embedded_wallet_recovery_error`,error:`User-owned recovery timed out`})),12e4),await this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>t(!0)})}).finally(()=>clearTimeout(e))}else throw t}}async signMessageRpc(e,t){return(await this._proxy.rpcWallet({accessToken:t,request:e,chainType:`solana`,hdWalletIndex:this._account.wallet_index,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier})).response.data}async signSerializedTransaction(t,n){let{messageBytes:r,signerIndex:i}=Qn({transaction:t,address:this._account.address}),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:e.base64.fromBytes(r)}},n);return $n({transaction:t,signerIndex:i,signature:e.base64.toBytes(a)})}};let N;async function lr(){if(!N){let{tempo:e,tempoModerato:t}=await import(`./tempoChains-CJGgHPcv.mjs`);N={tempo:e,tempoModerato:t}}return N}function ur(){return N!==void 0}const dr=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new Ln(`Unsupported chainId ${e}`,4901);let o=pr(a,n,r.appId);if(fr(i)){if(!N)throw new Ln(`Tempo chains are not loaded for chainId ${e}; await loadTempoChains() first`,4901);let t=i===Mt.id?N.tempo:N.tempoModerato;return Lt({transport:Wt(o),chain:t})}return Lt({transport:Wt(o),chain:a})};function fr(e){return e===Mt.id||e===Nt.id}const pr=(e,t,n)=>{let r=e.id,i=Number(e.id),a;if(e.rpcUrls.privyWalletOverride&&e.rpcUrls.privyWalletOverride.http[0])a=e.rpcUrls.privyWalletOverride.http[0];else if(t.rpcUrls&&t.rpcUrls[i])a=t.rpcUrls[i];else if(e.rpcUrls.privy?.http[0]){let t=new URL(e.rpcUrls.privy.http[0]);t.searchParams.append(`privyAppId`,n),a=t.toString()}else a=e.rpcUrls.public?.http[0]?e.rpcUrls.public.http[0]:e.rpcUrls.default?.http[0];if(!a)throw new Ln(`No RPC url found for ${r}`);return a};function mr({currentRecoveryMethod:e,upgradeToRecoveryMethod:t}){switch(e){case`privy`:case`user-passcode`:case`recovery-encryption-key`:return!0;case`icloud`:case`google-drive`:if(e===t)throw Error(`Cannot upgrade to the existing cloud platform`);return!0;default:throw Error(`Unknown recovery method`)}}const hr=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var gr=class extends Ft{_privyInternal;_account;_chainId;_chains;_client;_clientReady;_appApi;_dataSuffixPlugin;constructor({privyInternal:e,account:t,chains:n,chainId:r=n[0].id,appApi:i,dataSuffixPlugin:a}){super(),this._privyInternal=e,this._account=t,this._chainId=r,this._chains=n,this.updateClient(i.appId),this._appApi=i,this._dataSuffixPlugin=a}async request(e){if(await this.awaitClientReady(),hr.has(e.method))return this.handleIFrameRpc(e);switch(e.method){case`eth_accounts`:case`eth_requestAccounts`:return this._account.address?[this._account.address]:[];case`eth_chainId`:return`0x${this._chainId.toString(16)}`;case`wallet_switchEthereumChain`:return this.handleSwitchEthereumChain(e);case`eth_estimateGas`:return this.handleEstimateGas(e);case`eth_signTransaction`:{let t=this.applyDataSuffix(e.params?.[0]);return this.handleSignTransaction(t)}case`eth_sendTransaction`:{let t=this.applyDataSuffix(e.params?.[0]);return this.handleSendTransaction(t)}case`eth_populateTransactionRequest`:{let t=e.params?.[0];return this.handlePopulateTransaction(t)}default:return this.handleJsonRpc(e)}}applyDataSuffix(e){if(!this._dataSuffixPlugin||C(e))return e;let t=typeof e.data==`string`?e.data:`0x`;return{...e,data:this._dataSuffixPlugin.appendDataSuffix({data:t})}}async ensureChainId(e){let t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),await this.awaitClientReady(),t}async awaitClientReady(){for(;this._clientReady;){let e=this._clientReady;await e,this._clientReady===e&&(this._clientReady=void 0)}}internalSwitchEthereumChain(e){!e||Number(e)===this._chainId||(this._chainId=Number(e),this.updateClient(this._privyInternal.appId),this.emit(`chainChanged`,e))}updateClient(e){let t=this._chainId,n=()=>dr(t,this._chains,{rpcUrls:[]},{appId:e});if(!fr(t)||ur()){this._client=n(),this._clientReady=void 0;return}let r=lr().then(()=>{this._chainId===t&&(this._client=n())});this._clientReady=r,r.catch(()=>{})}async handlePopulateTransaction(e){let t=await this.ensureChainId(e);if(C(t)){let e=en(t),n=$t(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:Qt}}let n=tn(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:Zt[i.type],authorizationList:t.authorizationList}}async handleSignTransaction(e){let t={...e};for(let e of Object.keys(t)){let n=t[e];typeof n==`bigint`&&(t[e]=Yt(n))}return C(t)&&(t.calls=t.calls.map(e=>({...e,value:typeof e.value==`bigint`?Yt(e.value):e.value}))),await this.handleIFrameRpc({method:`eth_signTransaction`,params:[t]})}async handleSendTransaction(e){let t=await this.handlePopulateTransaction(e),n=await this.handleSignTransaction(t);return await this.handleJsonRpc({method:`eth_sendRawTransaction`,params:[n]})}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error(`Invalid params for eth_estimateGas`);let t=e.params?.[0],n=await this.ensureChainId(t);if(C(n)){let e=en(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=tn(n);return await this._client.estimateGas({account:n.from??this._account.address,...r})}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new Rn(`Invalid params for ${e.method}`,4200);let t;if(typeof e.params[0]==`string`)t=e.params[0];else if(`chainId`in e.params[0]&&typeof e.params[0].chainId==`string`)t=e.params[0].chainId;else throw new Rn(`Invalid params for ${e.method}`,4200);this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.signWithWallet(e,t)}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n})}}async handleJsonRpc(e){return this._client.request(e)}requireTempoClient(){if(!fr(this._chainId))throw new Rn(`Cannot send a Tempo (type 118) transaction on chain ${this._chainId}`,4901);return this._client}toJSON(){return`PrivyEIP1193Provider { address: '${this._account.address}', chainId: ${this._chainId}, request: [Function] }`}},_r=class extends gr{_walletProxy;_entropyId;_entropyIdVerifier;_onNeedsRecovery;constructor({walletProxy:e,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:r,...i}){super(i),this._walletProxy=e,this._entropyId=t,this._entropyIdVerifier=n,this._onNeedsRecovery=r}async signWithWallet(e,t){try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t})}catch(e){let n=zn(e);if(n&&this._account.recovery_method===`privy`)await this._walletProxy.recover({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t});else if(n&&this._onNeedsRecovery){let e;await new Promise(async(t,n)=>{e=setTimeout(()=>n(new E({code:`embedded_wallet_recovery_error`,error:`User-owned recovery timed out`})),12e4),await this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>t(!0)})}).finally(()=>clearTimeout(e))}else throw e}return(await this._walletProxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:`ethereum`})).response.data}};async function P(t,n){let r;if(n instanceof Uint8Array)r=e.base64.fromBytes(n);else{let t=nn(n);if(t===void 0)throw new E({error:`Failed to prepare the payload for signing`,code:`invalid_input`});r=e.base64.fromBytes(e.utf8.toBytes(t))}let{signature:i}=await t({message:r});return{signature:i}}const F=`privy-request-expiry`,I=1800*1e3;async function L(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath(_t,{params:{wallet_id:n}}),o=String(Date.now()+I),{signature:s}=await P(t,{version:1,url:a,method:_t.method,headers:{"privy-app-id":e.app.appId,[F]:o},body:{...i}});if(Date.now()>Number(o))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(_t,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[F]:o,...r??{}}})}function vr(e){return C(e)?br(e):yr(e)}function yr(e){return{from:e.from,to:e.to??void 0,nonce:R(e.nonce),chain_id:R(e.chainId),data:wr(e.data),value:R(e.value),type:Er(e.type),gas_limit:R(e.gasLimit??e.gas),gas_price:R(e.gasPrice),max_fee_per_gas:R(e.maxFeePerGas),max_priority_fee_per_gas:R(e.maxPriorityFeePerGas),authorization_list:e.authorizationList?.map(e=>{let t=e.yParity??(e.v===void 0?0:Number(e.v)-27);if(t!==0&&t!==1)throw Error(`EIP-7702 authorizations require a valid yParity value`);return{contract:e.address,chain_id:Or(e.chainId,`chainId`),nonce:Or(e.nonce,`nonce`),r:e.r,s:e.s,y_parity:t}})}}function br(e){return{type:Qt,from:e.from,chain_id:R(e.chainId),nonce:R(e.nonce),nonce_key:R(e.nonceKey),gas_limit:R(e.gasLimit),max_fee_per_gas:R(e.maxFeePerGas),max_priority_fee_per_gas:R(e.maxPriorityFeePerGas),fee_token:e.feeToken,valid_after:R(e.validAfter),valid_before:R(e.validBefore),fee_payer_signature:Sr(e.feePayerSignature),access_list:xr(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:R(e.value)}))}}function xr(e){if(e)return Array.isArray(e)?e.map(e=>`address`in e?{address:e.address,storage_keys:[...e.storageKeys]}:{address:e[0],storage_keys:[...e[1]]}):Object.entries(e).map(([e,t])=>({address:e,storage_keys:[...t]}))}function Sr(e){if(!e)return;let t=Cr(e);if(t!==0&&t!==1)throw Error(`Tempo fee payer signatures require a valid yParity value`);return{r:e.r,s:e.s,y_parity:t}}function Cr(e){if(e.yParity!==void 0)return e.yParity;if(e.v!==void 0)return Number(e.v)-27}function wr(e){if(e!==void 0)return typeof e==`string`?yn(e):vn(Uint8Array.from(e))}const Tr=[0,2,4];function Er(e){if(e==null)return;let t=Number(e);if(!Dr(t))throw Error(`Invalid transaction type: expected ${Tr.join(`, `)} as a number or hex string, got "${e}".`);return t}function Dr(e){return Tr.includes(e)}function R(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(_n(e))return e;throw Error(`Invalid quantity string: expected a hex-prefixed value (0x…), got "${e}". Use a number, bigint, or hex string instead.`)}}function Or(e,t){let n=R(e);if(n===void 0)throw Error(`EIP-7702 authorization ${t} is required`);return n}function kr(e){return typeof e==`string`&&(e=JSON.parse(e)),{types:e.types,primary_type:String(e.primaryType),domain:e.domain,message:e.message}}async function Ar({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return jr({context:e,account:t,rpcRequest:n.request});case`solana`:return Mr({context:e,account:t,rpcRequest:n.request})}}async function jr({context:e,account:t,rpcRequest:n}){switch(n.method){case`personal_sign`:{let[r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:`personal_sign`,wallet_id:t.id,params:r.startsWith(`0x`)?{message:r.slice(2),encoding:`hex`}:{message:r,encoding:`utf-8`}});if(i.method!==`personal_sign`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`eth_signTransaction`:{let[r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:`eth_signTransaction`,wallet_id:t.id,params:{transaction:vr(r)}});if(i.method!==`eth_signTransaction`)throw Error(`Unable to sign transaction`);return{data:i.data.signed_transaction}}case`eth_signTypedData_v4`:{let[,r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:n.method,wallet_id:t.id,params:{typed_data:kr(r)}});if(i.method!==`eth_signTypedData_v4`)throw Error(`Unable to sign typed data`);return{data:i.data.signature}}case`eth_sign`:{let[,r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:yn(r)}});if(i.method!==`secp256k1_sign`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`secp256k1_sign`:{let[r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:yn(r)}});if(i.method!==`secp256k1_sign`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`csw_signUserOperation`:case`eth_sendTransaction`:case`eth_populateTransactionRequest`:throw Error(`This wallet does not support the method: ${n.method}`)}}async function Mr({context:e,account:t,rpcRequest:n}){switch(n.method){case`signMessage`:{let{message:r}=n.params,i=await L(e,e.signRequest,{chain_type:`solana`,method:`signMessage`,wallet_id:t.id,params:{message:r,encoding:`base64`}});if(i.method!==`signMessage`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`signTransaction`:{let{transaction:r}=n.params,i=await L(e,e.signRequest,{chain_type:`solana`,method:`signTransaction`,wallet_id:t.id,params:{transaction:r,encoding:`base64`}});if(i.method!==`signTransaction`)throw Error(`Unable to sign transaction`);return{data:i.data.signed_transaction}}}}var Nr=class extends sr{_app;_signRequest;constructor({app:e,signRequest:t,...n}){super(n),this._app=e,this._signRequest=t}async prepare(){}async signMessageRpc(e){let{data:t}=await Ar({context:this.walletRpcContext(),account:this._account,rpcRequest:{chainType:`solana`,request:e}});return{signature:t}}async signSerializedTransaction(t){let{data:n}=await Ar({context:this.walletRpcContext(),account:this._account,rpcRequest:{chainType:`solana`,request:{method:`signTransaction`,params:{transaction:e.base64.fromBytes(t)}}}});return new Uint8Array(e.base64.toBytes(n))}walletRpcContext(){return{app:this._app,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:this._signRequest}}},Pr=class extends gr{_signRequest;constructor({signRequest:e,...t}){super(t),this._signRequest=e}async signWithWallet(e){let{data:t}=await Ar({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:this._signRequest},account:this._account,rpcRequest:{chainType:`ethereum`,request:e}});return t}};async function Fr(e,{request:t,headers:n}){return await e.fetchPrivyRoute(ft,{body:t,headers:n})}async function Ir({context:e,chainType:t,idempotencyKey:n}){return{wallet:await Fr(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}var Lr=class{_privyInternal;_proxy;_chains=Array.from(Ct);_mfa;_mfaPromises;_appApi;_dataSuffixPlugin;_signRequest=e=>this.signWithUserSigner(e);constructor(e,t,n,r,i,a,o){if(this._privyInternal=e,t&&(this._proxy=new Zn(t,i),r.setProxy(this._proxy)),n){let e=Ot(n);this._chains=e}this._mfa=r,this._mfaPromises=i,this._appApi=a,this._dataSuffixPlugin=o}setMessagePoster(e){if(this._proxy){this._proxy.retarget(e);return}this._proxy=new Zn(e,this._mfaPromises),this._mfa.setProxy(this._proxy)}async signWithUserSigner(e){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new E({error:`User must be logged in to sign a message with the user signer`,code:`user_signer_sign_error`});let{signature:n}=await this._proxy.signWithUserSigner({accessToken:t,message:e.message});return{signature:n}}async add(e){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await Ir({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:e.chainType});else{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(!e.entropyId)throw new E({error:`Missing entropy details for wallet creation`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new E({error:`User must be logged in to create an embedded wallet`,code:`embedded_wallet_creation_error`});await this._proxy.addWallet({accessToken:t,...e})}let{user:t}=await this._privyInternal.refreshSession();return{user:t}}async getBitcoinProvider({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(!await this._privyInternal.getAccessTokenInternal())throw Error(`User must be logged in to create an embedded wallet`);return O(e)||await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new An({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n})}async create({password:e,recoveryMethod:t,recoveryToken:n,recoveryKey:r,recoverySecretOverride:i,iCloudRecordNameOverride:a,solanaAccount:o,skipCallbacks:s,idempotencyKey:c}){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`){if(t&&!t.startsWith(`privy`))throw new E({error:`User-controlled server wallets do not support custom recovery methods`,code:`embedded_wallet_creation_error`});await Ir({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`ethereum`,idempotencyKey:c})}else{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let s;if(s=t||(e?`user-passcode`:`privy`),e&&typeof e!=`string`)throw Error(`Invalid recovery password, must be a string`);if(s===`privy`&&this._privyInternal.config?.embedded_wallet_config.require_user_password_on_create)throw Error(`Password not provided yet is required by App configuration`);let c=await this._privyInternal.getAccessTokenInternal();if(!c)throw Error(`User must be logged in to create an embedded wallet`);let{address:l}=await this._proxy.create({accessToken:c,recoveryMethod:s,recoveryKey:r,recoveryPassword:e,recoveryAccessToken:n,recoverySecretOverride:i,iCloudRecordNameOverride:a,solanaAddress:o?.address});if(!l)throw Error(`Failed to create wallet`)}return await this._privyInternal.refreshSession(s)}async importWallet({privateKey:e,chainType:t,additionalSigners:n}){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let r=this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`?`tee`:`on-device`;if(n&&r===`on-device`)throw new E({error:`Specifying additionalSigners is only supported for TEE execution and this app uses on-device execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`,code:`invalid_input`});let i=await this._privyInternal.getAccessTokenInternal();if(!i)throw new E({error:`User must be logged in to import an embedded wallet`,code:`embedded_wallet_before_logged_in`});let{address:a}=await this._proxy.importWallet({accessToken:i,privateKey:e,chainType:t,mode:r,additionalSigners:n});if(!a)throw new E({error:`Failed to import wallet`,code:`embedded_wallet_creation_error`});let{session_update_action:o,...s}=await this._privyInternal.refreshSession();return{address:a,user:s}}async createSolana(e){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await Ir({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`solana`,idempotencyKey:e?.idempotencyKey});else{if(!this._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new E({error:`User must be logged in to create an embedded wallet`,code:`embedded_wallet_creation_error`});e?.ethereumAccount&&await this.getProvider(e.ethereumAccount);let{publicKey:n}=await this._proxy.createSolana({accessToken:t,ethereumAddress:e?.ethereumAccount?.address});if(!n)throw new E({error:`Failed to create wallet`,code:`embedded_wallet_creation_error`})}return await this._privyInternal.refreshSession()}async delegateWallets({delegatedWallets:e,rootWallet:t}){if(!this._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new E({error:`User must be logged in to create an embedded wallet`,code:`embedded_wallet_creation_error`});await this._proxy.delegateWallets({accessToken:n,delegatedWallets:e,rootWallet:t})}async getProvider(e,t,n,r,i){if(O(e))return new Pr({account:e,privyInternal:this._privyInternal,chains:this._chains,signRequest:this._signRequest,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin});if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new _r({account:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin})}async getEthereumProvider({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o,onNeedsRecovery:s}){if(!await this._privyInternal.getAccessTokenInternal())throw Error(`User must be logged in to create an embedded wallet`);if(O(e))return new Pr({account:e,privyInternal:this._privyInternal,chains:this._chains,signRequest:this._signRequest,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin});if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new _r({account:e,entropyId:t,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,onNeedsRecovery:s,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin})}async getSolanaProvider(e,t,n,r,i,a,o){if(O(e))return new Nr({account:e,privyInternal:this._privyInternal,signRequest:this._signRequest,app:this._appApi});if(!this._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new cr({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:o})}async setRecovery(e){let{wallet:t,...n}=e;if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(O(t))throw new E({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});mr({currentRecoveryMethod:t.recovery_method,upgradeToRecoveryMethod:n.recoveryMethod===`icloud-native`?`icloud`:n.recoveryMethod}),await this._load(t.chain_type===`solana`?{wallet:t,entropyId:t.address,entropyIdVerifier:`solana-address-verifier`}:{wallet:t,entropyId:t.address,entropyIdVerifier:`ethereum-address-verifier`});let r=await this._privyInternal.getAccessTokenInternal();if(!r)throw Error(`User must be logged in to interact with embedded wallets`);let i=t.recovery_method;this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_set_recovery_started`,{address:t.address,target_recovery_method:n.recoveryMethod,existing_recovery_method:i});try{let e;if(n.recoveryMethod===`user-passcode`)e={recoveryMethod:`user-passcode`,recoveryPassword:n.password};else if(n.recoveryMethod===`google-drive`)e={recoveryMethod:`google-drive`,recoveryAccessToken:n.recoveryAccessToken};else if(n.recoveryMethod===`icloud`)e={recoveryMethod:`icloud`,recoveryAccessToken:n.recoveryAccessToken};else if(n.recoveryMethod===`icloud-native`)e={recoveryMethod:`icloud-native`,iCloudRecordNameOverride:n.iCloudRecordNameOverride,recoverySecretOverride:n.recoverySecretOverride};else if(n.recoveryMethod===`recovery-encryption-key`)e={recoveryMethod:`recovery-encryption-key`,recoveryKey:n.recoveryKey};else if(n.recoveryMethod===`privy`)e={recoveryMethod:`privy`};else throw Error(`Unknown recovery method: ${n.recoveryMethod}`);await this._proxy.setRecovery({accessToken:r,entropyId:t.address,entropyIdVerifier:t.chain_type===`solana`?`solana-address-verifier`:`ethereum-address-verifier`,...e}),this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_set_recovery_completed`,{address:t.address,target_recovery_method:n.recoveryMethod,existing_recovery_method:i});let{user:a}=await this._privyInternal.refreshSession();return{user:a,provider:t.chain_type===`ethereum`?new _r({account:t,entropyId:t.address,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin}):null}}catch(e){throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_set_recovery_failed`,{address:t.address,recovery_method:t.recovery_method,error:e instanceof Error?e.message:`Unable to recover wallet`}),e}}getURL(){let e=new URL(`${this._privyInternal.baseUrl}/apps/${this._privyInternal.appId}/embedded-wallets`);return this._privyInternal.caid&&e.searchParams.append(`caid`,this._privyInternal.caid),this._privyInternal.appClientId&&e.searchParams.append(`client_id`,this._privyInternal.appClientId),e.href}get chains(){return this._chains}onMessage(e){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return this._proxy.handleEmbeddedWalletMessages(e)}reload(){if(!this._proxy){this._privyInternal.logger.warn(`Attempted to reload proxy before initialized`);return}this._proxy.reload()}onBackground(){this._proxy?.onBackground()}async ping(e){try{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return await this._proxy.ping(e),!0}catch(e){return this._privyInternal.logger.debug(e),!1}}async _load({entropyId:e,entropyIdVerifier:t,wallet:n,recoveryPassword:r,recoveryKey:i,recoveryAccessToken:a,recoverySecretOverride:o}){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let s=await this._privyInternal.getAccessTokenInternal();if(!s)throw Error(`User must be logged in to interact with embedded wallets`);try{return await this._proxy.connect({accessToken:s,entropyId:e,entropyIdVerifier:t}),e}catch(c){if(zn(c)){try{if(n.recovery_method===`privy`){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let r=await this._proxy.recover({accessToken:s,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),r.entropyId}if(n.recovery_method===`user-passcode`&&r){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let i=await this._proxy.recover({accessToken:s,recoveryPassword:r,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),i.entropyId}if([`google-drive`,`icloud`].includes(n.recovery_method)&&a){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let r=await this._proxy.recover({accessToken:s,recoveryAccessToken:a,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),r.entropyId}if(n.recovery_method===`icloud`&&o){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:`icloud-native`});let r=await this._proxy.recover({accessToken:s,recoverySecretOverride:o,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:`icloud-native`}),r.entropyId}if(n.recovery_method===`recovery-encryption-key`&&i){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let r=await this._proxy.recover({accessToken:s,recoveryKey:i,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),r.entropyId}}catch(t){throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_failed`,{address:n.address,recovery_method:n.recovery_method,error:t instanceof Error?t.message:`Unable to recover wallet: ${e}`}),t}throw c}else throw c}}},Rr=class extends Ft{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const zr=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let Br=!1;const Vr=()=>{if(Br)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;Br=typeof t==`string`&&t.length>0||typeof n==`string`&&zr.includes(n)}catch{Br=!0}return Br},z={get(e){return on.get(e)},set(e,t,n){Vr()||on.set(e,t,n)},remove(e){on.remove(e)}},Hr=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!Vr(),Ur=`privy:active-user`,Wr=`privy:saved-users`,B=e=>e?`privy:${e}:token`:`privy:token`,V=e=>e?`privy:${e}:pat`:`privy:pat`,H=e=>e?`privy:${e}:refresh_token`:`privy:refresh_token`,U=e=>e?`privy:${e}:id-token`:`privy:id-token`,Gr=e=>e?`privy-${e}-token`:`privy-token`,Kr=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,qr=e=>e?`privy-${e}-id-token`:`privy-id-token`,W=e=>e?`privy-${e}-session`:`privy-session`,G=Promise.allSettled.bind(Promise)??(e=>Promise.all(e.map(e=>e.then(e=>({status:`fulfilled`,value:e})).catch(e=>({status:`rejected`,reason:e}))))),Jr=[`storage_cleared`,`token_cleared`,`refresh_token_cleared`,`identity_token_cleared`,`token_stored`,`refresh_token_stored`,`identity_token_stored`,`oauth_tokens_granted`,`error_storing_tokens`];var Yr=class extends Ft{static events=Jr;_storage;_isUsingServerCookies=!1;_cookieWriteBehavior;GUEST_CREDENTIAL_STORAGE_KEY;_setStoredUsers;_hasEmittedStoredUsers=!1;constructor(e){super(),this._storage=e.storage,this._isUsingServerCookies=e.isUsingServerCookies,this._cookieWriteBehavior=e.cookieWriteBehavior,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`,this._setStoredUsers=e.setStoredUsers}set isUsingServerCookies(e){this._isUsingServerCookies=e}shouldWriteCookies(){return Hr({useServerCookies:this._isUsingServerCookies,cookieWriteBehavior:this._cookieWriteBehavior})}writeCookie(e,t,n){this.shouldWriteCookies()&&z.set(e,t,n)}setStoredUsersCallback(e){this._setStoredUsers=e,this.getSavedUserIds().then(e=>{this._hasEmittedStoredUsers||this._setStoredUsers?.({users:e.map(e=>({id:e}))})})}async getCustomerAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(B(e));try{return typeof t==`string`?new D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(V(e));try{return typeof t==`string`?new D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async getRefreshToken(){let e=await this.getActiveUserId(),t=await this._storage.get(H(e));return typeof t==`string`?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(U(e));return typeof t==`string`?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=z.get(W(e));if(t!==void 0&&t.length>0)return!0;let n=z.get(W(null));return n!==void 0&&n.length>0}catch(e){console.error(e)}return!1}async hasRefreshCredentials(e,t){return await this.mightHaveServerCookies()||typeof e==`string`&&typeof t==`string`}tokenIsActive(e){if(!e)return!1;let t=D.parse(e);return t!==null&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),n=[this._storage.del(B(null)),this._storage.del(V(null)),this._storage.del(H(null)),this._storage.del(U(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(Ur)];t&&n.push(this._storage.del(B(t)),this._storage.del(V(t)),this._storage.del(H(t)),this._storage.del(U(t)),this.removeSavedUserId(t)),await G(n),z.remove(Gr(null)),z.remove(Kr(null)),z.remove(qr(null)),z.remove(W(null)),t&&(z.remove(Gr(t)),z.remove(Kr(t)),z.remove(qr(t)),z.remove(W(t))),e?.reason&&this.emit(`storage_cleared`,{reason:e.reason})}async storeCustomerAccessToken(e){let t=await this.getActiveUserId();await this.storeCustomerAccessTokenForUser(t,e)}async storeCustomerAccessTokenForUser(e,t){let n=B(e),r=Gr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),z.remove(r),e!==null&&this.emit(`token_cleared`,{reason:`set_with_non_string_value`})}}async storePrivyAccessToken(e){let t=await this.getActiveUserId();await this.storePrivyAccessTokenForUser(t,e)}async storePrivyAccessTokenForUser(e,t){let n=V(e);typeof t==`string`?await this._storage.put(n,t):await this._storage.del(n)}async storeRefreshTokenForUser(e,t){let n=H(e),r=Kr(e),i=W(e);typeof t==`string`?(await this._storage.put(n,t),this.writeCookie(i,`t`,{sameSite:`Strict`,secure:!0,expires:30}),this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:30}),this.emit(`refresh_token_stored`,{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(n),z.remove(r),z.remove(i),this.emit(`refresh_token_cleared`,{reason:`set_with_non_string_value`}))}async updateWithTokensResponse(e){let t=e.user.id,n=(await G([this.storeCustomerAccessTokenForUser(t,e.token),this.storePrivyAccessTokenForUser(t,e.privy_access_token),this.storeRefreshTokenForUser(t,e.refresh_token),this.storeIdentityTokenForUser(t,e.identity_token)])).filter(e=>e.status===`rejected`);if(n.length>0){this.emit(`error_storing_tokens`,n.map(e=>String(e.reason)).join(`, `));return}let r=(await G([this.storeCustomerAccessTokenForUser(null,e.token),this.storePrivyAccessTokenForUser(null,e.privy_access_token),this.storeRefreshTokenForUser(null,e.refresh_token),this.storeIdentityTokenForUser(null,e.identity_token)])).filter(e=>e.status===`rejected`);if(r.length>0){this.emit(`error_storing_tokens`,r.map(e=>String(e.reason)).join(`, `));return}await this.storeActiveUserId(t);let i=(await G([this.processOAuthTokens(e.oauth_tokens)])).filter(e=>e.status===`rejected`);i.length>0&&this.emit(`error_storing_tokens`,i.map(e=>String(e.reason)).join(`, `))}async backfillLegacySession(){if(await this.getActiveUserId())return;let[e,t,n,r]=await Promise.all([this._storage.get(B(null)),this._storage.get(V(null)),this._storage.get(H(null)),this._storage.get(U(null))]);if(typeof e!=`string`||typeof n!=`string`)return;let i=D.parse(e)?.subject;if(typeof i!=`string`||i.length===0)return;let a=[this.storeCustomerAccessTokenForUser(i,e),this.storeRefreshTokenForUser(i,n)];typeof t==`string`&&a.push(this.storePrivyAccessTokenForUser(i,t)),typeof r==`string`&&a.push(this.storeIdentityTokenForUser(i,r));let o=(await G(a)).filter(e=>e.status===`rejected`);if(o.length>0){this.emit(`error_storing_tokens`,o.map(e=>String(e.reason)).join(`, `));return}await this.storeActiveUserId(i)}async processOAuthTokens(e){e&&this.emit(`oauth_tokens_granted`,e)}async storeIdentityToken(e){let t=await this.getActiveUserId();await this.storeIdentityTokenForUser(t,e)}async storeIdentityTokenForUser(e,t){let n=U(e),r=qr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`identity_token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),z.remove(r),e!==null&&this.emit(`identity_token_cleared`,{reason:`set_with_non_string_value`})}}async getOrCreateGuestCredential(){let t=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(t&&typeof t==`string`)return t;let n=e.base64urlnopad.fromBytes(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,n),n}async getActiveUserId(){let e=await this._storage.get(Ur);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(Ur,e)}async getSavedUserIds(){let e=await this._storage.get(Wr);if(typeof e!=`string`)return[];try{let t=JSON.parse(e),n=Array.isArray(t)?t.filter(e=>typeof e==`string`):[];return[...new Set(n)]}catch{return[]}}async storeSavedUserIds(e){let t=[...new Set(e)];t.length>0?await this._storage.put(Wr,JSON.stringify(t)):await this._storage.del(Wr),this._setStoredUsers&&(this._hasEmittedStoredUsers=!0,this._setStoredUsers({users:t.map(e=>({id:e}))}))}async removeSavedUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds(t.filter(t=>t!==e))}async switchActiveUserId(e){if(!(await this.getSavedUserIds()).includes(e))throw new E({code:`invalid_input`,error:`Cannot switch active user because the user ID is not saved on this device`});await this._storage.put(Ur,e)}};const Xr=e=>{let t=new AbortController,n=e.filter(e=>!!e),r=()=>{for(let e of n)e.removeEventListener(`abort`,r);t.abort(n.find(e=>e.aborted)?.reason)};if(n.some(e=>e.aborted))r();else for(let e of n)e.addEventListener(`abort`,r);return t.signal},Zr=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function Qr(e){let t=new URLSearchParams;for(let n in e)e[n]!=null&&t.append(n,String(e[n]));return Array.from(t).length?`?`+t.toString():``}const $r=()=>void 0,K={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},ei=({level:e,logger:t})=>({get level(){return e},error:K[e]>=K.ERROR?t.error:$r,warn:K[e]>=K.WARN?t.warn:$r,info:K[e]>=K.INFO?t.info:$r,debug:K[e]>=K.DEBUG?t.debug:$r}),ti=`privy:caid`;var ni=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.79.3`;_fetch;nativeAppIdentifier;_crypto;isMultiUserModeEnabled;_cache=new Map;constructor(e){this.logger=ei({level:e.logger?.level??e.logLevel??`ERROR`,logger:e.logger??console}),this._storage=e.storage,this._crypto=e.crypto,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=e.baseUrl??`https://auth.privy.io`,this.appId=e.appId,this.appClientId=e.appClientId,this._sdkVersion=e.sdkVersion??this._sdkVersion,this.callbacks=e.callbacks,this.nativeAppIdentifier=e.nativeAppIdentifier,this.isMultiUserModeEnabled=e.isMultiUserModeEnabled,this.session=new Yr({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=an(globalThis.fetch),this.session.on(`error_storing_tokens`,e=>{this.createAnalyticsEvent(`error_updating_tokens_in_storage`,{reason:e})})}setCallbacks(e){this.callbacks={...this.callbacks,...e},this.session.setStoredUsersCallback(this.callbacks?.setStoredUsers)}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady){this.callbacks?.setIsReady?.(!0);return}if(!await this.isStorageAccessible())throw new E({code:`storage_error`,error:`Unable to access storage`});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.isMultiUserModeEnabled&&await this.session.backfillLegacySession(),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith(`js-sdk-core:`)&&this.createAnalyticsEvent(`sdk_initialize`,{})}getPath(e,{params:t,query:n}){return`${this.baseUrl}${xt(e.path,t)}${Qr(n)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new E({code:`invalid_input`,error:`Unauthenticated requests require sessions.mode to be set to "multi-user"`});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:n,query:r,headers:i,signal:a,onRequest:o=this._beforeRequest.bind(this)}){let s=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),c=await o(s);a&&(c.signal=Xr([a,c.signal]));let l=await this._fetch(s,c),u=await l.json();if(l.status>299)throw new T({...u,status:l.status});return u}async fetchRaw(e,{body:t,params:n,query:r,headers:i,onRequest:a=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),s=await a(o),c=await this._fetch(o,s);if(c.status>299)throw new T({...await c.json().catch(()=>({})),status:c.status});return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getPrivyAccessToken()??await this.session.getCustomerAccessToken(),n=new Headers(e.headers);n.set(`privy-app-id`,this.appId),this.appClientId&&n.set(`privy-client-id`,this.appClientId),n.set(`privy-client`,this._sdkVersion),t&&n.set(`Authorization`,`Bearer ${t}`),n.set(`Content-Type`,`application/json`),n.set(`Accept`,`application/json`);let r=await this._getOrGenerateClientAnalyticsId();return r&&n.set(`privy-ca-id`,r),this.nativeAppIdentifier&&n.set(`x-native-app-identifier`,this.nativeAppIdentifier),{signal:Zr(2e4),headers:n,credentials:`include`}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequestWithoutAuth(e){await this._initialize();let t=new Headers(e.headers);t.set(`privy-app-id`,this.appId),this.appClientId&&t.set(`privy-client-id`,this.appClientId),t.set(`privy-client`,this._sdkVersion),t.set(`Content-Type`,`application/json`),t.set(`Accept`,`application/json`);let n=await this._getOrGenerateClientAnalyticsId();return n&&t.set(`privy-ca-id`,n),this.nativeAppIdentifier&&t.set(`x-native-app-identifier`,this.nativeAppIdentifier),{signal:Zr(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(ti);if(typeof e==`string`&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error(`Unable to load clientId`,e)}try{this._analyticsId=this._crypto.randomUUID()}catch(e){this.logger.error(`Unable to generate uuidv4`,e)}if(this._analyticsId){try{await this._storage.put(ti,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}}async destroyClientAnalyticsId(){try{return await this._storage.del(ti)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,t){try{await this.fetch(r,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch{}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new E({code:`storage_error`,error:`Unable to access storage`});let t=await this.session.getRefreshToken()??void 0,n=t??`key`,r=this._cache.get(n);if(r)return this.logger.debug(`[privy:refresh] found in-flight session refresh request, deduping`),await r;let i=this._refreshSession(t,e);this._cache.set(n,i);try{return await i}finally{this._cache.delete(n)}}async _refreshSession(e,t){let n=await this.session.getCustomerAccessToken();if(!await this.session.hasRefreshCredentials(n,e??null))throw this.logger.debug(`[privy:refresh] missing tokens, skipping request`),await this._initialize(),new T({code:rn.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});let r;try{this.logger.debug(`[privy:refresh] fetching: ${qe.path}`),r=await this.fetch(qe,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(n){if(this.logger.debug(`[privy:refresh] error: ${n.message??`unknown error`}`),n instanceof T&&n.code===rn.MISSING_OR_INVALID_TOKEN){if(await this.hasRefreshTokenChanged(e))return this.logger.debug(`[privy:refresh] session replaced during refresh, refreshing again`),await this.refreshSession(t);await this.session.destroyLocalState(),!t&&this.callbacks?.setUser?.(null)}throw n}if(await this.hasRefreshTokenChanged(e))return this.logger.debug(`[privy:refresh] session replaced during refresh, refreshing again`),await this.refreshSession(t);let i=r.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),i===`set`&&(await this.session.updateWithTokensResponse(r),this.logger.debug(`[privy:refresh] tokens stored`)),i===`clear`&&(await this.session.destroyLocalState(),this.logger.debug(`[privy:refresh] tokens cleared`),!t&&this.callbacks?.setUser?.(null)),i===`ignore`&&(r.token&&(await this.session.storeCustomerAccessToken(r.token),this.logger.debug(`[privy:refresh] token stored (CAT)`)),r.privy_access_token&&(await this.session.storePrivyAccessToken(r.privy_access_token),this.logger.debug(`[privy:refresh] token stored (PAT)`)),r.identity_token&&(this.logger.debug(`[privy:refresh] token stored (IDT)`),await this.session.storeIdentityToken(r.identity_token))),this.logger.debug(`[privy:refresh] returning response`),!t&&this.callbacks?.setUser?.(r.user),r}async hasRefreshTokenChanged(e){return(await this.session.getRefreshToken()??void 0)!==e}async getAccessToken(){let[e,t]=await Promise.all([this.session.getCustomerAccessToken(),this.session.getRefreshToken()]);if(e&&!this.session.tokenIsActive(e)&&await this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),n=await this.session.getCustomerAccessToken();return t.token||this.logger.debug(`[privy:getAccessToken] expected token received null`),t.token===e&&this.logger.debug(`[privy:getAccessToken] expected new token in response received existing`),n===e&&this.logger.debug(`[privy:getAccessToken] expected new token in storage received existing`),t.token??n}return e&&!this.session.tokenIsActive(e)?(this.logger.debug(`[privy:getAccessToken] unable to refresh inactive token`),this.callbacks?.setUser?.(null),await this.session.destroyLocalState(),null):e}async getAccessTokenInternal(){let e=await this.getAccessToken();return await this.session.getPrivyAccessToken()??e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${this._crypto.randomUUID()}`,t=`blobby`;await this._storage.put(e,t);let n=await this._storage.get(e);return await this._storage.del(e),n===t}catch(e){return this.logger.error(e),!1}}},ri=class{_privyInternal;_embedded;_isMultiUserModeEnabled;constructor(e,t,n){this._privyInternal=e,this._embedded=t,this._isMultiUserModeEnabled=n}async get(){let{user:e}=await this._privyInternal.refreshSession();return{user:e}}async acceptTerms(){let e=await this._privyInternal.fetch(n,{});return this._privyInternal.callbacks?.setUser?.(e),{user:e}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(Je,{});return await this._privyInternal.session.storeIdentityToken(t),this._privyInternal.callbacks?.setUser?.(e),{user:e}}async switchActiveUser(e){if(!this._isMultiUserModeEnabled)throw new E({code:`invalid_input`,error:`User switching requires sessions.mode to be set to "multi-user"`});await this._privyInternal.session.switchActiveUserId(e.userId);try{this._embedded.reload();let{user:t}=await this._privyInternal.refreshSession(!0);if(t.id!==e.userId)throw new E({code:`invalid_input`,error:`Cannot switch active user because the refreshed user did not match the requested user ID`});return this._privyInternal.callbacks?.setUser?.(t),{user:t}}catch(e){throw await this._privyInternal.session.destroyLocalState(),this._privyInternal.callbacks?.setUser?.(null),e}}};const ii=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`,ai=e=>e?e.linked_accounts.filter(ii).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],q=e=>ai(e).find(e=>e.wallet_index===0)??null,oi=q,si=e=>e?e.linked_accounts.filter(ii).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],ci=e=>si(e).find(e=>e.wallet_index===0)??null,li=(e,t)=>t===`off`||ai(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,ui=(e,t)=>t===`off`||si(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,di=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),J=async(e,t,n)=>{let r=li(t.user,n?.ethereum?.createOnLogin??`off`),i=ui(t.user,n?.solana?.createOnLogin??`off`);if(r&&i){let n=await e.create({recoveryMethod:`privy`,skipCallbacks:!0}),r=await e.createSolana({ethereumAccount:q(n.user)??void 0});return di(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:ci(t.user)??void 0});return di(n,t)}if(i){let n=await e.createSolana({ethereumAccount:q(t.user)??void 0});return di(n,t)}return t};var fi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async syncWithToken(e,t,n){let r=await this._privyInternal.fetchForLogin(d,{body:{token:e,mode:n}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await J(this._embedded,r,t?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithToken(e){await this._privyInternal.fetch(f,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},pi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Ne,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Me,{body:{email:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Pe,{body:{email:e,code:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}async updateEmail({oldEmailAddress:e,newEmailAddress:t,code:n}){await this._privyInternal.fetch(Ve,{body:{oldAddress:e,newAddress:t,code:n}});let r=await this._privyInternal.refreshSession();return{user:r.user,identity_token:r.identity_token}}async unlink(e){await this._privyInternal.fetch(Be,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},mi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth({relyingParty:e,redirectUrl:t,token:n}){return await this._privyInternal.fetch(h,{body:{relying_party:e,redirect_url:t,token:n}})}async getFarcasterStatus({channel_token:e}){return await this._privyInternal.fetch(te,{headers:{"farcaster-channel-token":e}})}async authenticate({channel_token:e,message:t,signature:n,fid:r,mode:i},a){let o=await this._privyInternal.fetchForLogin(m,{body:{channel_token:e,message:t,signature:n,fid:r,mode:i}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await J(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async link({channel_token:e,message:t,signature:n,fid:r}){await this._privyInternal.fetch(ee,{body:{channel_token:e,message:t,signature:n,fid:r}});let i=await this._privyInternal.refreshSession();return{user:i.user,identity_token:i.identity_token}}async unlink({fid:e}){await this._privyInternal.fetch(ne,{body:{fid:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},hi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(ie,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(re,{body:{message:e,signature:t,fid:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}},gi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async create(e){let t=await this._privyInternal.session.getOrCreateGuestCredential(),n=await this._privyInternal.fetch(he,{body:{guest_credential:t}});await this._privyInternal.session.updateWithTokensResponse(n);let r=await J(this._embedded,n,e?.embedded);return this._privyInternal.callbacks?.setUser?.(r.user),r}};const Y=`privy:state_code`,X=`privy:code_verifier`;async function _i(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function vi(e){return crypto.getRandomValues(new Uint8Array(e))}function yi(){return e.base64urlnopad.fromBytes(vi(36))}function bi(){return yi()}async function xi({codeVerifier:t,method:n=`S256`,digest:r}){if(n==`S256`){let n=await _i(t,r);return e.base64urlnopad.fromBytes(n)}else return t}var Si=class{_privyInternal;_storage;_crypto;_embedded;constructor(e,t,n,r){this._privyInternal=e,this._embedded=t,this._storage=n,this._crypto=r}async generateURL(e,t){let n=yi(),r=bi(),i=await xi({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put(X,n),this._storage.put(Y,r)]),this._privyInternal.fetchForLogin(Ce,{body:{redirect_to:t,provider:e,code_challenge:i,state_code:r}})}async loginWithCode(e,t,n,r,i,a){let[o,s]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(s!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:s??``,returnedStateCode:t??``}),new E({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let c=await this._privyInternal.fetchForLogin(Se,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let l=await J(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del(X),this._storage.del(Y)]),this._privyInternal.callbacks?.setUser?.(l.user),l}async linkWithCode(e,t,n,r){let[i,a]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(a!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:a??``,returnedStateCode:t??``}),new E({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let o=await this._privyInternal.fetch(we,{body:{authorization_code:e,code_type:r,state_code:a,code_verifier:i}});await this._privyInternal.session.processOAuthTokens(o.oauth_tokens);let s=await this._privyInternal.refreshSession();return await Promise.all([this._storage.del(X),this._storage.del(Y)]),{user:s.user,identity_token:s.identity_token,oauth_tokens:o.oauth_tokens}}async unlink(e,t){await this._privyInternal.fetch(Te,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},Ci=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(ke,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(De,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(je,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Ee,{body:{relying_party:n,challenge:t,authenticator_response:this._transformAuthenticationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async signupWithPasskey(e,t,n){let r=await this._privyInternal.fetchForLogin(Ae,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await J(this._embedded,r,n?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithPasskey(e,t){await this._privyInternal.fetch(Oe,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}_transformRegistrationResponseToSnakeCase(e){return{type:e.type,id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData||void 0,transports:e.response.transports||void 0,public_key:e.response.publicKey||void 0,public_key_algorithm:e.response.publicKeyAlgorithm||void 0},authenticator_attachment:e.authenticatorAttachment||void 0,client_extension_results:{app_id:e.clientExtensionResults.appid||void 0,cred_props:e.clientExtensionResults.credProps||void 0,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret||void 0}}}_transformAuthenticationResponseToSnakeCase(e){return{type:e.type,id:e.id,raw_id:e.rawId,response:{signature:e.response.signature,client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,user_handle:e.response.userHandle||void 0},authenticator_attachment:e.authenticatorAttachment||void 0,client_extension_results:{app_id:e.clientExtensionResults.appid||void 0,cred_props:e.clientExtensionResults.credProps||void 0,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret||void 0}}}},wi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Ie,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Fe,{body:{phoneNumber:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Le,{body:{phoneNumber:e,code:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}async updatePhone({oldPhoneNumber:e,newPhoneNumber:t,code:n}){await this._privyInternal.fetch(ze,{body:{old_phone_number:e,new_phone_number:t,code:n}});let r=await this._privyInternal.refreshSession();return{user:r.user,identity_token:r.identity_token}}async unlink(e){await this._privyInternal.fetch(Re,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Ti=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(tt,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}async linkWithSiwe(e,t,n){let r=t||this._wallet,i=n||this._preparedMessage;if(!r)throw Error(`A wallet must be provided in the init step or as an argument to linkWithSiwe`);if(!i)throw Error(`A message must be generated and signed before being used to link a wallet to privy`);await this._privyInternal.fetch($e,{body:{message:i,signature:e,chainId:r.chainId,walletClientType:r.walletClientType??null,connectorType:r.connectorType??null}});let a=await this._privyInternal.refreshSession();return{user:a.user,identity_token:a.identity_token}}async loginWithSiwe(e,t,n,r,i){let a=t||this._wallet,o=n||this._preparedMessage;if(!a)throw Error(`A wallet must be provided in the init step or as an argument to loginWithSiwe`);if(!o)throw Error(`A message must be generated and signed before being used to login to privy with a wallet`);let s=await this._privyInternal.fetchForLogin(Ze,{body:{signature:e,message:o,chainId:a.chainId,walletClientType:a.walletClientType??null,connectorType:a.connectorType??null,mode:r}});await this._privyInternal.session.updateWithTokensResponse(s);let c=await J(this._embedded,s,i?.embedded);return this._privyInternal.callbacks?.setUser?.(c.user),c}async init(e,t,n){this._wallet=e;let{nonce:r}=await this._privyInternal.fetch(Qe,{body:{address:e.address}}),i=Ei({chainId:e.chainId.toString().replace(`eip155:`,``),address:e.address,issuedAt:new Date().toISOString(),statement:`By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.`,domain:t,nonce:r,uri:n});return this._preparedMessage=i,{nonce:r,message:i}}};function Ei(e){return`${e.domain} wants you to sign in with your Ethereum account:
1
+ import{encoding as e}from"@privy-io/encoding";import{AcceptCardConsents as t,AcceptTermsOnUser as n,AnalyticsEvent as r,AppConfig as i,CoinbaseOnRampInit as a,CoinbaseOnRampStatus as o,CreateCard as s,CreateCryptoDepositAccount as c,CreateCryptoDepositAccountQuote as l,CreateDepositAddressQuote as u,CustomJWTAuthenticate as d,CustomJWTLink as f,DownloadCardStatement as p,FarcasterAuthenticate as m,FarcasterInit as h,FarcasterLink as ee,FarcasterStatus as te,FarcasterUnlink as ne,FarcasterV2Authenticate as re,FarcasterV2Init as ie,GetCardCustomer as ae,GetCardEphemeralKey as oe,GetCardsConfig as se,GetCrossAppConnections as ce,GetCryptoDepositAccountNextOrder as le,GetCryptoDepositAccountOrder as ue,GetDepositAddressOrder as de,GetDepositConfig as fe,GetNextDepositAddressOrder as pe,GetSmartWalletConfig as me,GuestAuthenticate as he,ListCardTransactions as ge,ListCards as _e,Logout as ve,MfaPasskeyInit as ye,MfaPasswordlessSmsInit as be,MoonpayOnRampSign as xe,OAuthAuthenticate as Se,OAuthInit as Ce,OAuthLink as we,OAuthUnlink as Te,PasskeyAuthenticate as Ee,PasskeyAuthenticateInit as De,PasskeyLink as Oe,PasskeyLinkInit as ke,PasskeyRegister as Ae,PasskeyRegisterInit as je,PasswordlessAuthenticate as Me,PasswordlessInit as Ne,PasswordlessLink as Pe,PasswordlessSmsAuthenticate as Fe,PasswordlessSmsInit as Ie,PasswordlessSmsLink as Le,PasswordlessSmsUnlink as Re,PasswordlessSmsUpdate as ze,PasswordlessUnlink as Be,PasswordlessUpdate as Ve,RecoveryConfigurationICloud as He,RecoveryKeyMaterial as Ue,RecoveryOAuthAuthenticate as We,RecoveryOAuthInit as Ge,RecoveryOAuthInitICloud as Ke,RefreshSession as qe,RefreshUser as Je,ReplaceCard as Ye,SearchCryptoDepositAccountConfig as Xe,SiweAuthenticate as Ze,SiweInit as Qe,SiweLink as $e,SiweLinkSmartWallet as et,SiweUnlink as tt,SiwsAuthenticate as nt,SiwsInit as rt,SiwsLink as it,SiwsUnlink as at,TelegramAuthenticate as ot,TelegramLink as st,TelegramUnlink as ct,UpdateCard as lt,UpdateCardPin as ut,UpsertCardCustomer as dt,WalletCreate as ft,WalletGet as pt,WalletGetAction as mt,WalletListActions as ht,WalletRawSign as gt,WalletRpc as _t,WalletTransfer as vt,WalletUpdate as yt,WalletsRevoke as bt,getPathWithParams as xt}from"@privy-io/routes";import*as St from"jose";import{areAddressesEqual as Ct}from"@privy-io/are-addresses-equal";import{DEFAULT_SUPPORTED_CHAINS as wt,arbitrum as g,arbitrumSepolia as Tt,avalanche as _,avalancheFuji as Et,base as v,baseSepolia as Dt,celo as Ot,dedupeSupportedChains as kt,mainnet as y,monadMainnet as b,optimism as x,optimismSepolia as At,polygon as S,polygonAmoy as jt,sepolia as Mt,tempo as Nt,tempoTestnet as Pt}from"@privy-io/chains";import{base58 as Ft}from"@scure/base";import It from"eventemitter3";import{concat as Lt,createPublicClient as Rt,decodeAbiParameters as zt,decodeFunctionResult as Bt,encodeFunctionData as Vt,erc20Abi as Ht,formatEther as Ut,formatUnits as Wt,http as Gt,isAddress as Kt,isHex as qt,maxUint256 as Jt,stringToHex as Yt,toHex as Xt,zeroAddress as Zt}from"viem";import{STRING_TO_NUMBER_TXN_TYPE as Qt,TEMPO_TXN_TYPE_NUMBER as $t,isTempoTransactionRequest as C,normalizeViemPreparedTempoTransaction as en,toViemTempoTransactionSerializable as tn,toViemTransactionSerializable as nn}from"@privy-io/ethereum";import rn from"canonicalize";import{PrivyErrorCode as an}from"@privy-io/api-base";import{retryFetch as on}from"@privy-io/std/retry-fetch";import sn from"js-cookie";import cn from"fetch-retry";import ln from"libphonenumber-js/examples.mobile.json";import{AsYouType as un,getCountries as dn,getCountryCallingCode as fn,getExampleNumber as pn,isPossiblePhoneNumber as mn,parsePhoneNumberFromString as hn}from"libphonenumber-js/min";export*from"@privy-io/chains";var gn=Object.defineProperty,w=(e,t)=>{let n={};for(var r in e)gn(n,r,{get:e[r],enumerable:!0});return t||gn(n,Symbol.toStringTag,{value:`Module`}),n};function _n(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}const vn=e=>/^0x[0-9a-fA-F]*$/.test(e),yn=t=>`0x${e.hex.fromBytes(t)}`,bn=t=>vn(t)?t:yn(e.utf8.toBytes(t)),xn=Symbol(`data-suffix-plugin`);function Sn(e=[]){return e.find(e=>e.id===xn)}function Cn(e){let t=e.startsWith(`0x`)?e:`0x${e}`;if(!vn(t))throw Error(`[Privy] dataSuffix: Invalid suffix "${e}" is not valid hex`);let n=t.slice(2);return{id:xn,suffix:t,appendDataSuffix:({data:e})=>!e||e===`0x`?t:`${e}${n}`}}var wn=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(me,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},T=class extends Error{name=`PrivyApiError`;error;code;status;constructor({error:e,code:t,status:n}){super(e),this.error=e,this.code=t,this.status=n}},E=class extends Error{error;code;cause;constructor({error:e,code:t,cause:n}){super(e),this.code=t,this.error=e,n!==void 0&&(this.cause=n)}},Tn=class extends Error{error;code;response;constructor({error:e,code:t,response:n}){super(e),this.code=t,this.error=e,this.response=n}};function En(e){return e instanceof T||e instanceof E?e.code:`unknown_error`}const Dn=e=>t=>e[En(t)]??e.default;function On(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}var D=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=St.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=(this.expiration-e)*1e3}},kn=class e{_storage;_privyInternal;constructor(e,t){this._privyInternal=e,this._storage=t}static providerAccessTokenStorageKey=e=>`privy:cross-app:${e}`;async updateOnCrossAppAuthentication(t,n){let r=n.access_token,i=D.parse(r);if(!i||i.issuer!==`privy:${t}`)throw new E({code:`cross_app_invalid_app`,error:`Cross-app token issuer does not match the provider app.`});let a=e.providerAccessTokenStorageKey(t);await this._storage.put(a,r)}async getProviderAccessToken(t){let n=e.providerAccessTokenStorageKey(t),r=await this._storage.get(n);if(typeof r!=`string`)return null;try{let e=new D(r);return e.isExpired()||e.issuer!==`privy:${t}`?(await this._storage.del(n),null):r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(ce,{params:{app_id:this._privyInternal.appId}})}},An=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(bt,{})}};const O=e=>!!e.id&&e.recovery_method===`privy-v2`;var jn=class{_proxy;_privyInternal;_account;_entropyId;_entropyIdVerifier;constructor({proxy:e,privyInternal:t,account:n,entropyId:r,entropyIdVerifier:i}){this._proxy=e,this._privyInternal=t,this._account=n,this._entropyId=r,this._entropyIdVerifier=i}async sign({message:e}){return await this.request({method:`sign`,params:{message:new TextDecoder(`utf8`).decode(e)}})}async signTransaction({psbt:e}){return await this.request({method:`signTransaction`,params:{psbt:e}})}async request(e){if(O(this._account))throw new E({code:`unsupported_wallet_type`,error:`Bitcoin wallet providers are only supported for on-device execution and this app uses TEE execution. Use the useSignRawHash hook from @privy-io/expo/extended-chains to sign over a hash with this wallet. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide`});if(!await this._privyInternal.getAccessTokenInternal())throw new E({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return this.handleIFrameRpc(e)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing access token. User must be authenticated.`);return(await this._proxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:this._account.chain_type})).response.data}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedBitcoinProvider { address: '${this._account.address}', request: [Function] }`}},Mn=class{callbacks={};enqueue(e,t){this.callbacks[e]=t}flush(e){let t=Object.values(this.callbacks);this.callbacks={};for(let{reject:n}of t)n(e)}dequeue(e,t){let n=this.callbacks[t];if(!n)return console.warn(`[Privy] No callback found for "${e}" (id: ${t})`),null;switch(delete this.callbacks[t],e){case`privy:iframe:ready`:return n;case`privy:wallets:create`:return n;case`privy:user-signer:sign`:return n;case`privy:wallets:add`:return n;case`privy:wallets:set-recovery`:return n;case`privy:wallets:connect`:return n;case`privy:wallets:recover`:return n;case`privy:wallets:rpc`:return n;case`privy:wallets:import`:return n;case`privy:wallet:create`:return n;case`privy:wallet:connect`:return n;case`privy:wallet:recover`:return n;case`privy:wallet:rpc`:return n;case`privy:solana-wallet:create`:return n;case`privy:solana-wallet:create-additional`:return n;case`privy:solana-wallet:connect`:return n;case`privy:solana-wallet:recover`:return n;case`privy:solana-wallet:rpc`:return n;case`privy:delegated-actions:consent`:return n;case`privy:mfa:verify`:return n;case`privy:mfa:init-enrollment`:return n;case`privy:mfa:submit-enrollment`:return n;case`privy:mfa:unenroll`:return n;case`privy:mfa:clear`:return n;case`privy:auth:unlink-passkey`:return n;default:throw Error(`invalid wallet event type ${e}`)}}};const Nn=[`error`,`invalid_request_arguments`,`wallet_not_on_device`,`invalid_recovery_pin`,`insufficient_funds`,`mfa_timeout`,`missing_or_invalid_mfa`,`mfa_verification_max_attempts_reached`];let Pn=function(e){return e.MISSING_OR_INVALID_PRIVY_APP_ID=`missing_or_invalid_privy_app_id`,e.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID=`missing_or_invalid_privy_account_id`,e.INVALID_DATA=`invalid_data`,e.LINKED_TO_ANOTHER_USER=`linked_to_another_user`,e.ALLOWLIST_REJECTED=`allowlist_rejected`,e.OAUTH_USER_DENIED=`oauth_user_denied`,e.UNKNOWN_AUTH_ERROR=`unknown_auth_error`,e.USER_EXITED_AUTH_FLOW=`exited_auth_flow`,e.MUST_BE_AUTHENTICATED=`must_be_authenticated`,e.UNKNOWN_CONNECT_WALLET_ERROR=`unknown_connect_wallet_error`,e.GENERIC_CONNECT_WALLET_ERROR=`generic_connect_wallet_error`,e.CLIENT_REQUEST_TIMEOUT=`client_request_timeout`,e.INVALID_CREDENTIALS=`invalid_credentials`,e}({});var Fn=class extends Error{cause;privyErrorCode;constructor(e,t,n){super(e),t instanceof Error&&(this.cause=t),this.privyErrorCode=n}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:``}: ${this.message}${this.cause?` [cause: ${this.cause}]`:``}`}},In=class extends Fn{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},Ln=class extends Error{type;constructor(e,t){super(t),this.type=e}},Rn=class extends Fn{type=`connector_error`;constructor(e,t,n){super(e,t,n)}},zn=class extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}};const k={UNKNOWN_ERROR:{eipCode:0,message:`Unknown error`,detail:`Unknown error`,retryable:!0},E4001_DEFAULT_USER_REJECTED_REQUEST:{eipCode:4001,message:`User Rejected Request`,detail:`The user rejected the request.`,default:!0,retryable:!0},E4100_DEFAULT_UNAUTHORIZED:{eipCode:4100,message:`Unauthorized`,detail:`The requested method and/or account has not been authorized by the user.`,default:!0,retryable:!1},E4200_DEFAULT_UNSUPPORTED_METHOD:{eipCode:4200,message:`Unsupported Method`,detail:`The Provider does not support the requested method.`,default:!0,retryable:!1},E4900_DEFAULT_DISCONNECTED:{eipCode:4900,message:`Disconnected`,detail:`The Provider is disconnected from all chains.`,default:!0,retryable:!0},E4901_DEFAULT_CHAIN_DISCONNECTED:{eipCode:4901,message:`Chain Disconnected`,detail:`The Provider is not connected to the requested chain.`,default:!0,retryable:!0},E32700_DEFAULT_PARSE_ERROR:{eipCode:-32700,message:`Parse error`,detail:`Invalid JSON`,default:!0,retryable:!1},E32600_DEFAULT_INVALID_REQUEST:{eipCode:-32600,message:`Invalid request`,detail:`JSON is not a valid request object`,default:!0,retryable:!1},E32601_DEFAULT_METHOD_NOT_FOUND:{eipCode:-32601,message:`Method not found`,detail:`Method does not exist`,default:!0,retryable:!1},E32602_DEFAULT_INVALID_PARAMS:{eipCode:-32602,message:`Invalid params`,detail:`Invalid method parameters`,default:!0,retryable:!1},E32603_DEFAULT_INTERNAL_ERROR:{eipCode:-32603,message:`Internal error`,detail:`Internal JSON-RPC error`,default:!0,retryable:!0},E32000_DEFAULT_INVALID_INPUT:{eipCode:-32e3,message:`Invalid input`,detail:`Missing or invalid parameters`,default:!0,retryable:!1},E32001_DEFAULT_RESOURCE_NOT_FOUND:{eipCode:-32001,message:`Resource not found`,detail:`Requested resource not found`,default:!0,retryable:!1},E32002_DEFAULT_RESOURCE_UNAVAILABLE:{eipCode:-32002,message:`Resource unavailable`,detail:`Requested resource not available`,default:!0,retryable:!0},E32003_DEFAULT_TRANSACTION_REJECTED:{eipCode:-32003,message:`Transaction rejected`,detail:`Transaction creation failed`,default:!0,retryable:!0},E32004_DEFAULT_METHOD_NOT_SUPPORTED:{eipCode:-32004,message:`Method not supported`,detail:`Method is not implemented`,default:!0,retryable:!1},E32005_DEFAULT_LIMIT_EXCEEDED:{eipCode:-32005,message:`Limit exceeded`,detail:`Request exceeds defined limit`,default:!0,retryable:!1},E32006_DEFAULT_JSON_RPC_VERSION_NOT_SUPPORTED:{eipCode:-32006,message:`JSON-RPC version not supported`,detail:`Version of JSON-RPC protocol is not supported`,default:!0,retryable:!1},E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:`Connection request already pending`,detail:`Don’t see your wallet? Check your other browser windows.`,retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:`Resource request already pending`,detail:`Don’t see your wallet? Check your other browser windows.`,retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:`Wallet might be locked`,detail:`Unlock your wallet and try again.`,retryable:!0},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:`Signature rejected`,detail:`Please try signing again.`,retryable:!0}};function A(e){let t=e.type;return typeof t==`string`&&Nn.includes(t)}function Bn(e){return A(e)&&e.type===`wallet_not_on_device`}function Vn(e){return A(e)&&e.type===`mfa_timeout`}function Hn(e){return A(e)&&e.type===`missing_or_invalid_mfa`}function Un(e){return A(e)&&e.type===`mfa_verification_max_attempts_reached`}function Wn(e){return A(e)&&e.message.includes(`code 429`)}var Gn=class extends In{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(k).find(e=>e.eipCode===t.code);this.details=n||k.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=k.E32002_CONNECTION_ALREADY_PENDING:this.details=k.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=k.E32002_WALLET_LOCKED))}};async function Kn(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new Ln(`missing_or_invalid_mfa`,`MFA verification failed, retry.`)),await e(await new Promise((e,r)=>{t.current={resolve:e,reject:r},setTimeout(()=>{let e=new Ln(`mfa_timeout`,`Timed out waiting for MFA code`);n.current?.reject(e),r(e)},o)}))):await e(),l=null;for(let e=0;e<a;e++)try{l=await c(e),n.current?.resolve(void 0);break}catch(e){if(e.type===`missing_or_invalid_mfa`)s=!0;else throw n.current?.resolve(void 0),e}if(l===null){let e=new Ln(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function qn(e){return e.error!==void 0}const Jn=(function(e){return()=>`id-${e++}`})(0),Yn=(e,t)=>typeof t==`bigint`?t.toString():t,Xn=(e,t)=>`${e}${JSON.stringify(t,Yn)}`,j=async(e,{ms:t,msg:n})=>{let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t??15e3)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}},Zn=new Mn;var Qn=class{ready;_waitForReadyPromise=null;cache;_embeddedWalletMessagePoster;mfa;constructor(e,t){this.ready=!1,this.cache=new Map,this._embeddedWalletMessagePoster=e,this.mfa=t}invokeWithMfa(e,t){return j(Kn(n=>j(this.waitForReady().then(()=>e(n)),{msg:t.timeoutMsg,ms:t.timeoutMs}),this.mfa.rootPromise,this.mfa.submitPromise,()=>this.mfa.emit(`mfaRequired`),t.mfaAlwaysRequired??!1,4,3e5),{msg:`Operation reached timeout: MFA verification`,ms:126e4})}reload(){return this.ready=!1,this._waitForReadyPromise=null,Zn.flush(Error(`Embedded wallet WebView was reloaded`)),this.cache.clear(),this._embeddedWalletMessagePoster.reload()}retarget(e){e!==this._embeddedWalletMessagePoster&&(this._embeddedWalletMessagePoster=e,this.ready=!1)}onBackground(){this.ready=!1}ping(e=15e3){return j(this.invoke(`privy:iframe:ready`,{}),{msg:`Ping reached timeout`,ms:e})}create(e){return j(this.waitForReady().then(()=>this.invoke(`privy:wallet:create`,e)),{msg:`Operation reached timeout: create`})}rpc(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallet:rpc`,{...t,...e}),{timeoutMsg:`Operation reached timeout: rpc`})}createSolana(e){return this.invokeWithMfa(t=>this.invoke(`privy:solana-wallet:create`,{...t,...e}),{timeoutMsg:`Operation reached timeout: create`,timeoutMs:6e4})}createAdditionalSolana(e){return j(this.waitForReady().then(()=>this.invoke(`privy:solana-wallet:create-additional`,e)),{msg:`Operation reached timeout: create`})}solanaRpc(e){return this.invokeWithMfa(t=>this.invoke(`privy:solana-wallet:rpc`,{...t,...e}),{timeoutMsg:`Operation reached timeout: solana-rpc`})}delegateWallets(e){return this.invokeWithMfa(t=>this.invoke(`privy:delegated-actions:consent`,{...t,...e}),{timeoutMsg:`Operation reached timeout: delegated-actions:consent`})}verifyMfa(e){return this.invokeWithMfa(t=>this.invoke(`privy:mfa:verify`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:verify`,mfaAlwaysRequired:!0})}initEnrollMfa(e){return this.invokeWithMfa(t=>this.invoke(`privy:mfa:init-enrollment`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:init-enrollment`})}submitEnrollMfa(e){return e.method===`passkey`?this.invokeWithMfa(t=>this.invoke(`privy:mfa:submit-enrollment`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:submit-enrollment`}):j(this.waitForReady().then(()=>this.invoke(`privy:mfa:submit-enrollment`,e)),{msg:`Operation reached timeout: mfa:submit-enrollment`})}unenrollMfa(e){return this.invokeWithMfa(t=>this.invoke(`privy:mfa:unenroll`,{...t,...e}),{timeoutMsg:`Operation reached timeout: mfa:unenroll`,mfaAlwaysRequired:!0})}unlinkPasskey(e){return this.invokeWithMfa(t=>this.invoke(`privy:auth:unlink-passkey`,{...t,...e}),{timeoutMsg:`Operation reached timeout: auth:unlink-passkey`,mfaAlwaysRequired:!0})}clearMfa(e){return j(this.waitForReady().then(()=>this.invoke(`privy:mfa:clear`,e)),{msg:`Operation reached timeout: mfa:clear`})}createWallet(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:create`,{...t,...e}),{timeoutMsg:`Operation reached timeout: create`,timeoutMs:6e4})}signWithUserSigner(e){return this.invokeWithMfa(t=>this.invoke(`privy:user-signer:sign`,{...t,...e}),{timeoutMsg:`Operation reached timeout: user-signer:sign`})}addWallet(e){return j(this.waitForReady().then(()=>this.invoke(`privy:wallets:add`,e)),{msg:`Operation reached timeout: wallets:add`})}importWallet(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:import`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:import`,timeoutMs:6e4})}setRecovery(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:set-recovery`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:set-recovery`,timeoutMs:6e4})}connect(e){return j(this.waitForReady().then(()=>this.invoke(`privy:wallets:connect`,e)),{msg:`Operation reached timeout: wallets:connect`})}recover(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:recover`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:recover`,timeoutMs:6e4})}rpcWallet(e){return this.invokeWithMfa(t=>this.invoke(`privy:wallets:rpc`,{...t,...e}),{timeoutMsg:`Operation reached timeout: wallets:rpc`})}handleEmbeddedWalletMessages(e){if(!e.event.startsWith(`privy:`)){console.warn(`Unsupported event type: ${e.event}`);return}let t=Zn.dequeue(e.event,e.id);if(t)return qn(e)?t.reject(new Ln(e.error.type,e.error.message)):t.resolve(e.data)}waitForReady(){return this.ready?Promise.resolve():(this._waitForReadyPromise||=new Promise((e,t)=>{(async()=>{for(let t=0;t<100&&!this.ready;t++)this.invoke(`privy:iframe:ready`,{}).then(()=>{this.ready=!0,this._waitForReadyPromise=null,e()}).catch(()=>{}),await new Promise(e=>setTimeout(e,150));this.ready||(this._waitForReadyPromise=null,t(Error(`Embedded wallet WebView failed to become ready`)))})()}),this._waitForReadyPromise)}invoke(e,t){let n=Xn(e,t);if(e===`privy:wallet:create`||e===`privy:solana-wallet:create`){let e=this.cache.get(n);if(e)return e}let r=new Promise((n,r)=>{let i=Jn();Zn.enqueue(i,{resolve:n,reject:r}),this._embeddedWalletMessagePoster.postMessage(JSON.stringify({id:i,event:e,data:t}),`*`)}).finally(()=>{this.cache.delete(n)});return this.cache.set(n,r),r}};function $n({transaction:e,address:t}){let{messageBytes:n,signerAddresses:r}=tr(e),i=r.indexOf(t);if(i===-1)throw Error(`Transaction does not require a signature from ${t}`);return{messageBytes:new Uint8Array(n),signerIndex:i}}function er({transaction:e,signerIndex:t,signature:n}){if(n.length!==64)throw Error(`Solana signatures must be 64 bytes`);let{signaturesOffset:r,signerAddresses:i}=tr(e);if(!Number.isInteger(t)||t<0||t>=i.length)throw Error(`Invalid signer index ${t}`);let a=new Uint8Array(e);return a.set(n,r+t*64),a}function tr(e){if(e.length===0)throw Error(`Cannot decode an empty Solana transaction`);return e[0]===129?nr(e):rr(e)}function nr(e){let t=ir(e,1),n=e.length-t*64;if(n<=41)throw Error(`Malformed V1 Solana transaction`);let r=e.subarray(0,n);if(ir(r,41)<t)throw Error(`Malformed V1 Solana transaction`);return{messageBytes:r,signaturesOffset:n,signerAddresses:or(r,42,t)}}function rr(e){let[t,n]=ar(e,0),r=n+t*64,i=ir(e,r),a=r;if(i&128){let e=i&-129;if(e!==0)throw Error(`Unsupported Solana transaction version ${e}`);a+=1}let o=ir(e,a);if(o!==t)throw Error(`Solana transaction signature count does not match its message header`);let[s,c]=ar(e,a+3);if(s<o)throw Error(`Malformed Solana transaction`);return{messageBytes:e.subarray(r),signaturesOffset:n,signerAddresses:or(e,c,o)}}function ir(e,t){let n=e[t];if(n===void 0)throw Error(`Malformed Solana transaction`);return n}function ar(e,t){let n=0;for(let r=0;r<3;r++){let i=ir(e,t+r);if(n|=(i&127)<<7*r,!(i&128))return[n,t+r+1]}throw Error(`Malformed Solana transaction`)}function or(e,t,n){if(t+n*32>e.length)throw Error(`Malformed Solana transaction`);return Array.from({length:n},(n,r)=>Ft.encode(e.subarray(t+r*32,t+(r+1)*32)))}function sr(e){return`version`in e}function cr(e,t){let n=(sr(e)?e.message:e.compileMessage()).staticAccountKeys.find(e=>e.toBase58()===t);if(!n)throw Error(`Transaction does not contain public key ${t}`);return n}var lr=class{_privyInternal;_account;constructor({privyInternal:e,account:t}){this._privyInternal=e,this._account=t}async request(e){if(!await this._privyInternal.getAccessTokenInternal())throw new E({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});switch(e.method){case`signAndSendTransaction`:return await this.handleSignAndSendTransaction(e);case`signTransaction`:return await this.handleSignTransaction(e);default:return await this.handleIFrameRpc(e)}}get _publicKey(){return this._account.address}async signTransactionObject(t,n){if(sr(t)&&t.version===1)throw Error(`V1 transactions cannot be serialized by web3.js. Pass the serialized transaction as a Uint8Array instead.`);let r=cr(t,this._account.address),i=sr(t)?t.message.serialize():t.serializeMessage(),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:e.base64.fromBytes(i)}},n);t.addSignature(r,e.base64.toBytes(a))}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.prepare(t),await this.signMessageRpc(e,t)}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n,cause:t})}}async handleSignAndSendTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.prepare(t);let{transaction:n,connection:r,options:i}=e.params,a;return n instanceof Uint8Array?a=await this.signSerializedTransaction(n,t):(await this.signTransactionObject(n,t),a=n.serialize()),{signature:await r.sendRawTransaction(a,i)}}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n,cause:t})}}async handleSignTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.prepare(t);let{transaction:n}=e.params;return n instanceof Uint8Array?{signedTransaction:await this.signSerializedTransaction(n,t)}:(await this.signTransactionObject(n,t),{signedTransaction:n})}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n,cause:t})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},ur=class extends lr{_proxy;_entropyId;_entropyIdVerifier;_onNeedsRecovery;constructor({proxy:e,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:r,...i}){super(i),this._proxy=e,this._entropyId=t,this._entropyIdVerifier=n,this._onNeedsRecovery=r}async prepare(e){try{await this._proxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:e})}catch(t){let n=Bn(t);if(n&&this._account.recovery_method===`privy`)await this._proxy.recover({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:e});else if(n&&this._onNeedsRecovery){let e;await new Promise(async(t,n)=>{e=setTimeout(()=>n(new E({code:`embedded_wallet_recovery_error`,error:`User-owned recovery timed out`})),12e4),await this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>t(!0)})}).finally(()=>clearTimeout(e))}else throw t}}async signMessageRpc(e,t){return(await this._proxy.rpcWallet({accessToken:t,request:e,chainType:`solana`,hdWalletIndex:this._account.wallet_index,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier})).response.data}async signSerializedTransaction(t,n){let{messageBytes:r,signerIndex:i}=$n({transaction:t,address:this._account.address}),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:e.base64.fromBytes(r)}},n);return er({transaction:t,signerIndex:i,signature:e.base64.toBytes(a)})}};let M;async function dr(){if(!M){let{tempo:e,tempoModerato:t}=await import(`./tempoChains-CJGgHPcv.mjs`);M={tempo:e,tempoModerato:t}}return M}function fr(){return M!==void 0}const pr=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new Rn(`Unsupported chainId ${e}`,4901);let o=hr(a,n,r.appId);if(mr(i)){if(!M)throw new Rn(`Tempo chains are not loaded for chainId ${e}; await loadTempoChains() first`,4901);let t=i===Nt.id?M.tempo:M.tempoModerato;return Rt({transport:Gt(o),chain:t})}return Rt({transport:Gt(o),chain:a})};function mr(e){return e===Nt.id||e===Pt.id}const hr=(e,t,n)=>{let r=e.id,i=Number(e.id),a;if(e.rpcUrls.privyWalletOverride&&e.rpcUrls.privyWalletOverride.http[0])a=e.rpcUrls.privyWalletOverride.http[0];else if(t.rpcUrls&&t.rpcUrls[i])a=t.rpcUrls[i];else if(e.rpcUrls.privy?.http[0]){let t=new URL(e.rpcUrls.privy.http[0]);t.searchParams.append(`privyAppId`,n),a=t.toString()}else a=e.rpcUrls.public?.http[0]?e.rpcUrls.public.http[0]:e.rpcUrls.default?.http[0];if(!a)throw new Rn(`No RPC url found for ${r}`);return a};function gr({currentRecoveryMethod:e,upgradeToRecoveryMethod:t}){switch(e){case`privy`:case`user-passcode`:case`recovery-encryption-key`:return!0;case`icloud`:case`google-drive`:if(e===t)throw Error(`Cannot upgrade to the existing cloud platform`);return!0;default:throw Error(`Unknown recovery method`)}}const _r=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var vr=class extends It{_privyInternal;_account;_chainId;_chains;_client;_clientReady;_appApi;_dataSuffixPlugin;constructor({privyInternal:e,account:t,chains:n,chainId:r=n[0].id,appApi:i,dataSuffixPlugin:a}){super(),this._privyInternal=e,this._account=t,this._chainId=r,this._chains=n,this.updateClient(i.appId),this._appApi=i,this._dataSuffixPlugin=a}async request(e){if(await this.awaitClientReady(),_r.has(e.method))return this.handleIFrameRpc(e);switch(e.method){case`eth_accounts`:case`eth_requestAccounts`:return this._account.address?[this._account.address]:[];case`eth_chainId`:return`0x${this._chainId.toString(16)}`;case`wallet_switchEthereumChain`:return this.handleSwitchEthereumChain(e);case`eth_estimateGas`:return this.handleEstimateGas(e);case`eth_signTransaction`:{let t=this.applyDataSuffix(e.params?.[0]);return this.handleSignTransaction(t)}case`eth_sendTransaction`:{let t=this.applyDataSuffix(e.params?.[0]);return this.handleSendTransaction(t)}case`eth_populateTransactionRequest`:{let t=e.params?.[0];return this.handlePopulateTransaction(t)}default:return this.handleJsonRpc(e)}}applyDataSuffix(e){if(!this._dataSuffixPlugin||C(e))return e;let t=typeof e.data==`string`?e.data:`0x`;return{...e,data:this._dataSuffixPlugin.appendDataSuffix({data:t})}}async ensureChainId(e){let t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),await this.awaitClientReady(),t}async awaitClientReady(){for(;this._clientReady;){let e=this._clientReady;await e,this._clientReady===e&&(this._clientReady=void 0)}}internalSwitchEthereumChain(e){!e||Number(e)===this._chainId||(this._chainId=Number(e),this.updateClient(this._privyInternal.appId),this.emit(`chainChanged`,e))}updateClient(e){let t=this._chainId,n=()=>pr(t,this._chains,{rpcUrls:[]},{appId:e});if(!mr(t)||fr()){this._client=n(),this._clientReady=void 0;return}let r=dr().then(()=>{this._chainId===t&&(this._client=n())});this._clientReady=r,r.catch(()=>{})}async handlePopulateTransaction(e){let t=await this.ensureChainId(e);if(C(t)){let e=tn(t),n=en(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:$t}}let n=nn(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:Qt[i.type],authorizationList:t.authorizationList}}async handleSignTransaction(e){let t={...e};for(let e of Object.keys(t)){let n=t[e];typeof n==`bigint`&&(t[e]=Xt(n))}return C(t)&&(t.calls=t.calls.map(e=>({...e,value:typeof e.value==`bigint`?Xt(e.value):e.value}))),await this.handleIFrameRpc({method:`eth_signTransaction`,params:[t]})}async handleSendTransaction(e){let t=await this.handlePopulateTransaction(e),n=await this.handleSignTransaction(t);return await this.handleJsonRpc({method:`eth_sendRawTransaction`,params:[n]})}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error(`Invalid params for eth_estimateGas`);let t=e.params?.[0],n=await this.ensureChainId(t);if(C(n)){let e=tn(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=nn(n);return await this._client.estimateGas({account:n.from??this._account.address,...r})}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new zn(`Invalid params for ${e.method}`,4200);let t;if(typeof e.params[0]==`string`)t=e.params[0];else if(`chainId`in e.params[0]&&typeof e.params[0].chainId==`string`)t=e.params[0].chainId;else throw new zn(`Invalid params for ${e.method}`,4200);this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.signWithWallet(e,t)}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new E({code:`embedded_wallet_request_error`,error:n,cause:t})}}async handleJsonRpc(e){return this._client.request(e)}requireTempoClient(){if(!mr(this._chainId))throw new zn(`Cannot send a Tempo (type 118) transaction on chain ${this._chainId}`,4901);return this._client}toJSON(){return`PrivyEIP1193Provider { address: '${this._account.address}', chainId: ${this._chainId}, request: [Function] }`}},yr=class extends vr{_walletProxy;_entropyId;_entropyIdVerifier;_onNeedsRecovery;constructor({walletProxy:e,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:r,...i}){super(i),this._walletProxy=e,this._entropyId=t,this._entropyIdVerifier=n,this._onNeedsRecovery=r}async signWithWallet(e,t){try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t})}catch(e){let n=Bn(e);if(n&&this._account.recovery_method===`privy`)await this._walletProxy.recover({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t});else if(n&&this._onNeedsRecovery){let e;await new Promise(async(t,n)=>{e=setTimeout(()=>n(new E({code:`embedded_wallet_recovery_error`,error:`User-owned recovery timed out`})),12e4),await this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>t(!0)})}).finally(()=>clearTimeout(e))}else throw e}return(await this._walletProxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:`ethereum`})).response.data}};async function N(t,n){let r;if(n instanceof Uint8Array)r=e.base64.fromBytes(n);else{let t=rn(n);if(t===void 0)throw new E({error:`Failed to prepare the payload for signing`,code:`invalid_input`});r=e.base64.fromBytes(e.utf8.toBytes(t))}let{signature:i}=await t({message:r});return{signature:i}}const P=`privy-request-expiry`,F=1800*1e3;async function I(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath(_t,{params:{wallet_id:n}}),o=String(Date.now()+F),{signature:s}=await N(t,{version:1,url:a,method:_t.method,headers:{"privy-app-id":e.app.appId,[P]:o},body:{...i}});if(Date.now()>Number(o))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(_t,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[P]:o,...r??{}}})}function br(e){return C(e)?Sr(e):xr(e)}function xr(e){return{from:e.from,to:e.to??void 0,nonce:L(e.nonce),chain_id:L(e.chainId),data:Er(e.data),value:L(e.value),type:Or(e.type),gas_limit:L(e.gasLimit??e.gas),gas_price:L(e.gasPrice),max_fee_per_gas:L(e.maxFeePerGas),max_priority_fee_per_gas:L(e.maxPriorityFeePerGas),authorization_list:e.authorizationList?.map(e=>{let t=e.yParity??(e.v===void 0?0:Number(e.v)-27);if(t!==0&&t!==1)throw Error(`EIP-7702 authorizations require a valid yParity value`);return{contract:e.address,chain_id:Ar(e.chainId,`chainId`),nonce:Ar(e.nonce,`nonce`),r:e.r,s:e.s,y_parity:t}})}}function Sr(e){return{type:$t,from:e.from,chain_id:L(e.chainId),nonce:L(e.nonce),nonce_key:L(e.nonceKey),gas_limit:L(e.gasLimit),max_fee_per_gas:L(e.maxFeePerGas),max_priority_fee_per_gas:L(e.maxPriorityFeePerGas),fee_token:e.feeToken,valid_after:L(e.validAfter),valid_before:L(e.validBefore),fee_payer_signature:wr(e.feePayerSignature),access_list:Cr(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:L(e.value)}))}}function Cr(e){if(e)return Array.isArray(e)?e.map(e=>`address`in e?{address:e.address,storage_keys:[...e.storageKeys]}:{address:e[0],storage_keys:[...e[1]]}):Object.entries(e).map(([e,t])=>({address:e,storage_keys:[...t]}))}function wr(e){if(!e)return;let t=Tr(e);if(t!==0&&t!==1)throw Error(`Tempo fee payer signatures require a valid yParity value`);return{r:e.r,s:e.s,y_parity:t}}function Tr(e){if(e.yParity!==void 0)return e.yParity;if(e.v!==void 0)return Number(e.v)-27}function Er(e){if(e!==void 0)return typeof e==`string`?bn(e):yn(Uint8Array.from(e))}const Dr=[0,2,4];function Or(e){if(e==null)return;let t=Number(e);if(!kr(t))throw Error(`Invalid transaction type: expected ${Dr.join(`, `)} as a number or hex string, got "${e}".`);return t}function kr(e){return Dr.includes(e)}function L(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(vn(e))return e;throw Error(`Invalid quantity string: expected a hex-prefixed value (0x…), got "${e}". Use a number, bigint, or hex string instead.`)}}function Ar(e,t){let n=L(e);if(n===void 0)throw Error(`EIP-7702 authorization ${t} is required`);return n}function jr(e){return typeof e==`string`&&(e=JSON.parse(e)),{types:e.types,primary_type:String(e.primaryType),domain:e.domain,message:e.message}}async function Mr({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return Nr({context:e,account:t,rpcRequest:n.request});case`solana`:return Pr({context:e,account:t,rpcRequest:n.request})}}async function Nr({context:e,account:t,rpcRequest:n}){switch(n.method){case`personal_sign`:{let[r]=n.params,i=await I(e,e.signRequest,{chain_type:`ethereum`,method:`personal_sign`,wallet_id:t.id,params:r.startsWith(`0x`)?{message:r.slice(2),encoding:`hex`}:{message:r,encoding:`utf-8`}});if(i.method!==`personal_sign`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`eth_signTransaction`:{let[r]=n.params,i=await I(e,e.signRequest,{chain_type:`ethereum`,method:`eth_signTransaction`,wallet_id:t.id,params:{transaction:br(r)}});if(i.method!==`eth_signTransaction`)throw Error(`Unable to sign transaction`);return{data:i.data.signed_transaction}}case`eth_signTypedData_v4`:{let[,r]=n.params,i=await I(e,e.signRequest,{chain_type:`ethereum`,method:n.method,wallet_id:t.id,params:{typed_data:jr(r)}});if(i.method!==`eth_signTypedData_v4`)throw Error(`Unable to sign typed data`);return{data:i.data.signature}}case`eth_sign`:{let[,r]=n.params,i=await I(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:bn(r)}});if(i.method!==`secp256k1_sign`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`secp256k1_sign`:{let[r]=n.params,i=await I(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:bn(r)}});if(i.method!==`secp256k1_sign`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`csw_signUserOperation`:case`eth_sendTransaction`:case`eth_populateTransactionRequest`:throw Error(`This wallet does not support the method: ${n.method}`)}}async function Pr({context:e,account:t,rpcRequest:n}){switch(n.method){case`signMessage`:{let{message:r}=n.params,i=await I(e,e.signRequest,{chain_type:`solana`,method:`signMessage`,wallet_id:t.id,params:{message:r,encoding:`base64`}});if(i.method!==`signMessage`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`signTransaction`:{let{transaction:r}=n.params,i=await I(e,e.signRequest,{chain_type:`solana`,method:`signTransaction`,wallet_id:t.id,params:{transaction:r,encoding:`base64`}});if(i.method!==`signTransaction`)throw Error(`Unable to sign transaction`);return{data:i.data.signed_transaction}}}}const Fr=async({callback:e,onMfaEnrollmentRequired:t,onMfaVerificationRequired:n})=>{let r=!1,i=!1;for(;;)try{return await e()}catch(e){if(!(e instanceof T))throw e;if(e.code===an.MISSING_MFA_ENROLLMENT){if(!t||r)throw e;r=!0;let{user:n}=await t({error:e});if(!n?.mfa_methods.length)throw e;continue}if(e.code===an.MFA_REQUIRED){if(!n||i)throw e;i=!0,await n({error:e});continue}throw e}};var Ir=class extends lr{_app;_signRequest;_onMfaEnrollmentRequired;_onMfaVerificationRequired;constructor({app:e,signRequest:t,onMfaEnrollmentRequired:n,onMfaVerificationRequired:r,...i}){super(i),this._app=e,this._signRequest=t,this._onMfaEnrollmentRequired=n,this._onMfaVerificationRequired=r}async prepare(){}async signMessageRpc(e){return{signature:await this.signWithWallet(e)}}async signSerializedTransaction(t){let n=await this.signWithWallet({method:`signTransaction`,params:{transaction:e.base64.fromBytes(t)}});return new Uint8Array(e.base64.toBytes(n))}async signWithWallet(e){return await Fr({callback:async()=>{let{data:t}=await Mr({context:{app:this._app,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:this._signRequest},account:this._account,rpcRequest:{chainType:`solana`,request:e}});return t},onMfaEnrollmentRequired:this._onMfaEnrollmentRequired,onMfaVerificationRequired:this._onMfaVerificationRequired})}},Lr=class extends vr{_signRequest;_onMfaEnrollmentRequired;_onMfaVerificationRequired;constructor({signRequest:e,onMfaEnrollmentRequired:t,onMfaVerificationRequired:n,...r}){super(r),this._signRequest=e,this._onMfaEnrollmentRequired=t,this._onMfaVerificationRequired=n}async signWithWallet(e){return await Fr({callback:async()=>{let{data:t}=await Mr({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:this._signRequest},account:this._account,rpcRequest:{chainType:`ethereum`,request:e}});return t},onMfaEnrollmentRequired:this._onMfaEnrollmentRequired,onMfaVerificationRequired:this._onMfaVerificationRequired})}};async function Rr(e,{request:t,headers:n}){return await e.fetchPrivyRoute(ft,{body:t,headers:n})}async function zr({context:e,chainType:t,idempotencyKey:n}){return{wallet:await Rr(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}const R=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`;var Br=class{_privyInternal;_proxy;_chains=Array.from(wt);_mfa;_mfaPromises;_appApi;_dataSuffixPlugin;_signRequest=e=>this.signWithUserSigner(e);constructor(e,t,n,r,i,a,o){if(this._privyInternal=e,t&&(this._proxy=new Qn(t,i),r.setProxy(this._proxy)),n){let e=kt(n);this._chains=e}this._mfa=r,this._mfaPromises=i,this._appApi=a,this._dataSuffixPlugin=o}setMessagePoster(e){if(this._proxy){this._proxy.retarget(e);return}this._proxy=new Qn(e,this._mfaPromises),this._mfa.setProxy(this._proxy)}async signWithUserSigner(e){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new E({error:`User must be logged in to sign a message with the user signer`,code:`user_signer_sign_error`});let{signature:n}=await this._proxy.signWithUserSigner({accessToken:t,message:e.message});return{signature:n}}async add(e){let t;if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)t=(await zr({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:e.chainType})).wallet.address;else{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(!e.entropyId)throw new E({error:`Missing entropy details for wallet creation`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new E({error:`User must be logged in to create an embedded wallet`,code:`embedded_wallet_creation_error`});t=(await this._proxy.addWallet({accessToken:n,...e})).address}let{user:n}=await this._privyInternal.refreshSession();return{user:n,account:n.linked_accounts.filter(R).find(n=>n.chain_type===e.chainType&&Ct(n.address,t))}}async getBitcoinProvider({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(!await this._privyInternal.getAccessTokenInternal())throw Error(`User must be logged in to create an embedded wallet`);return O(e)||await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new jn({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n})}async create({password:e,recoveryMethod:t,recoveryToken:n,recoveryKey:r,recoverySecretOverride:i,iCloudRecordNameOverride:a,solanaAccount:o,skipCallbacks:s,idempotencyKey:c}){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`){if(t&&!t.startsWith(`privy`))throw new E({error:`User-controlled server wallets do not support custom recovery methods`,code:`embedded_wallet_creation_error`});await zr({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`ethereum`,idempotencyKey:c})}else{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let s;if(s=t||(e?`user-passcode`:`privy`),e&&typeof e!=`string`)throw Error(`Invalid recovery password, must be a string`);if(s===`privy`&&this._privyInternal.config?.embedded_wallet_config.require_user_password_on_create)throw Error(`Password not provided yet is required by App configuration`);let c=await this._privyInternal.getAccessTokenInternal();if(!c)throw Error(`User must be logged in to create an embedded wallet`);let{address:l}=await this._proxy.create({accessToken:c,recoveryMethod:s,recoveryKey:r,recoveryPassword:e,recoveryAccessToken:n,recoverySecretOverride:i,iCloudRecordNameOverride:a,solanaAddress:o?.address});if(!l)throw Error(`Failed to create wallet`)}return await this._privyInternal.refreshSession(s)}async importWallet({privateKey:e,chainType:t,additionalSigners:n}){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let r=this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`?`tee`:`on-device`;if(n&&r===`on-device`)throw new E({error:`Specifying additionalSigners is only supported for TEE execution and this app uses on-device execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`,code:`invalid_input`});let i=await this._privyInternal.getAccessTokenInternal();if(!i)throw new E({error:`User must be logged in to import an embedded wallet`,code:`embedded_wallet_before_logged_in`});let{address:a}=await this._proxy.importWallet({accessToken:i,privateKey:e,chainType:t,mode:r,additionalSigners:n});if(!a)throw new E({error:`Failed to import wallet`,code:`embedded_wallet_creation_error`});let{session_update_action:o,...s}=await this._privyInternal.refreshSession();return{address:a,user:s}}async createSolana(e){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await zr({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`solana`,idempotencyKey:e?.idempotencyKey});else{if(!this._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new E({error:`User must be logged in to create an embedded wallet`,code:`embedded_wallet_creation_error`});e?.ethereumAccount&&await this.getProvider(e.ethereumAccount);let{publicKey:n}=await this._proxy.createSolana({accessToken:t,ethereumAddress:e?.ethereumAccount?.address});if(!n)throw new E({error:`Failed to create wallet`,code:`embedded_wallet_creation_error`})}return await this._privyInternal.refreshSession()}async delegateWallets({delegatedWallets:e,rootWallet:t}){if(!this._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new E({error:`User must be logged in to create an embedded wallet`,code:`embedded_wallet_creation_error`});await this._proxy.delegateWallets({accessToken:n,delegatedWallets:e,rootWallet:t})}async getProvider(e,t,n,r,i,a,o){if(O(e))return new Lr({account:e,privyInternal:this._privyInternal,chains:this._chains,signRequest:this._signRequest,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin,onMfaEnrollmentRequired:a,onMfaVerificationRequired:o});if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new yr({account:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin})}async getEthereumProvider({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o,onNeedsRecovery:s,onMfaEnrollmentRequired:c,onMfaVerificationRequired:l}){if(!await this._privyInternal.getAccessTokenInternal())throw Error(`User must be logged in to create an embedded wallet`);if(O(e))return new Lr({account:e,privyInternal:this._privyInternal,chains:this._chains,signRequest:this._signRequest,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin,onMfaEnrollmentRequired:c,onMfaVerificationRequired:l});if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new yr({account:e,entropyId:t,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,onNeedsRecovery:s,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin})}async getSolanaProvider(e,t,n,r,i,a,o,s,c){if(O(e))return new Ir({account:e,privyInternal:this._privyInternal,signRequest:this._signRequest,app:this._appApi,onMfaEnrollmentRequired:s,onMfaVerificationRequired:c});if(!this._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new ur({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:o})}async setRecovery(e){let{wallet:t,...n}=e;if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(O(t))throw new E({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});gr({currentRecoveryMethod:t.recovery_method,upgradeToRecoveryMethod:n.recoveryMethod===`icloud-native`?`icloud`:n.recoveryMethod}),await this._load(t.chain_type===`solana`?{wallet:t,entropyId:t.address,entropyIdVerifier:`solana-address-verifier`}:{wallet:t,entropyId:t.address,entropyIdVerifier:`ethereum-address-verifier`});let r=await this._privyInternal.getAccessTokenInternal();if(!r)throw Error(`User must be logged in to interact with embedded wallets`);let i=t.recovery_method;this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_set_recovery_started`,{address:t.address,target_recovery_method:n.recoveryMethod,existing_recovery_method:i});try{let e;if(n.recoveryMethod===`user-passcode`)e={recoveryMethod:`user-passcode`,recoveryPassword:n.password};else if(n.recoveryMethod===`google-drive`)e={recoveryMethod:`google-drive`,recoveryAccessToken:n.recoveryAccessToken};else if(n.recoveryMethod===`icloud`)e={recoveryMethod:`icloud`,recoveryAccessToken:n.recoveryAccessToken};else if(n.recoveryMethod===`icloud-native`)e={recoveryMethod:`icloud-native`,iCloudRecordNameOverride:n.iCloudRecordNameOverride,recoverySecretOverride:n.recoverySecretOverride};else if(n.recoveryMethod===`recovery-encryption-key`)e={recoveryMethod:`recovery-encryption-key`,recoveryKey:n.recoveryKey};else if(n.recoveryMethod===`privy`)e={recoveryMethod:`privy`};else throw Error(`Unknown recovery method: ${n.recoveryMethod}`);await this._proxy.setRecovery({accessToken:r,entropyId:t.address,entropyIdVerifier:t.chain_type===`solana`?`solana-address-verifier`:`ethereum-address-verifier`,...e}),this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_set_recovery_completed`,{address:t.address,target_recovery_method:n.recoveryMethod,existing_recovery_method:i});let{user:a}=await this._privyInternal.refreshSession();return{user:a,provider:t.chain_type===`ethereum`?new yr({account:t,entropyId:t.address,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin}):null}}catch(e){throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_set_recovery_failed`,{address:t.address,recovery_method:t.recovery_method,error:e instanceof Error?e.message:`Unable to recover wallet`}),e}}getURL(){let e=new URL(`${this._privyInternal.baseUrl}/apps/${this._privyInternal.appId}/embedded-wallets`);return this._privyInternal.caid&&e.searchParams.append(`caid`,this._privyInternal.caid),this._privyInternal.appClientId&&e.searchParams.append(`client_id`,this._privyInternal.appClientId),e.href}get chains(){return this._chains}onMessage(e){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return this._proxy.handleEmbeddedWalletMessages(e)}reload(){if(!this._proxy){this._privyInternal.logger.warn(`Attempted to reload proxy before initialized`);return}this._proxy.reload()}onBackground(){this._proxy?.onBackground()}async ping(e){try{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return await this._proxy.ping(e),!0}catch(e){return this._privyInternal.logger.debug(e),!1}}async _load({entropyId:e,entropyIdVerifier:t,wallet:n,recoveryPassword:r,recoveryKey:i,recoveryAccessToken:a,recoverySecretOverride:o}){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let s=await this._privyInternal.getAccessTokenInternal();if(!s)throw Error(`User must be logged in to interact with embedded wallets`);try{return await this._proxy.connect({accessToken:s,entropyId:e,entropyIdVerifier:t}),e}catch(c){if(Bn(c)){try{if(n.recovery_method===`privy`){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let r=await this._proxy.recover({accessToken:s,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),r.entropyId}if(n.recovery_method===`user-passcode`&&r){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let i=await this._proxy.recover({accessToken:s,recoveryPassword:r,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),i.entropyId}if([`google-drive`,`icloud`].includes(n.recovery_method)&&a){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let r=await this._proxy.recover({accessToken:s,recoveryAccessToken:a,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),r.entropyId}if(n.recovery_method===`icloud`&&o){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:`icloud-native`});let r=await this._proxy.recover({accessToken:s,recoverySecretOverride:o,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:`icloud-native`}),r.entropyId}if(n.recovery_method===`recovery-encryption-key`&&i){this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_started`,{address:n.address,recovery_method:n.recovery_method});let r=await this._proxy.recover({accessToken:s,recoveryKey:i,entropyId:e,entropyIdVerifier:t});return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_completed`,{address:n.address,recovery_method:n.recovery_method}),r.entropyId}}catch(t){throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_recovery_failed`,{address:n.address,recovery_method:n.recovery_method,error:t instanceof Error?t.message:`Unable to recover wallet: ${e}`}),t}throw c}else throw c}}},Vr=class extends It{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const Hr=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let Ur=!1;const Wr=()=>{if(Ur)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;Ur=typeof t==`string`&&t.length>0||typeof n==`string`&&Hr.includes(n)}catch{Ur=!0}return Ur},z={get(e){return sn.get(e)},set(e,t,n){Wr()||sn.set(e,t,n)},remove(e){sn.remove(e)}},Gr=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!Wr(),Kr=`privy:active-user`,qr=`privy:saved-users`,B=e=>e?`privy:${e}:token`:`privy:token`,V=e=>e?`privy:${e}:pat`:`privy:pat`,H=e=>e?`privy:${e}:refresh_token`:`privy:refresh_token`,U=e=>e?`privy:${e}:id-token`:`privy:id-token`,Jr=e=>e?`privy-${e}-token`:`privy-token`,Yr=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,Xr=e=>e?`privy-${e}-id-token`:`privy-id-token`,W=e=>e?`privy-${e}-session`:`privy-session`,G=Promise.allSettled.bind(Promise)??(e=>Promise.all(e.map(e=>e.then(e=>({status:`fulfilled`,value:e})).catch(e=>({status:`rejected`,reason:e}))))),Zr=[`storage_cleared`,`token_cleared`,`refresh_token_cleared`,`identity_token_cleared`,`token_stored`,`refresh_token_stored`,`identity_token_stored`,`oauth_tokens_granted`,`error_storing_tokens`];var Qr=class extends It{static events=Zr;_storage;_isUsingServerCookies=!1;_cookieWriteBehavior;GUEST_CREDENTIAL_STORAGE_KEY;_setStoredUsers;_hasEmittedStoredUsers=!1;constructor(e){super(),this._storage=e.storage,this._isUsingServerCookies=e.isUsingServerCookies,this._cookieWriteBehavior=e.cookieWriteBehavior,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`,this._setStoredUsers=e.setStoredUsers}set isUsingServerCookies(e){this._isUsingServerCookies=e}shouldWriteCookies(){return Gr({useServerCookies:this._isUsingServerCookies,cookieWriteBehavior:this._cookieWriteBehavior})}writeCookie(e,t,n){this.shouldWriteCookies()&&z.set(e,t,n)}setStoredUsersCallback(e){this._setStoredUsers=e,this.getSavedUserIds().then(e=>{this._hasEmittedStoredUsers||this._setStoredUsers?.({users:e.map(e=>({id:e}))})})}async getCustomerAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(B(e));try{return typeof t==`string`?new D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(V(e));try{return typeof t==`string`?new D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async getRefreshToken(){let e=await this.getActiveUserId(),t=await this._storage.get(H(e));return typeof t==`string`?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(U(e));return typeof t==`string`?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=z.get(W(e));if(t!==void 0&&t.length>0)return!0;let n=z.get(W(null));return n!==void 0&&n.length>0}catch(e){console.error(e)}return!1}async hasRefreshCredentials(e,t){return await this.mightHaveServerCookies()||typeof e==`string`&&typeof t==`string`}tokenIsActive(e){if(!e)return!1;let t=D.parse(e);return t!==null&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),n=[this._storage.del(B(null)),this._storage.del(V(null)),this._storage.del(H(null)),this._storage.del(U(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(Kr)];t&&n.push(this._storage.del(B(t)),this._storage.del(V(t)),this._storage.del(H(t)),this._storage.del(U(t)),this.removeSavedUserId(t)),await G(n),z.remove(Jr(null)),z.remove(Yr(null)),z.remove(Xr(null)),z.remove(W(null)),t&&(z.remove(Jr(t)),z.remove(Yr(t)),z.remove(Xr(t)),z.remove(W(t))),e?.reason&&this.emit(`storage_cleared`,{reason:e.reason})}async storeCustomerAccessToken(e){let t=await this.getActiveUserId();await this.storeCustomerAccessTokenForUser(t,e)}async storeCustomerAccessTokenForUser(e,t){let n=B(e),r=Jr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),z.remove(r),e!==null&&this.emit(`token_cleared`,{reason:`set_with_non_string_value`})}}async storePrivyAccessToken(e){let t=await this.getActiveUserId();await this.storePrivyAccessTokenForUser(t,e)}async storePrivyAccessTokenForUser(e,t){let n=V(e);typeof t==`string`?await this._storage.put(n,t):await this._storage.del(n)}async storeRefreshTokenForUser(e,t){let n=H(e),r=Yr(e),i=W(e);typeof t==`string`?(await this._storage.put(n,t),this.writeCookie(i,`t`,{sameSite:`Strict`,secure:!0,expires:30}),this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:30}),this.emit(`refresh_token_stored`,{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(n),z.remove(r),z.remove(i),this.emit(`refresh_token_cleared`,{reason:`set_with_non_string_value`}))}async updateWithTokensResponse(e){let t=e.user.id,n=(await G([this.storeCustomerAccessTokenForUser(t,e.token),this.storePrivyAccessTokenForUser(t,e.privy_access_token),this.storeRefreshTokenForUser(t,e.refresh_token),this.storeIdentityTokenForUser(t,e.identity_token)])).filter(e=>e.status===`rejected`);if(n.length>0){this.emit(`error_storing_tokens`,n.map(e=>String(e.reason)).join(`, `));return}let r=(await G([this.storeCustomerAccessTokenForUser(null,e.token),this.storePrivyAccessTokenForUser(null,e.privy_access_token),this.storeRefreshTokenForUser(null,e.refresh_token),this.storeIdentityTokenForUser(null,e.identity_token)])).filter(e=>e.status===`rejected`);if(r.length>0){this.emit(`error_storing_tokens`,r.map(e=>String(e.reason)).join(`, `));return}await this.storeActiveUserId(t);let i=(await G([this.processOAuthTokens(e.oauth_tokens)])).filter(e=>e.status===`rejected`);i.length>0&&this.emit(`error_storing_tokens`,i.map(e=>String(e.reason)).join(`, `))}async backfillLegacySession(){if(await this.getActiveUserId())return;let[e,t,n,r]=await Promise.all([this._storage.get(B(null)),this._storage.get(V(null)),this._storage.get(H(null)),this._storage.get(U(null))]);if(typeof e!=`string`||typeof n!=`string`)return;let i=D.parse(e)?.subject;if(typeof i!=`string`||i.length===0)return;let a=[this.storeCustomerAccessTokenForUser(i,e),this.storeRefreshTokenForUser(i,n)];typeof t==`string`&&a.push(this.storePrivyAccessTokenForUser(i,t)),typeof r==`string`&&a.push(this.storeIdentityTokenForUser(i,r));let o=(await G(a)).filter(e=>e.status===`rejected`);if(o.length>0){this.emit(`error_storing_tokens`,o.map(e=>String(e.reason)).join(`, `));return}await this.storeActiveUserId(i)}async processOAuthTokens(e){e&&this.emit(`oauth_tokens_granted`,e)}async storeIdentityToken(e){let t=await this.getActiveUserId();await this.storeIdentityTokenForUser(t,e)}async storeIdentityTokenForUser(e,t){let n=U(e),r=Xr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`identity_token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),z.remove(r),e!==null&&this.emit(`identity_token_cleared`,{reason:`set_with_non_string_value`})}}async getOrCreateGuestCredential(){let t=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(t&&typeof t==`string`)return t;let n=e.base64urlnopad.fromBytes(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,n),n}async getActiveUserId(){let e=await this._storage.get(Kr);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(Kr,e)}async getSavedUserIds(){let e=await this._storage.get(qr);if(typeof e!=`string`)return[];try{let t=JSON.parse(e),n=Array.isArray(t)?t.filter(e=>typeof e==`string`):[];return[...new Set(n)]}catch{return[]}}async storeSavedUserIds(e){let t=[...new Set(e)];t.length>0?await this._storage.put(qr,JSON.stringify(t)):await this._storage.del(qr),this._setStoredUsers&&(this._hasEmittedStoredUsers=!0,this._setStoredUsers({users:t.map(e=>({id:e}))}))}async removeSavedUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds(t.filter(t=>t!==e))}async switchActiveUserId(e){if(!(await this.getSavedUserIds()).includes(e))throw new E({code:`invalid_input`,error:`Cannot switch active user because the user ID is not saved on this device`});await this._storage.put(Kr,e)}};const $r=e=>{let t=new AbortController,n=e.filter(e=>!!e),r=()=>{for(let e of n)e.removeEventListener(`abort`,r);t.abort(n.find(e=>e.aborted)?.reason)};if(n.some(e=>e.aborted))r();else for(let e of n)e.addEventListener(`abort`,r);return t.signal},ei=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function ti(e){let t=new URLSearchParams;for(let n in e)e[n]!=null&&t.append(n,String(e[n]));return Array.from(t).length?`?`+t.toString():``}const ni=()=>void 0,K={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},ri=({level:e,logger:t})=>({get level(){return e},error:K[e]>=K.ERROR?t.error:ni,warn:K[e]>=K.WARN?t.warn:ni,info:K[e]>=K.INFO?t.info:ni,debug:K[e]>=K.DEBUG?t.debug:ni}),ii=`privy:caid`;var ai=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.79.4`;_fetch;nativeAppIdentifier;_crypto;isMultiUserModeEnabled;_cache=new Map;constructor(e){this.logger=ri({level:e.logger?.level??e.logLevel??`ERROR`,logger:e.logger??console}),this._storage=e.storage,this._crypto=e.crypto,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=e.baseUrl??`https://auth.privy.io`,this.appId=e.appId,this.appClientId=e.appClientId,this._sdkVersion=e.sdkVersion??this._sdkVersion,this.callbacks=e.callbacks,this.nativeAppIdentifier=e.nativeAppIdentifier,this.isMultiUserModeEnabled=e.isMultiUserModeEnabled,this.session=new Qr({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=on(globalThis.fetch),this.session.on(`error_storing_tokens`,e=>{this.createAnalyticsEvent(`error_updating_tokens_in_storage`,{reason:e})})}setCallbacks(e){this.callbacks={...this.callbacks,...e},this.session.setStoredUsersCallback(this.callbacks?.setStoredUsers)}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady){this.callbacks?.setIsReady?.(!0);return}if(!await this.isStorageAccessible())throw new E({code:`storage_error`,error:`Unable to access storage`});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.isMultiUserModeEnabled&&await this.session.backfillLegacySession(),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith(`js-sdk-core:`)&&this.createAnalyticsEvent(`sdk_initialize`,{})}getPath(e,{params:t,query:n}){return`${this.baseUrl}${xt(e.path,t)}${ti(n)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new E({code:`invalid_input`,error:`Unauthenticated requests require sessions.mode to be set to "multi-user"`});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:n,query:r,headers:i,signal:a,onRequest:o=this._beforeRequest.bind(this)}){let s=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),c=await o(s);a&&(c.signal=$r([a,c.signal]));let l=await this._fetch(s,c),u=await l.json();if(l.status>299)throw new T({...u,status:l.status});return u}async fetchRaw(e,{body:t,params:n,query:r,headers:i,onRequest:a=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),s=await a(o),c=await this._fetch(o,s);if(c.status>299)throw new T({...await c.json().catch(()=>({})),status:c.status});return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getPrivyAccessToken()??await this.session.getCustomerAccessToken(),n=new Headers(e.headers);n.set(`privy-app-id`,this.appId),this.appClientId&&n.set(`privy-client-id`,this.appClientId),n.set(`privy-client`,this._sdkVersion),t&&n.set(`Authorization`,`Bearer ${t}`),n.set(`Content-Type`,`application/json`),n.set(`Accept`,`application/json`);let r=await this._getOrGenerateClientAnalyticsId();return r&&n.set(`privy-ca-id`,r),this.nativeAppIdentifier&&n.set(`x-native-app-identifier`,this.nativeAppIdentifier),{signal:ei(2e4),headers:n,credentials:`include`}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequestWithoutAuth(e){await this._initialize();let t=new Headers(e.headers);t.set(`privy-app-id`,this.appId),this.appClientId&&t.set(`privy-client-id`,this.appClientId),t.set(`privy-client`,this._sdkVersion),t.set(`Content-Type`,`application/json`),t.set(`Accept`,`application/json`);let n=await this._getOrGenerateClientAnalyticsId();return n&&t.set(`privy-ca-id`,n),this.nativeAppIdentifier&&t.set(`x-native-app-identifier`,this.nativeAppIdentifier),{signal:ei(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(ii);if(typeof e==`string`&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error(`Unable to load clientId`,e)}try{this._analyticsId=this._crypto.randomUUID()}catch(e){this.logger.error(`Unable to generate uuidv4`,e)}if(this._analyticsId){try{await this._storage.put(ii,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}}async destroyClientAnalyticsId(){try{return await this._storage.del(ii)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,t){try{await this.fetch(r,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch{}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new E({code:`storage_error`,error:`Unable to access storage`});let t=await this.session.getRefreshToken()??void 0,n=t??`key`,r=this._cache.get(n);if(r)return this.logger.debug(`[privy:refresh] found in-flight session refresh request, deduping`),await r;let i=this._refreshSession(t,e);this._cache.set(n,i);try{return await i}finally{this._cache.delete(n)}}async _refreshSession(e,t){let n=await this.session.getCustomerAccessToken();if(!await this.session.hasRefreshCredentials(n,e??null))throw this.logger.debug(`[privy:refresh] missing tokens, skipping request`),await this._initialize(),new T({code:an.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});let r;try{this.logger.debug(`[privy:refresh] fetching: ${qe.path}`),r=await this.fetch(qe,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(n){if(this.logger.debug(`[privy:refresh] error: ${n.message??`unknown error`}`),n instanceof T&&n.code===an.MISSING_OR_INVALID_TOKEN){if(await this.hasRefreshTokenChanged(e))return this.logger.debug(`[privy:refresh] session replaced during refresh, refreshing again`),await this.refreshSession(t);await this.session.destroyLocalState(),!t&&this.callbacks?.setUser?.(null)}throw n}if(await this.hasRefreshTokenChanged(e))return this.logger.debug(`[privy:refresh] session replaced during refresh, refreshing again`),await this.refreshSession(t);let i=r.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),i===`set`&&(await this.session.updateWithTokensResponse(r),this.logger.debug(`[privy:refresh] tokens stored`)),i===`clear`&&(await this.session.destroyLocalState(),this.logger.debug(`[privy:refresh] tokens cleared`),!t&&this.callbacks?.setUser?.(null)),i===`ignore`&&(r.token&&(await this.session.storeCustomerAccessToken(r.token),this.logger.debug(`[privy:refresh] token stored (CAT)`)),r.privy_access_token&&(await this.session.storePrivyAccessToken(r.privy_access_token),this.logger.debug(`[privy:refresh] token stored (PAT)`)),r.identity_token&&(this.logger.debug(`[privy:refresh] token stored (IDT)`),await this.session.storeIdentityToken(r.identity_token))),this.logger.debug(`[privy:refresh] returning response`),!t&&this.callbacks?.setUser?.(r.user),r}async hasRefreshTokenChanged(e){return(await this.session.getRefreshToken()??void 0)!==e}async getAccessToken(){let[e,t]=await Promise.all([this.session.getCustomerAccessToken(),this.session.getRefreshToken()]);if(e&&!this.session.tokenIsActive(e)&&await this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),n=await this.session.getCustomerAccessToken();return t.token||this.logger.debug(`[privy:getAccessToken] expected token received null`),t.token===e&&this.logger.debug(`[privy:getAccessToken] expected new token in response received existing`),n===e&&this.logger.debug(`[privy:getAccessToken] expected new token in storage received existing`),t.token??n}return e&&!this.session.tokenIsActive(e)?(this.logger.debug(`[privy:getAccessToken] unable to refresh inactive token`),this.callbacks?.setUser?.(null),await this.session.destroyLocalState(),null):e}async getAccessTokenInternal(){let e=await this.getAccessToken();return await this.session.getPrivyAccessToken()??e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${this._crypto.randomUUID()}`,t=`blobby`;await this._storage.put(e,t);let n=await this._storage.get(e);return await this._storage.del(e),n===t}catch(e){return this.logger.error(e),!1}}},oi=class{_privyInternal;_embedded;_isMultiUserModeEnabled;constructor(e,t,n){this._privyInternal=e,this._embedded=t,this._isMultiUserModeEnabled=n}async get(){let{user:e}=await this._privyInternal.refreshSession();return{user:e}}async acceptTerms(){let e=await this._privyInternal.fetch(n,{});return this._privyInternal.callbacks?.setUser?.(e),{user:e}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(Je,{});return await this._privyInternal.session.storeIdentityToken(t),this._privyInternal.callbacks?.setUser?.(e),{user:e}}async switchActiveUser(e){if(!this._isMultiUserModeEnabled)throw new E({code:`invalid_input`,error:`User switching requires sessions.mode to be set to "multi-user"`});await this._privyInternal.session.switchActiveUserId(e.userId);try{this._embedded.reload();let{user:t}=await this._privyInternal.refreshSession(!0);if(t.id!==e.userId)throw new E({code:`invalid_input`,error:`Cannot switch active user because the refreshed user did not match the requested user ID`});return this._privyInternal.callbacks?.setUser?.(t),{user:t}}catch(e){throw await this._privyInternal.session.destroyLocalState(),this._privyInternal.callbacks?.setUser?.(null),e}}};const si=e=>e?e.linked_accounts.filter(R).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],q=e=>si(e).find(e=>e.wallet_index===0)??null,ci=q,li=e=>e?e.linked_accounts.filter(R).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],ui=e=>li(e).find(e=>e.wallet_index===0)??null,di=(e,t)=>t===`off`||si(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,fi=(e,t)=>t===`off`||li(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,pi=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),J=async(e,t,n)=>{let r=di(t.user,n?.ethereum?.createOnLogin??`off`),i=fi(t.user,n?.solana?.createOnLogin??`off`);if(r&&i){let n=await e.create({recoveryMethod:`privy`,skipCallbacks:!0}),r=await e.createSolana({ethereumAccount:q(n.user)??void 0});return pi(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:ui(t.user)??void 0});return pi(n,t)}if(i){let n=await e.createSolana({ethereumAccount:q(t.user)??void 0});return pi(n,t)}return t};var mi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async syncWithToken(e,t,n){let r=await this._privyInternal.fetchForLogin(d,{body:{token:e,mode:n}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await J(this._embedded,r,t?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithToken(e){await this._privyInternal.fetch(f,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},hi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Ne,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Me,{body:{email:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Pe,{body:{email:e,code:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}async updateEmail({oldEmailAddress:e,newEmailAddress:t,code:n}){await this._privyInternal.fetch(Ve,{body:{oldAddress:e,newAddress:t,code:n}});let r=await this._privyInternal.refreshSession();return{user:r.user,identity_token:r.identity_token}}async unlink(e){await this._privyInternal.fetch(Be,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},gi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth({relyingParty:e,redirectUrl:t,token:n}){return await this._privyInternal.fetch(h,{body:{relying_party:e,redirect_url:t,token:n}})}async getFarcasterStatus({channel_token:e}){return await this._privyInternal.fetch(te,{headers:{"farcaster-channel-token":e}})}async authenticate({channel_token:e,message:t,signature:n,fid:r,mode:i},a){let o=await this._privyInternal.fetchForLogin(m,{body:{channel_token:e,message:t,signature:n,fid:r,mode:i}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await J(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async link({channel_token:e,message:t,signature:n,fid:r}){await this._privyInternal.fetch(ee,{body:{channel_token:e,message:t,signature:n,fid:r}});let i=await this._privyInternal.refreshSession();return{user:i.user,identity_token:i.identity_token}}async unlink({fid:e}){await this._privyInternal.fetch(ne,{body:{fid:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},_i=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(ie,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(re,{body:{message:e,signature:t,fid:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}},vi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async create(e){let t=await this._privyInternal.session.getOrCreateGuestCredential(),n=await this._privyInternal.fetch(he,{body:{guest_credential:t}});await this._privyInternal.session.updateWithTokensResponse(n);let r=await J(this._embedded,n,e?.embedded);return this._privyInternal.callbacks?.setUser?.(r.user),r}};const Y=`privy:state_code`,X=`privy:code_verifier`;async function yi(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function bi(e){return crypto.getRandomValues(new Uint8Array(e))}function xi(){return e.base64urlnopad.fromBytes(bi(36))}function Si(){return xi()}async function Ci({codeVerifier:t,method:n=`S256`,digest:r}){if(n==`S256`){let n=await yi(t,r);return e.base64urlnopad.fromBytes(n)}else return t}var wi=class{_privyInternal;_storage;_crypto;_embedded;constructor(e,t,n,r){this._privyInternal=e,this._embedded=t,this._storage=n,this._crypto=r}async generateURL(e,t){let n=xi(),r=Si(),i=await Ci({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put(X,n),this._storage.put(Y,r)]),this._privyInternal.fetchForLogin(Ce,{body:{redirect_to:t,provider:e,code_challenge:i,state_code:r}})}async loginWithCode(e,t,n,r,i,a){let[o,s]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(s!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:s??``,returnedStateCode:t??``}),new E({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let c=await this._privyInternal.fetchForLogin(Se,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let l=await J(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del(X),this._storage.del(Y)]),this._privyInternal.callbacks?.setUser?.(l.user),l}async linkWithCode(e,t,n,r){let[i,a]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(a!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:a??``,returnedStateCode:t??``}),new E({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let o=await this._privyInternal.fetch(we,{body:{authorization_code:e,code_type:r,state_code:a,code_verifier:i}});await this._privyInternal.session.processOAuthTokens(o.oauth_tokens);let s=await this._privyInternal.refreshSession();return await Promise.all([this._storage.del(X),this._storage.del(Y)]),{user:s.user,identity_token:s.identity_token,oauth_tokens:o.oauth_tokens}}async unlink(e,t){await this._privyInternal.fetch(Te,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},Ti=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(ke,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(De,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(je,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Ee,{body:{relying_party:n,challenge:t,authenticator_response:this._transformAuthenticationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async signupWithPasskey(e,t,n){let r=await this._privyInternal.fetchForLogin(Ae,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await J(this._embedded,r,n?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithPasskey(e,t){await this._privyInternal.fetch(Oe,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}_transformRegistrationResponseToSnakeCase(e){return{type:e.type,id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData||void 0,transports:e.response.transports||void 0,public_key:e.response.publicKey||void 0,public_key_algorithm:e.response.publicKeyAlgorithm||void 0},authenticator_attachment:e.authenticatorAttachment||void 0,client_extension_results:{app_id:e.clientExtensionResults.appid||void 0,cred_props:e.clientExtensionResults.credProps||void 0,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret||void 0}}}_transformAuthenticationResponseToSnakeCase(e){return{type:e.type,id:e.id,raw_id:e.rawId,response:{signature:e.response.signature,client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,user_handle:e.response.userHandle||void 0},authenticator_attachment:e.authenticatorAttachment||void 0,client_extension_results:{app_id:e.clientExtensionResults.appid||void 0,cred_props:e.clientExtensionResults.credProps||void 0,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret||void 0}}}},Ei=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Ie,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Fe,{body:{phoneNumber:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Le,{body:{phoneNumber:e,code:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}async updatePhone({oldPhoneNumber:e,newPhoneNumber:t,code:n}){await this._privyInternal.fetch(ze,{body:{old_phone_number:e,new_phone_number:t,code:n}});let r=await this._privyInternal.refreshSession();return{user:r.user,identity_token:r.identity_token}}async unlink(e){await this._privyInternal.fetch(Re,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Di=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(tt,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}async linkWithSiwe(e,t,n){let r=t||this._wallet,i=n||this._preparedMessage;if(!r)throw Error(`A wallet must be provided in the init step or as an argument to linkWithSiwe`);if(!i)throw Error(`A message must be generated and signed before being used to link a wallet to privy`);await this._privyInternal.fetch($e,{body:{message:i,signature:e,chainId:r.chainId,walletClientType:r.walletClientType??null,connectorType:r.connectorType??null}});let a=await this._privyInternal.refreshSession();return{user:a.user,identity_token:a.identity_token}}async loginWithSiwe(e,t,n,r,i){let a=t||this._wallet,o=n||this._preparedMessage;if(!a)throw Error(`A wallet must be provided in the init step or as an argument to loginWithSiwe`);if(!o)throw Error(`A message must be generated and signed before being used to login to privy with a wallet`);let s=await this._privyInternal.fetchForLogin(Ze,{body:{signature:e,message:o,chainId:a.chainId,walletClientType:a.walletClientType??null,connectorType:a.connectorType??null,mode:r}});await this._privyInternal.session.updateWithTokensResponse(s);let c=await J(this._embedded,s,i?.embedded);return this._privyInternal.callbacks?.setUser?.(c.user),c}async init(e,t,n){this._wallet=e;let{nonce:r}=await this._privyInternal.fetch(Qe,{body:{address:e.address}}),i=Oi({chainId:e.chainId.toString().replace(`eip155:`,``),address:e.address,issuedAt:new Date().toISOString(),statement:`By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.`,domain:t,nonce:r,uri:n});return this._preparedMessage=i,{nonce:r,message:i}}};function Oi(e){return`${e.domain} wants you to sign in with your Ethereum account:
2
2
  ${e.address}
3
3
 
4
4
  ${e.statement}
@@ -9,7 +9,7 @@ Chain ID: ${e.chainId}
9
9
  Nonce: ${e.nonce}
10
10
  Issued At: ${e.issuedAt}
11
11
  Resources:
12
- - https://privy.io`}var Di=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlink({address:e}){await this._privyInternal.fetch(at,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}async link({message:e,signature:t,walletClientType:n,connectorType:r}){await this._privyInternal.fetch(it,{body:{message:e,signature:t,walletClientType:n??null,connectorType:r??null}});let i=await this._privyInternal.refreshSession();return{user:i.user,identity_token:i.identity_token}}async login({mode:e,message:t,signature:n,walletClientType:r,connectorType:i,opts:a}){let o=await this._privyInternal.fetchForLogin(nt,{body:{signature:n,message:t,walletClientType:r??null,connectorType:i??null,mode:e}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await J(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async fetchNonce({address:e}){let{nonce:t}=await this._privyInternal.fetch(rt,{body:{address:e}});return{nonce:t}}},Oi=class{_privyInternal;constructor(e){this._privyInternal=e}async link(e,t,n,r){await this._privyInternal.fetch(et,{body:{message:e,signature:t,smart_wallet_type:n,smart_wallet_version:r}});let i=await this._privyInternal.refreshSession();return{user:i.user,identity_token:i.identity_token}}async init(e){let{nonce:t}=await this._privyInternal.fetch(Qe,{body:{address:e.address}});return{nonce:t,message:ki({chainId:e.chainId.toString().replace(`eip155:`,``),address:e.address,issuedAt:new Date().toISOString(),statement:`By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.`,domain:`privy.io`,uri:`https://auth.privy.io`,nonce:t})}}};function ki(e){return`${e.domain} wants you to sign in with your Ethereum account:
12
+ - https://privy.io`}var ki=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlink({address:e}){await this._privyInternal.fetch(at,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}async link({message:e,signature:t,walletClientType:n,connectorType:r}){await this._privyInternal.fetch(it,{body:{message:e,signature:t,walletClientType:n??null,connectorType:r??null}});let i=await this._privyInternal.refreshSession();return{user:i.user,identity_token:i.identity_token}}async login({mode:e,message:t,signature:n,walletClientType:r,connectorType:i,opts:a}){let o=await this._privyInternal.fetchForLogin(nt,{body:{signature:n,message:t,walletClientType:r??null,connectorType:i??null,mode:e}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await J(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async fetchNonce({address:e}){let{nonce:t}=await this._privyInternal.fetch(rt,{body:{address:e}});return{nonce:t}}},Ai=class{_privyInternal;constructor(e){this._privyInternal=e}async link(e,t,n,r){await this._privyInternal.fetch(et,{body:{message:e,signature:t,smart_wallet_type:n,smart_wallet_version:r}});let i=await this._privyInternal.refreshSession();return{user:i.user,identity_token:i.identity_token}}async init(e){let{nonce:t}=await this._privyInternal.fetch(Qe,{body:{address:e.address}});return{nonce:t,message:ji({chainId:e.chainId.toString().replace(`eip155:`,``),address:e.address,issuedAt:new Date().toISOString(),statement:`By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.`,domain:`privy.io`,uri:`https://auth.privy.io`,nonce:t})}}};function ji(e){return`${e.domain} wants you to sign in with your Ethereum account:
13
13
  ${e.address}
14
14
 
15
15
  ${e.statement}
@@ -20,7 +20,7 @@ Chain ID: ${e.chainId}
20
20
  Nonce: ${e.nonce}
21
21
  Issued At: ${e.issuedAt}
22
22
  Resources:
23
- - https://privy.io`}var Ai=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async authenticate({telegramWebAppData:e,telegramAuthResult:t,captchaToken:n,mode:r=`login-or-sign-up`},i){let a=await this._privyInternal.fetchForLogin(ot,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n,mode:r}});await this._privyInternal.session.updateWithTokensResponse(a);let o=await J(this._embedded,a,i?.embedded);return this._privyInternal.callbacks?.setUser?.(o.user),o}async link({telegramWebAppData:e,telegramAuthResult:t,captchaToken:n}){await this._privyInternal.fetch(st,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n}});let r=await this._privyInternal.refreshSession();return{user:r.user,identity_token:r.identity_token}}async unlink({telegramUserId:e}){await this._privyInternal.fetch(ct,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},ji=class{_privyInternal;_embedded;_mfa;customProvider;phone;email;oauth;siwe;siws;smartWallet;passkey;farcaster;farcasterV2;guest;telegram;constructor(e,t,n,r,i){this._privyInternal=e,this._embedded=t,this._mfa=i,this.customProvider=new fi(this._privyInternal,t),this.phone=new wi(this._privyInternal,t),this.email=new pi(this._privyInternal,t),this.oauth=new Si(this._privyInternal,t,n,r),this.guest=new gi(this._privyInternal,t),this.siwe=new Ti(this._privyInternal,t),this.siws=new Di(this._privyInternal,t),this.smartWallet=new Oi(this._privyInternal),this.passkey=new Ci(this._privyInternal,t),this.farcaster=new mi(this._privyInternal,t),this.farcasterV2=new hi(this._privyInternal,t),this.telegram=new Ai(this._privyInternal,t)}async logout(e){try{this._embedded.reload()}catch{this._privyInternal.logger.warn(`Error reloading embedded wallet`)}let t=await this._prepareSessionRevocation();await Promise.all([this._privyInternal.session.destroyLocalState({reason:`logout`}),this._privyInternal.destroyClientAnalyticsId(),e?.userId&&this._mfa.clearMfa({userId:e.userId}).catch(e=>{this._privyInternal.logger.warn(`Error clearing MFA state`,e)})]),this._privyInternal.callbacks?.setUser?.(null),t&&this._privyInternal.fetch(ve,{body:{refresh_token:t.refresh_token},onRequest:()=>t.init}).catch(()=>{console.warn(`Error destroying session`)})}async _prepareSessionRevocation(){try{let e=await this._privyInternal.beforeRequestWithoutRefresh(new Request(this._privyInternal.baseUrl));return{refresh_token:await this._privyInternal.session.getRefreshToken()??void 0,init:e}}catch{console.warn(`Error preparing session revocation`);return}}},Mi=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(a,{body:e})}async getStatus(e){return await this._privyInternal.fetch(o,{query:{partnerUserId:e}})}};const Ni={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},Pi=new Set([y.id,g.id,v.id,S.id,_.id,Dt.id,b.id]),Fi=new Set([y.id,g.id,x.id,v.id,S.id,_.id]);function Ii(e,t){switch(t){case`native-currency`:return Pi.has(e);case`USDC`:return Fi.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function Li(e,t){switch(e){case g.id:return t===`native-currency`?`ETH_ARBITRUM`:`USDC_ARBITRUM`;case _.id:return t===`native-currency`?`AVAX_CCHAIN`:`USDC_CCHAIN`;case v.id:return t===`native-currency`?`ETH_BASE`:`USDC_BASE`;case Dt.id:return`CELO_CELO`;case S.id:return t===`native-currency`?`MATIC_POLYGON`:`USDC_POLYGON`;case b.id:return`MON_MON`;case y.id:return t===`native-currency`?`ETH_ETHEREUM`:`USDC_ETHEREUM`;default:return console.warn(`Chain ${e} not supported by Moonpay, defaulting to Ethereum mainnet`),`ETH_ETHEREUM`}}function Ri(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var zi=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(xe,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=Ni[t?`sandbox`:`prod`],i=await sn(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new wn({error:`Failed to fetch transaction status for Transaction ${e}`,code:`failed_to_fetch_moonpay_transaction_status`,response:i});let a=await i.json();return Array.isArray(a)?a.at(0):void 0}},Bi=class{moonpay;coinbase;constructor(e){this.moonpay=new zi(e),this.coinbase=new Mi(e)}},Vi=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(ye,{body:e})}},Hi=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(be,{body:e})}},Ui=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new Hi(e),this.passkey=new Vi(e)}setProxy(e){this.proxy=e}async getAccessTokenInternal(){let e=await this.privyInternal.getAccessTokenInternal();if(!e)throw new E({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return e}async verifyMfa(){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.verifyMfa({accessToken:await this.getAccessTokenInternal()})}async initEnrollMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.initEnrollMfa({...e,accessToken:await this.getAccessTokenInternal()})}async submitEnrollMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});let t=await this.proxy.submitEnrollMfa({...e,accessToken:await this.getAccessTokenInternal()}),n=await this.privyInternal.refreshSession();if(n.user.mfa_methods.length===0)try{await this.proxy.clearMfa({userId:n.user.id})}catch{}return t}async unenrollMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});let t=await this.proxy.unenrollMfa({method:e,accessToken:await this.getAccessTokenInternal()}),n=await this.privyInternal.refreshSession();if(n.user.mfa_methods.length===0)try{await this.proxy.clearMfa({userId:n.user.id})}catch{}return t}async unlinkPasskey({credentialId:e,removeAsMfa:t}){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});await this.proxy.unlinkPasskey({credentialId:e,removeAsMfa:t,accessToken:await this.getAccessTokenInternal()});let n=await this.privyInternal.refreshSession();if(n.user.mfa_methods.length===0)try{await this.proxy.clearMfa({userId:n.user.id})}catch{}}async clearMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.clearMfa(e)}},Wi=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(Ke,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(He,{body:{client_type:e}})}},Gi=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=yi(),n=bi(),r=await xi({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put(X,t),this._storage.put(Y,n)]),this._privyInternal.fetch(Ge,{body:{redirect_to:e,code_challenge:r,state_code:n}})}async authorize(e,t){let[n,r]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(r!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`recovery_oauth`,storedStateCode:r??``,returnedStateCode:t??``}),new E({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let i=await this._privyInternal.fetch(We,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del(X),this._storage.del(Y)]),i}},Ki=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new Gi(this._privyInternal,t,n),this.icloudAuth=new Wi(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(Ue,{body:{chain_type:t},params:{address:e}})}},qi=class{plugins;auth;user;embeddedWallet;recovery;mfa;app;mfaPromises;funding;delegated;crossApp;isMultiUserModeEnabled;_privyInternal;constructor({clientId:e,sessions:t,plugins:n=[],...r}){let i=gn(r.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this.plugins=[...n],this._privyInternal=new ni({...r,appClientId:e,crypto:i,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new Ui(this._privyInternal),this.mfaPromises=new Rr,this.app=new Cn(this._privyInternal),this.embeddedWallet=new Lr(this._privyInternal,r.embeddedWalletMessagePoster,r.supportedChains,this.mfa,this.mfaPromises,this.app,xn(this.plugins)),this.user=new ri(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new ji(this._privyInternal,this.embeddedWallet,r.storage,i,this.mfa),this.recovery=new Ki(this._privyInternal,r.storage,i),this.funding=new Bi(this._privyInternal),this.delegated=new kn(this._privyInternal),this.crossApp=new On(this._privyInternal,r.storage)}async initialize(){await this._privyInternal._initialize()}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}addOAuthTokensListener(e){return this._privyInternal.session.on(`oauth_tokens_granted`,e),{unsubscribe:()=>{this._privyInternal.session.removeListener(`oauth_tokens_granted`,e)}}}setCallbacks(e){this._privyInternal.setCallbacks(e)}getAccessToken(){return this._privyInternal.getAccessToken()}getIdentityToken(){return this._privyInternal.getIdentityToken()}track({name:e,properties:t}){this._privyInternal.createAnalyticsEvent(e,t)}getCompiledPath(e,t){return this._privyInternal.getPath(e,t)}async fetchPrivyRoute(e,t){return this._privyInternal.fetch(e,t)}async fetchPrivyRouteRaw(e,t){return this._privyInternal.fetchRaw(e,t)}get logger(){return this._privyInternal.logger}},Ji=class{async get(e){let t=localStorage.getItem(e);return t===null?void 0:JSON.parse(t)}put(e,t){t===void 0?this.del(e):localStorage.setItem(e,JSON.stringify(t))}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}},Yi=class{_cache={};get(e){return this._cache[e]}put(e,t){t===void 0?this.del(e):this._cache[e]=t}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}};const Xi=e=>e?e.linked_accounts.filter(ii).filter(Zi).sort((e,t)=>e.wallet_index-t.wallet_index):[],Zi=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,Qi=(e,t)=>{if(!e)return null;if(t?.imported||t&&O(t))return $i(t);let n=q(e)??ci(e);return n?$i(n):null},$i=e=>{if(e.chain_type===`ethereum`)return{entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`};if(e.chain_type===`solana`)return{entropyId:e.address,entropyIdVerifier:`solana-address-verifier`};throw Error(`Invalid embedded wallet account type`)},ea=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,ta=(e,t)=>pn(String(e),t),na=e=>mn(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),ra=(e,t)=>`+${dn(t)} ${e}`,ia=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,aa=e=>new ln(e),oa=un().map(e=>({code:e,callCode:dn(e)})),sa=e=>{let t=fn(e,cn)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},ca=e=>{let t=new ln;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},la=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),ua={[y.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[jt.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[x.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[kt.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[S.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[At.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[v.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[Et.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[_.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[Tt.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[g.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[wt.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},da={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function fa(e,t){return e===ua[t.id]}async function pa(e,t){let n=`${e}-auto-${t===`ethereum`?`eth`:`sol`}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest(`SHA-256`,r);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const ma=new Set([y.id,v.id,x.id,S.id,g.id,_.id,b.id]),ha=new Set([y.id,v.id,S.id,x.id,g.id,_.id,b.id]),ga={buy:`CARD`,send:`CRYPTO_ACCOUNT`},_a={USDC:`2b92315d-eab7-5bef-84fa-089a131333f5`,ETH:`d85dce9b-5b73-5c3c-8978-522ce1d1c1b4`,BTC:`5b71fc48-3dd3-540c-809b-f8c94d0e68b5`,SOL:`4f039497-3af8-5bb3-951c-6df9afa9be1c`,POL:`026bcc1e-9163-591c-a709-34dd18b2e7a1`,MON:`92aa538f-b005-45cc-a237-71d6466f54d9`},va={[y.id]:`ethereum`,[v.id]:`base`,[x.id]:`optimism`,[S.id]:`polygon`,[g.id]:`arbitrum`,[_.id]:`avacchain`,[b.id]:`monad`};function ya(e){return e.startsWith(`.`)?`0${e}`:e}function ba({appId:e,input:t,amount:n,blockchain:r,asset:i,experience:a}){let o=new URL(`https://pay.coinbase.com/buy/select-asset`);return o.searchParams.set(`appId`,t.app_id),o.searchParams.set(`sessionToken`,t.session_token),o.searchParams.set(`endPartnerName`,`privy:${e}`),o.searchParams.set(`defaultExperience`,a),o.searchParams.set(`presetCryptoAmount`,ya(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,ga[a]),o.searchParams.set(`defaultAsset`,_a[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const xa=(e,t)=>{switch(t){case`native-currency`:return ma.has(e);case`USDC`:return ha.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function Sa(e){return va[e]}function Ca(e,t){return t===`USDC`?`USDC`:e===S.id?`POL`:e===b.id?`MON`:`ETH`}const wa=e=>e.provider.replace(/-sandbox$/,``),Ta={BINANCECONNECT:`BINANCE_CONNECT`,COINBASEPAY:`COINBASE`},Ea=e=>{let t=(e.sub_provider?.trim()||wa(e)).toUpperCase();return Ta[t]??t};var Da=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=gn(t)}async invokeRpc({method:e,params:t}){return await(await fetch(this.cluster.rpcUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({jsonrpc:`2.0`,id:this._crypto.randomUUID(),method:e,params:t})})).json()}async getBalance(e){try{let t=await this.invokeRpc({method:`getBalance`,params:[e]});return t.error?null:BigInt(t.result.value)}catch{return null}}async getTokenAccountsByOwner(e,t){try{let n=await this.invokeRpc({method:`getTokenAccountsByOwner`,params:[e,{mint:t},{encoding:`jsonParsed`}]});if(n.error)return null;let r=n.result.value.at(0)?.account?.data?.parsed?.info?.tokenAmount;return r?{amount:BigInt(r.amount),decimals:r.decimals}:null}catch{return null}}async getAccountInfo(e){try{let t=await this.invokeRpc({method:`getAccountInfo`,params:[e,{encoding:`jsonParsed`}]});if(t.error)return null;let n=t.result.value?.data?.parsed?.info;return n?{decimals:n.decimals}:null}catch{return null}}};const Oa=({address:e,nonce:t,domain:n,uri:r})=>`${n} wants you to sign in with your Solana account:
23
+ - https://privy.io`}var Mi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async authenticate({telegramWebAppData:e,telegramAuthResult:t,captchaToken:n,mode:r=`login-or-sign-up`},i){let a=await this._privyInternal.fetchForLogin(ot,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n,mode:r}});await this._privyInternal.session.updateWithTokensResponse(a);let o=await J(this._embedded,a,i?.embedded);return this._privyInternal.callbacks?.setUser?.(o.user),o}async link({telegramWebAppData:e,telegramAuthResult:t,captchaToken:n}){await this._privyInternal.fetch(st,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n}});let r=await this._privyInternal.refreshSession();return{user:r.user,identity_token:r.identity_token}}async unlink({telegramUserId:e}){await this._privyInternal.fetch(ct,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Ni=class{_privyInternal;_embedded;_mfa;customProvider;phone;email;oauth;siwe;siws;smartWallet;passkey;farcaster;farcasterV2;guest;telegram;constructor(e,t,n,r,i){this._privyInternal=e,this._embedded=t,this._mfa=i,this.customProvider=new mi(this._privyInternal,t),this.phone=new Ei(this._privyInternal,t),this.email=new hi(this._privyInternal,t),this.oauth=new wi(this._privyInternal,t,n,r),this.guest=new vi(this._privyInternal,t),this.siwe=new Di(this._privyInternal,t),this.siws=new ki(this._privyInternal,t),this.smartWallet=new Ai(this._privyInternal),this.passkey=new Ti(this._privyInternal,t),this.farcaster=new gi(this._privyInternal,t),this.farcasterV2=new _i(this._privyInternal,t),this.telegram=new Mi(this._privyInternal,t)}async logout(e){try{this._embedded.reload()}catch{this._privyInternal.logger.warn(`Error reloading embedded wallet`)}let t=await this._prepareSessionRevocation();await Promise.all([this._privyInternal.session.destroyLocalState({reason:`logout`}),this._privyInternal.destroyClientAnalyticsId(),e?.userId&&this._mfa.clearMfa({userId:e.userId}).catch(e=>{this._privyInternal.logger.warn(`Error clearing MFA state`,e)})]),this._privyInternal.callbacks?.setUser?.(null),t&&this._privyInternal.fetch(ve,{body:{refresh_token:t.refresh_token},onRequest:()=>t.init}).catch(()=>{console.warn(`Error destroying session`)})}async _prepareSessionRevocation(){try{let e=await this._privyInternal.beforeRequestWithoutRefresh(new Request(this._privyInternal.baseUrl));return{refresh_token:await this._privyInternal.session.getRefreshToken()??void 0,init:e}}catch{console.warn(`Error preparing session revocation`);return}}},Pi=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(a,{body:e})}async getStatus(e){return await this._privyInternal.fetch(o,{query:{partnerUserId:e}})}};const Fi={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},Ii=new Set([y.id,g.id,v.id,S.id,_.id,Ot.id,b.id]),Li=new Set([y.id,g.id,x.id,v.id,S.id,_.id]);function Ri(e,t){switch(t){case`native-currency`:return Ii.has(e);case`USDC`:return Li.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function zi(e,t){switch(e){case g.id:return t===`native-currency`?`ETH_ARBITRUM`:`USDC_ARBITRUM`;case _.id:return t===`native-currency`?`AVAX_CCHAIN`:`USDC_CCHAIN`;case v.id:return t===`native-currency`?`ETH_BASE`:`USDC_BASE`;case Ot.id:return`CELO_CELO`;case S.id:return t===`native-currency`?`MATIC_POLYGON`:`USDC_POLYGON`;case b.id:return`MON_MON`;case y.id:return t===`native-currency`?`ETH_ETHEREUM`:`USDC_ETHEREUM`;default:return console.warn(`Chain ${e} not supported by Moonpay, defaulting to Ethereum mainnet`),`ETH_ETHEREUM`}}function Bi(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var Vi=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(xe,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=Fi[t?`sandbox`:`prod`],i=await cn(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new Tn({error:`Failed to fetch transaction status for Transaction ${e}`,code:`failed_to_fetch_moonpay_transaction_status`,response:i});let a=await i.json();return Array.isArray(a)?a.at(0):void 0}},Hi=class{moonpay;coinbase;constructor(e){this.moonpay=new Vi(e),this.coinbase=new Pi(e)}},Ui=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(ye,{body:e})}},Wi=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(be,{body:e})}},Gi=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new Wi(e),this.passkey=new Ui(e)}setProxy(e){this.proxy=e}async getAccessTokenInternal(){let e=await this.privyInternal.getAccessTokenInternal();if(!e)throw new E({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return e}async verifyMfa(){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.verifyMfa({accessToken:await this.getAccessTokenInternal()})}async initEnrollMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.initEnrollMfa({...e,accessToken:await this.getAccessTokenInternal()})}async submitEnrollMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});let t=await this.proxy.submitEnrollMfa({...e,accessToken:await this.getAccessTokenInternal()}),n=await this.privyInternal.refreshSession();if(n.user.mfa_methods.length===0)try{await this.proxy.clearMfa({userId:n.user.id})}catch{}return t}async unenrollMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});let t=await this.proxy.unenrollMfa({method:e,accessToken:await this.getAccessTokenInternal()}),n=await this.privyInternal.refreshSession();if(n.user.mfa_methods.length===0)try{await this.proxy.clearMfa({userId:n.user.id})}catch{}return t}async unlinkPasskey({credentialId:e,removeAsMfa:t}){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});await this.proxy.unlinkPasskey({credentialId:e,removeAsMfa:t,accessToken:await this.getAccessTokenInternal()});let n=await this.privyInternal.refreshSession();if(n.user.mfa_methods.length===0)try{await this.proxy.clearMfa({userId:n.user.id})}catch{}}async clearMfa(e){if(!this.proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.clearMfa(e)}},Ki=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(Ke,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(He,{body:{client_type:e}})}},qi=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=xi(),n=Si(),r=await Ci({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put(X,t),this._storage.put(Y,n)]),this._privyInternal.fetch(Ge,{body:{redirect_to:e,code_challenge:r,state_code:n}})}async authorize(e,t){let[n,r]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(r!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`recovery_oauth`,storedStateCode:r??``,returnedStateCode:t??``}),new E({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let i=await this._privyInternal.fetch(We,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del(X),this._storage.del(Y)]),i}},Ji=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new qi(this._privyInternal,t,n),this.icloudAuth=new Ki(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(Ue,{body:{chain_type:t},params:{address:e}})}},Yi=class{plugins;auth;user;embeddedWallet;recovery;mfa;app;mfaPromises;funding;delegated;crossApp;isMultiUserModeEnabled;_privyInternal;constructor({clientId:e,sessions:t,plugins:n=[],...r}){let i=_n(r.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this.plugins=[...n],this._privyInternal=new ai({...r,appClientId:e,crypto:i,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new Gi(this._privyInternal),this.mfaPromises=new Vr,this.app=new wn(this._privyInternal),this.embeddedWallet=new Br(this._privyInternal,r.embeddedWalletMessagePoster,r.supportedChains,this.mfa,this.mfaPromises,this.app,Sn(this.plugins)),this.user=new oi(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new Ni(this._privyInternal,this.embeddedWallet,r.storage,i,this.mfa),this.recovery=new Ji(this._privyInternal,r.storage,i),this.funding=new Hi(this._privyInternal),this.delegated=new An(this._privyInternal),this.crossApp=new kn(this._privyInternal,r.storage)}async initialize(){await this._privyInternal._initialize()}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}addOAuthTokensListener(e){return this._privyInternal.session.on(`oauth_tokens_granted`,e),{unsubscribe:()=>{this._privyInternal.session.removeListener(`oauth_tokens_granted`,e)}}}setCallbacks(e){this._privyInternal.setCallbacks(e)}getAccessToken(){return this._privyInternal.getAccessToken()}getIdentityToken(){return this._privyInternal.getIdentityToken()}track({name:e,properties:t}){this._privyInternal.createAnalyticsEvent(e,t)}getCompiledPath(e,t){return this._privyInternal.getPath(e,t)}async fetchPrivyRoute(e,t){return this._privyInternal.fetch(e,t)}async fetchPrivyRouteRaw(e,t){return this._privyInternal.fetchRaw(e,t)}get logger(){return this._privyInternal.logger}},Xi=class{async get(e){let t=localStorage.getItem(e);return t===null?void 0:JSON.parse(t)}put(e,t){t===void 0?this.del(e):localStorage.setItem(e,JSON.stringify(t))}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}},Zi=class{_cache={};get(e){return this._cache[e]}put(e,t){t===void 0?this.del(e):this._cache[e]=t}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}};const Qi=e=>e?e.linked_accounts.filter(R).filter($i).sort((e,t)=>e.wallet_index-t.wallet_index):[],$i=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,ea=(e,t)=>{if(!e)return null;if(t?.imported||t&&O(t))return ta(t);let n=q(e)??ui(e);return n?ta(n):null},ta=e=>{if(e.chain_type===`ethereum`)return{entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`};if(e.chain_type===`solana`)return{entropyId:e.address,entropyIdVerifier:`solana-address-verifier`};throw Error(`Invalid embedded wallet account type`)},na=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,ra=(e,t)=>mn(String(e),t),ia=e=>hn(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),aa=(e,t)=>`+${fn(t)} ${e}`,oa=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,sa=e=>new un(e),ca=dn().map(e=>({code:e,callCode:fn(e)})),la=e=>{let t=pn(e,ln)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},ua=e=>{let t=new un;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},da=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),fa={[y.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[Mt.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[x.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[At.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[S.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[jt.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[v.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[Dt.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[_.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[Et.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[g.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[Tt.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},pa={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function ma(e,t){return e===fa[t.id]}async function ha(e,t){let n=`${e}-auto-${t===`ethereum`?`eth`:`sol`}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest(`SHA-256`,r);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const ga=new Set([y.id,v.id,x.id,S.id,g.id,_.id,b.id]),_a=new Set([y.id,v.id,S.id,x.id,g.id,_.id,b.id]),va={buy:`CARD`,send:`CRYPTO_ACCOUNT`},ya={USDC:`2b92315d-eab7-5bef-84fa-089a131333f5`,ETH:`d85dce9b-5b73-5c3c-8978-522ce1d1c1b4`,BTC:`5b71fc48-3dd3-540c-809b-f8c94d0e68b5`,SOL:`4f039497-3af8-5bb3-951c-6df9afa9be1c`,POL:`026bcc1e-9163-591c-a709-34dd18b2e7a1`,MON:`92aa538f-b005-45cc-a237-71d6466f54d9`},ba={[y.id]:`ethereum`,[v.id]:`base`,[x.id]:`optimism`,[S.id]:`polygon`,[g.id]:`arbitrum`,[_.id]:`avacchain`,[b.id]:`monad`};function xa(e){return e.startsWith(`.`)?`0${e}`:e}function Sa({appId:e,input:t,amount:n,blockchain:r,asset:i,experience:a}){let o=new URL(`https://pay.coinbase.com/buy/select-asset`);return o.searchParams.set(`appId`,t.app_id),o.searchParams.set(`sessionToken`,t.session_token),o.searchParams.set(`endPartnerName`,`privy:${e}`),o.searchParams.set(`defaultExperience`,a),o.searchParams.set(`presetCryptoAmount`,xa(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,va[a]),o.searchParams.set(`defaultAsset`,ya[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const Ca=(e,t)=>{switch(t){case`native-currency`:return ga.has(e);case`USDC`:return _a.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function wa(e){return ba[e]}function Ta(e,t){return t===`USDC`?`USDC`:e===S.id?`POL`:e===b.id?`MON`:`ETH`}const Ea=e=>e.provider.replace(/-sandbox$/,``),Da={BINANCECONNECT:`BINANCE_CONNECT`,COINBASEPAY:`COINBASE`},Oa=e=>{let t=(e.sub_provider?.trim()||Ea(e)).toUpperCase();return Da[t]??t};var ka=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=_n(t)}async invokeRpc({method:e,params:t}){return await(await fetch(this.cluster.rpcUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({jsonrpc:`2.0`,id:this._crypto.randomUUID(),method:e,params:t})})).json()}async getBalance(e){try{let t=await this.invokeRpc({method:`getBalance`,params:[e]});return t.error?null:BigInt(t.result.value)}catch{return null}}async getTokenAccountsByOwner(e,t){try{let n=await this.invokeRpc({method:`getTokenAccountsByOwner`,params:[e,{mint:t},{encoding:`jsonParsed`}]});if(n.error)return null;let r=n.result.value.at(0)?.account?.data?.parsed?.info?.tokenAmount;return r?{amount:BigInt(r.amount),decimals:r.decimals}:null}catch{return null}}async getAccountInfo(e){try{let t=await this.invokeRpc({method:`getAccountInfo`,params:[e,{encoding:`jsonParsed`}]});if(t.error)return null;let n=t.result.value?.data?.parsed?.info;return n?{decimals:n.decimals}:null}catch{return null}}};const Aa=({address:e,nonce:t,domain:n,uri:r})=>`${n} wants you to sign in with your Solana account:
24
24
  ${e}
25
25
 
26
26
  ${`You are proving you own ${e}.`}
@@ -31,5 +31,5 @@ Chain ID: mainnet
31
31
  Nonce: ${t}
32
32
  Issued At: ${new Date().toISOString()}
33
33
  Resources:
34
- - https://privy.io`;function ka({name:e,rpcUrl:t}){if(t)return t;switch(e){case`mainnet-beta`:return`https://api.mainnet-beta.solana.com`;case`testnet`:return`https://api.testnet.solana.com`;case`devnet`:return`https://api.devnet.solana.com`}}function Aa({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function ja(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const Ma=`solana offchain`,Na=1232;function Pa(t){let n=e.utf8.toBytes(t),r=new Uint8Array(32);return r.set(n.slice(0,32)),r}function Fa({message:t,signerPublicKey:n,domain:r}){let i=e.utf8.toBytes(t);if(n.length!==32)throw Error(`Signer public key must be 32 bytes`);let a=85+i.length;if(a>Na)throw Error(`Combined message length (${a}) exceeds maximum (${Na})`);let o=Pa(r),s=new Uint8Array(a),c=0;s[c]=255,c+=1;let l=e.utf8.toBytes(Ma);return s.set(l,c),c+=l.length,s[c]=0,c+=1,s.set(o,c),c+=32,s[c]=1,c+=1,s[c]=1,c+=1,s.set(n,c),c+=32,s[c]=i.length&255,s[c+1]=i.length>>8&255,c+=2,s.set(i,c),s}function Ia(e){if(e.length<85)throw Error(`Message too short to contain a valid off-chain preamble`);let t=0;if(e[t]!==255)throw Error(`Invalid signing domain prefix`);if(t+=1,new TextDecoder().decode(e.slice(t,t+15))!==Ma)throw Error(`Invalid signing domain text`);t+=15;let n=e[t];t+=1;let r=e.slice(t,t+32);t+=32;let i=e[t];t+=1;let a=e[t];if(a!==1)throw Error(`Expected 1 signer, got ${a}`);t+=1;let o=e.slice(t,t+32);t+=32;let s=e[t]|e[t+1]<<8;if(t+=2,e.length<t+s)throw Error(`Message body is shorter than declared length`);return{version:n,applicationDomain:r,format:i,signerPublicKey:o,message:new TextDecoder().decode(e.slice(t,t+s))}}const La=[`privy`],Ra=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],za=[`coinbase_wallet`],Ba=`metamask.trust.safe.rainbow.uniswap.zerion.argent.spot.omni.cryptocom.blockchain.safepal.bitget_wallet.zengo.1inch.binance.exodus.mew_wallet.alphawallet.keyring_pro.mathwallet.unstoppable.obvious.ambire.internet_money_wallet.coin98.abc_wallet.arculus_wallet.haha.cling_wallet.broearn.copiosa.burrito_wallet.enjin_wallet.plasma_wallet.avacus.bee.pitaka.pltwallet.minerva.kryptogo.prema.slingshot.kriptonio.timeless.secux.bitizen.blocto.safemoon`.split(`.`),Va=[`unknown`],Ha=[...Ra,...za,...Ba,...La,...Va],Ua=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Wa(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function Ga({wei:e,precision:t=3}){return parseFloat(Ht(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function Ka({amount:e,decimals:t}){return Ut(BigInt(e),t)}function qa({lamports:e}){return Ut(e,9)}const Ja=e=>[...ai(e),...si(e)],Ya=(e,t)=>e.imported?e:q(t)??ci(t),Xa=e=>async({address:t,chainType:n})=>{let{user:r}=await e.user.get();if(!r)throw new E({code:`delegated_actions_before_logged_in`,error:`Must be logged in to delegate wallets`});if(n!==`solana`&&n!==`ethereum`)throw new E({code:`unsupported_chain_type`,error:`Only Solana and Ethereum embedded wallets are supported for delegation and revocation.`});let i=Ja(r).find(e=>e.chain_type===n&&e.address===t);if(!i)throw new E({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});if(O(i))throw new E({code:`unsupported_wallet_type`,error:`useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`});if(i.delegated)return{user:r};let a=Ya(i,r);if(!a)throw new E({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});await e.embeddedWallet.delegateWallets({rootWallet:{address:a.address,chainType:a.chain_type,imported:a.imported},delegatedWallets:[{address:i.address,chainType:i.chain_type,walletIndex:i.wallet_index}]});let{user:o}=await e.user.get();return{user:o}},Za=e=>async()=>{let{user:t}=await e.user.get();if(!t)throw new E({code:`delegated_actions_before_logged_in`,error:`Must be logged in to revoke delegated wallets`});let n=Ja(t);if(n.some(O))throw new E({code:`unsupported_wallet_type`,error:`revokeWallets is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to manage server side access on behalf of your users. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`});if(n.every(e=>!e.delegated))throw new E({code:`delegated_actions_no_wallet_to_revoke`,error:`User has no delegated wallets to revoke.`});await e.delegated.revoke();let{user:r}=await e.user.get();return{user:r}};var Qa=w({delegateWallet:()=>Xa,revokeWallets:()=>Za});const $a=({client:e,openAuthSession:t})=>async({providerAppId:n,redirectUrl:r,loginOptions:i})=>{let a=`privy:${n}`,{url:o}=await e.auth.oauth.generateURL(a,r),s=await t(o,r),c=s.privy_oauth_state,l=s.privy_oauth_code;if(!c||!l)throw new E({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let u=await e.auth.oauth.loginWithCode(l,c,a,void 0,void 0,i),d=u.oauth_tokens;return d&&await e.crossApp.updateOnCrossAppAuthentication(n,d),u},eo=({client:e,openAuthSession:t})=>async({providerAppId:n,redirectUrl:r})=>{let i=`privy:${n}`,{url:a}=await e.auth.oauth.generateURL(i,r),o=await t(a,r),s=o.privy_oauth_state,c=o.privy_oauth_code;if(!s||!c)throw new E({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let{user:l,oauth_tokens:u}=await e.auth.oauth.linkWithCode(c,s,i);return u&&await e.crossApp.updateOnCrossAppAuthentication(n,u),l};function to(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const no=(e,t)=>e.linked_accounts.filter(e=>e.type===`cross_app`).find(({embedded_wallets:e,smart_wallets:n})=>[...e,...n].some(e=>e.address===t)),ro=({client:e,openAuthSession:t})=>{let n=eo({client:e,openAuthSession:t});return async({providerAppId:t,redirectUrl:r})=>await e.crossApp.getProviderAccessToken(t)||(await n({providerAppId:t,redirectUrl:r}),await e.crossApp.getProviderAccessToken(t))},io=({client:e,openAuthSession:t})=>{let n=ro({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=no(r,o);if(!s)throw new E({code:`cross_app_invalid_wallet`,error:`Cannot operate with this wallet address`});let c=s.provider_app_id,{connections:l}=await e.crossApp.getCrossAppConnections(),u=l.find(e=>e.provider_app_id===c);if(!u)throw new E({code:`cross_app_invalid_app`,error:`Invalid connected app`});if(u.read_only)throw new E({code:`cross_app_read_only`,error:`Cannot transact against a read-only provider app`});let d=await n({providerAppId:c,redirectUrl:a});if(!d)throw new E({code:`cross_app_request_error`,error:`Wallet operations require a valid token`});let f={content:{request:{request:i}},timestamp:Date.now(),callbackUrl:a},p=new URL(`${u.provider_app_custom_api_url}/oauth/transact`);p.searchParams.set(`communicationMode`,`redirect`),p.searchParams.set(`token`,d),p.searchParams.set(`request`,JSON.stringify(f));let{privy_cross_app_type:m,privy_cross_app_payload:h}=await t(p.href,a);if(!m||!h)throw new E({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(m===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new E({code:`cross_app_request_error`,error:h});if(m!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new E({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:h}}};function ao(e){if(!e)throw new E({code:`attempted_cross_app_request_before_logged_in`,error:`Must be logged in to sign messages with a cross-app wallet`})}const oo=({client:e,openAuthSession:t})=>{let n=io({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{ao(e);let a={method:to(e,t)?`privy_signSmartWalletMessage`:`personal_sign`,params:[r,t]},{result:o}=await n({user:e,request:a,address:t,redirectUrl:i});return{signature:o}}};function so(e){let t={name:`string`,version:`string`,chainId:`uint256`,verifyingContract:`address`,salt:`bytes32`},n=e.types.EIP712Domain??Object.entries(e.domain??{}).map(([e,n])=>{if(n!=null&&typeof e==`string`&&e in t)return{name:e,type:t[e]}}).filter(e=>!!e),r={...e.types};return r.EIP712Domain=n,{...e,types:r}}const co=({client:e,openAuthSession:t})=>{let n=io({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{ao(e);let a={method:to(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,so(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},lo=({client:e,openAuthSession:t})=>{let n=io({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{ao(e);let a={method:to(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var uo=w({sendTransaction:()=>lo,signMessage:()=>oo,signTypedData:()=>co}),fo=w({linkWithCrossAppAuth:()=>eo,loginWithCrossAppAuth:()=>$a,wallet:()=>uo});function po(e){if(e.startsWith(`eip155:`))return`ethereum`;if(e.startsWith(`solana:`))return`solana`;if(e.startsWith(`bip122:`))return`bitcoin-segwit`;if(e.startsWith(`tron:`))return`tron`}function mo(e,t){let n=po(e);if(!n)return;let r=t.linked_accounts.find(e=>e.type===`wallet`&&e.chain_type===n&&`address`in e&&e.address);return r&&`address`in r?r.address:void 0}async function ho(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=mo(e.caip2,t);if(n)return{ok:!0,address:n};let r=po(e.caip2);if(!r)return{ok:!1,error:`UNSUPPORTED_CHAIN`};try{let t=await e.privy.fetchPrivyRoute(ft,{body:{chain_type:r}});return await e.privy.user.get(),await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function go(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await ho({privy:e.privy,caip2:e.sourceChain,onWalletCreated:e.onWalletCreated});if(!t.ok)throw Error(t.error);n=t.address}let r=await e.privy.fetchPrivyRoute(u,{body:{source_chain:e.sourceChain,source_currency:e.sourceCurrency,destination_chain:e.destinationChain,destination_currency:e.destinationCurrency,destination_address:e.destinationAddress,refund_address:n,...e.slippageBps==null?{}:{slippage_bps:e.slippageBps}}});return e.privy.track({name:`sdk_deposit_address_headless_quote`,properties:{sourceChain:e.sourceChain,sourceCurrency:e.sourceCurrency,destinationChain:e.destinationChain,destinationCurrency:e.destinationCurrency,depositAddressId:r.id}}),r}function _o(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const Z=async({operation:e,until:t,delay:n,interval:r,attempts:i,signal:a})=>{n&&await _o(n);let o=0,s,c;for(;o<i;){if(a?.aborted)return{status:`aborted`,result:s,attempts:o,error:c};o++;try{if(c=void 0,s=await e(),t(s))return{status:`success`,result:s,attempts:o};o<i&&await _o(r)}catch(e){e instanceof Error&&(c=e),o<i&&await _o(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},vo=2e3,yo=1800*1e3;function bo(e,t){return Math.ceil(t/e)}function xo(e){return e.status===`success`?e.result?{status:`success`,order:e.result}:{status:`timeout`}:e.status===`aborted`?{status:`aborted`,error:e.error}:{status:`timeout`,error:e.error}}async function So(e){return await e.privy.fetchPrivyRoute(de,{params:{order_id:e.orderId}})}async function Co(e){let t=e.pollIntervalMs??vo,n=e.timeoutMs??yo,r=e.signal??new AbortController().signal;return xo(await Z({operation:async()=>{let t=await e.privy.fetchPrivyRoute(pe,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(de,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:bo(t,n),signal:r}))}async function wo(e){let t=e.pollIntervalMs??vo,n=e.timeoutMs??yo,r=e.signal??new AbortController().signal;return xo(await Z({operation:()=>e.privy.fetchPrivyRoute(de,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:bo(t,n),signal:r}))}var To=w({generateDepositAddress:()=>go,getConfig:()=>Eo,getDeposit:()=>So,resolveRefundAddress:()=>ho,waitForCompletion:()=>wo,waitForDeposit:()=>Co});async function Eo(e){let t=await e.fetchPrivyRoute(fe,{});return{currencies:t.currencies,chains:t.chains}}function Do(e){let t=e.depositAddressStrategy===void 0?{}:{deposit_address_strategy:e.depositAddressStrategy};return e.type===`deposit_config`?{type:`deposit_config`,deposit_config_id:e.depositConfigId,...t}:{type:`inline_route`,source:e.source,destination:e.destination,...t}}async function Oo(e,t,n){let{walletId:r}=n,i=Do(n),a=e.getCompiledPath(c,{params:{wallet_id:r}}),o=String(Date.now()+I),{signature:s}=await P(t,{version:1,url:a,method:c.method,headers:{"privy-app-id":e.app.appId,[F]:o},body:i});if(Date.now()>Number(o))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});let l=await e.fetchPrivyRoute(c,{body:i,params:{wallet_id:r},headers:{"privy-authorization-signature":s,[F]:o}});return e.track({name:`sdk_deposit_address_headless_create`,properties:{version:`v3`,action:`create`,walletId:r,type:n.type,...n.type===`inline_route`?{destinationChain:n.destination.chain,destinationCurrency:n.destination.asset}:{depositConfigId:n.depositConfigId}}}),l}async function ko(e,t){let n=await e.fetchPrivyRoute(l,{body:{source:t.source,destination:t.destination,...t.inputAmount==null?{}:{input_amount:t.inputAmount},...t.slippageBps==null?{}:{slippage_bps:t.slippageBps}}});return e.track({name:`sdk_deposit_address_headless_quote`,properties:{version:`v3`,action:`quote`,sourceChain:t.source.chain,sourceCurrency:t.source.asset,destinationChain:t.destination.chain,destinationCurrency:t.destination.asset}}),n}function Ao(e){let t=Number(e.input_amount),n=Number(e.estimated_output_amount);if(!(!Number.isFinite(t)||!Number.isFinite(n)||t===0))return String(n/t)}async function jo(e,t){return e.fetchPrivyRoute(Xe,{query:{q:t}})}async function Mo(e,t){return e.fetchPrivyRoute(ue,{params:{wallet_id:t.walletId,order_id:t.orderId}})}async function No(e,t){return e.fetchPrivyRoute(le,{params:{wallet_id:t.walletId},query:{after:t.after}})}const Po={ethereum:`eip155:1`,arbitrum:`eip155:42161`,avalanche:`eip155:43114`,arc:`eip155:5042`,monad:`eip155:143`,base:`eip155:8453`,tempo:`eip155:4217`,linea:`eip155:59144`,optimism:`eip155:10`,polygon:`eip155:137`,bsc:`eip155:56`,zksync_era:`eip155:324`,solana:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,tron:`tron:mainnet`,robinhood:`eip155:4663`,unichain:`eip155:130`,worldchain:`eip155:480`,ink:`eip155:57073`,soneium:`eip155:1868`,megaeth:`eip155:4326`,hyperevm:`eip155:999`,hypercore:`eip155:1337`,"tempo_zone:00001":`eip155:421700001`,"tempo_zone:00002":`eip155:421700002`,tempo_testnet:`eip155:42431`,"tempo_testnet_zone:00003":`eip155:1424310003`,hoodi:`eip155:560048`,sepolia:`eip155:11155111`,arbitrum_sepolia:`eip155:421614`,avalanche_fuji:`eip155:43113`,base_sepolia:`eip155:84532`,linea_testnet:`eip155:59140`,optimism_sepolia:`eip155:11155420`,polygon_amoy:`eip155:80002`,bsc_testnet:`eip155:97`,solana_devnet:`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,solana_testnet:`solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`,tron_nile:`tron:nile`,robinhood_testnet:`eip155:46630`,ink_sepolia:`eip155:763373`},Fo=[{id:`eth`,symbol:`ETH`},{id:`sol`,symbol:`SOL`},{id:`pol`,symbol:`POL`},{id:`trx`,symbol:`TRX`},{id:`usdc`,symbol:`USDC`},{id:`usdc_e`,symbol:`USDC.e`},{id:`usdt`,symbol:`USDT`},{id:`usdt0`,symbol:`USDT0`},{id:`usdb`,symbol:`USDB`},{id:`eurc`,symbol:`EURC`},{id:`ousd`,symbol:`OUSD`},{id:`usdg`,symbol:`USDG`},{id:`pathusd`,symbol:`PathUSD`}],Io=new Set([`native`,`native-token`,`0x0000000000000000000000000000000000000000`,`11111111111111111111111111111111`]);function Lo(e){return Io.has(e.toLowerCase())}function Ro(e){return e.includes(`:`)}function zo(e){return Ro(e)?e:Po[e.toLowerCase()]||(/^\d+$/.test(e)?`eip155:${e}`:e)}function Bo(e){return Lo(e)}function Vo(e){let t=e.toLowerCase();return Fo.find(e=>e.id===t||e.symbol.toLowerCase()===t)}function Ho({symbol:e,address:t}){return Vo(e)?.id??t}function Uo({asset:e,symbol:t,addresses:n}){let r=e.toLowerCase();return t.toLowerCase()===r?!0:Bo(e)?n.some(Lo):n.some(e=>e.toLowerCase()===r)}function Wo({config:e,chain:t,asset:n}){let r=t?zo(t):void 0;for(let t of e.currencies){let e=r?t.chains.filter(e=>zo(e.caip2)===r):t.chains;if(e.length!==0&&Uo({asset:n,symbol:t.symbol,addresses:e.map(e=>e.address)}))return t.symbol}return n.toUpperCase()}function Go(e,t,n){return Ko(e,n)===Ko(t,n)}function Ko(e,t){if(/^eip155:\d+$/i.test(e))return e.toLowerCase();let n=zo(e);if(n!==e||e.includes(`:`))return n;let r=e.toLowerCase();for(let n of Object.values(t.chains))if(n.caip2===e||n.display_name.toLowerCase()===r||String(n.chain_id)===e)return n.caip2;return n}function qo(e,t){return t.asset===`*`||Uo({asset:t.asset,symbol:e.symbol,addresses:e.chains.map(e=>e.address)})}function Jo({caip2:e,asset:t,config:n}){return!t.chain||t.chain===`*`||Go(t.chain,e,n)}function Yo({currency:e,source:t,config:n}){switch(t.mode){case`all`:return e.chains;case`include`:{let r=t.values.filter(t=>qo(e,t));return r.length===0?[]:e.chains.filter(e=>r.some(t=>Jo({caip2:e.caip2,asset:t,config:n})))}case`exclude`:{let r=t.values.filter(t=>qo(e,t));return r.length===0?e.chains:e.chains.filter(e=>!r.some(t=>Jo({caip2:e.caip2,asset:t,config:n})))}default:return e.chains}}function Xo(e,t){return{currencies:e.currencies.map(n=>({...n,chains:Yo({currency:n,source:t,config:e})})).filter(e=>e.chains.length>0),chains:e.chains}}const Zo=/^T[1-9A-HJ-NP-Za-km-z]{33}$/,Qo=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function $o(e,t){switch(t){case`evm`:case`hypevm`:return Gt(e,{strict:!1});case`svm`:return Qo.test(e)&&!Zo.test(e);case`tron`:case`tvm`:return Zo.test(e);default:return!1}}function es({accounts:e,selectedChain:t}){return e.find(e=>$o(e.deposit_address,t.vmType))?.deposit_address}var ts=w({createCryptoDepositAccount:()=>Oo,filterDepositConfig:()=>Xo,findCatalogSymbol:()=>Wo,getCryptoDepositAccountNextOrder:()=>No,getCryptoDepositAccountOrder:()=>Mo,getCryptoDepositAccountQuote:()=>ko,indicativeRateFromQuote:()=>Ao,isNativeAssetAlias:()=>Bo,pickDepositAddressForChain:()=>es,quoteSourceAsset:()=>Ho,resolveChainAlias:()=>zo,searchCryptoDepositAccountConfig:()=>jo});async function ns(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(gt,{params:{wallet_id:n}}),a=String(Date.now()+I),{signature:o}=await P(t,{version:1,url:i,method:gt.method,headers:{"privy-app-id":e.app.appId,[F]:a},body:{...r}});if(Date.now()>Number(a))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(gt,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[F]:a}})}async function rs(e,{wallet_id:t}){return await e.fetchPrivyRoute(pt,{params:{wallet_id:t}})}async function is(e,{wallet_id:t},n,r){let i=e.getCompiledPath(yt,{params:{wallet_id:t}}),a=String(Date.now()+I),{signature:o}=await P(n,{version:1,url:i,method:yt.method,headers:{"privy-app-id":e.app.appId,[F]:a},body:r});if(Date.now()>Number(a))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(yt,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":o,[F]:a}})}async function as(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(vt,{params:{wallet_id:n}}),a=String(Date.now()+I),{signature:o}=await P(t,{version:1,url:i,method:vt.method,headers:{"privy-app-id":e.app.appId,[F]:a},body:{...r}});if(Date.now()>Number(a))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(vt,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[F]:a}})}async function os(e,{wallet_id:t,action_id:n}){return await e.fetchPrivyRoute(mt,{params:{wallet_id:t,action_id:n}})}async function ss(e,{wallet_id:t,...n}){return await e.fetchPrivyRoute(ht,{params:{wallet_id:t},query:{...n.cursor?{cursor:n.cursor}:{},...n.limit===void 0||n.limit===null?{}:{limit:n.limit},...n.type?{type:n.type}:{}}})}async function cs({client:e,wallet:t,signers:n}){if(t.chain_type!==`ethereum`&&t.chain_type!==`solana`)throw Error(`Session signers are only supported for Ethereum and Solana wallets`);if(O(t)){if(n.length===0)throw Error(`Must specify at least one signer to add.`);let r={wallet_id:t.id},i=await rs(e,r);await is(e,r,ds(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return us(e);if(n.length>0)throw Error(`Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`);let{user:r}=await e.user.get(),i=Ya(t,r);if(!i)throw Error(`Unable to determine root address for delegated address.`);await e.embeddedWallet.delegateWallets({rootWallet:{address:i.address,chainType:i.chain_type,imported:i.imported??!1},delegatedWallets:[{address:t.address,chainType:t.chain_type,walletIndex:t.wallet_index}]})}return us(e)}async function ls({client:e,wallet:t}){return O(t)?await is(e,{wallet_id:t.id},ds(e),{additional_signers:[]}):await e.delegated.revoke(),us(e)}async function us(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function ds(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var fs=class{#e;#t;get standardWallet(){return this.#e}get address(){return this.#t.address}constructor({wallet:e,account:t}){this.#e=e,this.#t=t}async disconnect(){if(!this.#e.features[`standard:disconnect`]?.disconnect)throw Error(`Wallet does not support disconnect`);await this.#e.features[`standard:disconnect`].disconnect()}async signMessage(...e){if(!this.#e.features[`solana:signMessage`]?.signMessage)throw Error(`Wallet does not support signMessage`);let t=await this.#e.features[`solana:signMessage`].signMessage(...e.map(e=>({...e,account:this.#t})));return e.length===1?t[0]:[...t]}async signTransaction(...e){if(!this.#e.features[`solana:signTransaction`]?.signTransaction)throw Error(`Wallet does not support signTransaction`);let t=await this.#e.features[`solana:signTransaction`].signTransaction(...e.map(e=>({...e,account:this.#t})));return e.length===1?t[0]:[...t]}async signAndSendTransaction(...e){if(!this.#e.features[`solana:signAndSendTransaction`]?.signAndSendTransaction)throw Error(`Wallet does not support signAndSendTransaction`);let t=await this.#e.features[`solana:signAndSendTransaction`].signAndSendTransaction(...e.map(e=>({...e,account:this.#t})));return e.length===1?t[0]:[...t]}async signAndSendAllTransactions(e){if(!this.#e.features[`solana:signAndSendTransaction`]?.signAndSendTransaction)throw Error(`Wallet does not support signAndSendTransaction`);return[...await this.#e.features[`solana:signAndSendTransaction`].signAndSendTransaction(...e.map(e=>({...e,account:this.#t})))]}};const ps=async(e,{environment:n,acceptElectronicDisclosure:r,acceptBankTerms:i})=>{let{data:a}=await e.fetchPrivyRoute(t,{body:{environment:n,accept_electronic_disclosure:r,accept_bank_terms:i}});return a},ms=async({sendTransaction:e,evmChainId:t,stablecoinAddress:n,spenderAddress:r})=>{let i={to:n,chainId:t,data:Bt({abi:Vt,functionName:`approve`,args:[r,qt]})};try{return await e(i,{sponsor:!0})}catch(t){return console.warn(`[privy] Sponsored card approval failed; retrying pre-funded.`,t instanceof Error?t.message:String(t)),e(i,{sponsor:!1})}},hs=({cardCreatedAt:e,environment:t,now:n=new Date})=>{let r=new Intl.DateTimeFormat(void 0,{month:`long`,year:`numeric`,timeZone:`UTC`}),i=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1),a=+(t===`production`),o=[];for(let e=0;e<24;e++){let t=Date.UTC(n.getUTCFullYear(),n.getUTCMonth()-a-e,1);if(t<i)break;let s=new Date(t),c=`${s.getUTCFullYear()}-${String(s.getUTCMonth()+1).padStart(2,`0`)}`;o.push({value:c,label:r.format(s)})}return o},gs=[{type:`function`,name:`publicCall`,stateMutability:`nonpayable`,inputs:[{name:`data`,type:`bytes`}],outputs:[]},{type:`function`,name:`publicGetCall`,stateMutability:`view`,inputs:[{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bytes`}]}],_s=async({sendTransaction:e,evmChainId:t,spenderAddress:n,vaultAddress:r})=>{let i={to:n,chainId:t,data:Bt({abi:gs,functionName:`publicCall`,args:[It([Jt(`TEUP`),r])]})};try{return await e(i,{sponsor:!0})}catch(t){return console.warn(`[privy] Sponsored card vault choice failed; retrying pre-funded.`,t instanceof Error?t.message:String(t)),e(i,{sponsor:!1})}},vs=async(e,{environment:t,walletId:n,chainId:r,asset:i})=>e.fetchPrivyRoute(s,{body:{environment:t,wallet_id:n,chain_id:r,asset:i}}),Q=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(ae,{query:{environment:t}});return n},ys=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(dt,{body:{environment:t}});return n},bs=async(e,{environment:t,limit:n,cursor:r})=>e.fetchPrivyRoute(_e,{query:{environment:t,...n===void 0?{}:{limit:n},...r?{cursor:r}:{}}}),xs=20,Ss=async({provider:e,evmChainId:t,owner:n,stablecoinAddress:r,spenderAddress:i})=>{await e.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${t.toString(16)}`}]});let a=await e.request({method:`eth_call`,params:[{to:r,data:Bt({abi:Vt,functionName:`allowance`,args:[n,i]})},`latest`]});if(!Kt(a)||a===`0x`)throw Error(`Could not read the spend approval`);return zt({abi:Vt,functionName:`allowance`,data:a})},Cs=async({provider:e,evmChainId:t,owner:n,spenderAddress:r})=>{await e.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${t.toString(16)}`}]});let i=await e.request({method:`eth_call`,params:[{to:r,data:Bt({abi:gs,functionName:`publicGetCall`,args:[It([Jt(`TEGP`),n])]})},`latest`]});if(!Kt(i)||i===`0x`)throw Error(`Could not read the card vault choice`);let[a]=Rt([{type:`address`}],zt({abi:gs,functionName:`publicGetCall`,data:i}));return a},ws=2e3,Ts=1e3,Es=new Map([[`morpho`,`Morpho`],[`aave`,`Aave`]]),Ds=e=>{switch(e.status){case`kyc_required`:return{kind:`kyc`,url:e.kyc_url};case`provider_terms_required`:return{kind:`provider`,url:e.tos_url};default:return null}},Os=e=>{try{return new URL(e).protocol===`https:`?e:null}catch{return null}},$=e=>e instanceof Error&&e.message?e.message:void 0,ks=({client:e,environment:t,walletId:n,chainId:r,asset:i,platform:a})=>{let o=null,s=e=>{o=e,a.setStep(e)},c=null,l=null,u=null,d=i=>{let o=u;if(!o)return a.resolveSpendApproval();if(!r.startsWith(`eip155:`))return{kind:`unsupported`};let{spenderAddress:s,shareTokenAddress:c}=o,d=a.resolveEvmWallet(),f=Number(r.slice(7)),p=async()=>Ss({provider:await d.getProvider(),evmChainId:f,owner:d.address,stablecoinAddress:c,spenderAddress:s}),m=async()=>Cs({provider:await d.getProvider(),evmChainId:f,owner:d.address,spenderAddress:s});return{kind:`supported`,isApproved:async()=>await p()>0n&&(o.kind!==`opt_in`||await m()!==Xt),approve:async()=>{if(await ms({sendTransaction:d.sendTransaction,evmChainId:f,stablecoinAddress:c,spenderAddress:s}),o.kind!==`opt_in`)return;let a=await Z({operation:p,until:e=>e>0n,delay:0,interval:Ts,attempts:60,signal:i});if(a.status===`aborted`)return;if(a.status===`max_attempts`)throw Error(`The share approval did not land in time`,{cause:a.error});let u=await m();if(i.aborted||u!==Xt)return;await _s({sendTransaction:d.sendTransaction,evmChainId:f,spenderAddress:s,vaultAddress:o.vaultAddress});let h=await Z({operation:m,until:e=>e.toLowerCase()===o.vaultAddress.toLowerCase(),delay:0,interval:Ts,attempts:60,signal:i});if(h.status===`max_attempts`)throw Error(`The vault choice did not land in time`,{cause:h.error});h.status===`success`&&l&&e.track({name:`sdk_card_sign_up_tempo_earn_opt_in`,properties:{cardId:l,walletId:n,chainId:r,environment:t,vaultAddress:o.vaultAddress}})}}},f=async(e,t)=>{if(t.aborted)return;l=e;let n={status:`approve-prompt`,vaultProvider:u?.providerName??null},r;try{r=d(t)}catch{s(n);return}if(r.kind===`unsupported`){s(r.reason?{status:`error`,message:r.reason,cardId:e}:{status:`error`,cardId:e});return}try{let i=await r.isApproved();if(t.aborted)return;s(i?{status:`ready`,cardId:e}:n)}catch{t.aborted||s(n)}},p=async a=>{if(!a.aborted)try{let o=await bs(e,{environment:t,limit:20});if(a.aborted)return;let c=o.data.find(e=>e.wallet_id===n&&e.chain_id===r&&e.asset===i&&e.status!==`replaced`);if(c||=(s({status:`creating-card`}),await vs(e,{environment:t,walletId:n,chainId:r,asset:i})),a.aborted)return;let l=c.funding_sources,d=l?.find(e=>e.selected),p;if(d?.type===`erc4626_vault`?p=Es.get(d.provider):d?.type===`tempo_earn_vault`&&(p=`Tempo`),l&&!d||d&&d.type!==`wallet`&&!p){console.warn(`[privy] Card funding source is not supported by this SDK version`,{type:d?.type,provider:d?.type===`erc4626_vault`?d.provider:void 0}),s({status:`error`,cardId:c.id});return}if(u=null,d&&d.type!==`wallet`&&p)u={kind:`selected`,spenderAddress:d.spender_address,shareTokenAddress:d.share_token_address,providerName:p};else{let e=c.funding_sources?.find(e=>e.type===`tempo_earn_vault`);e&&(u={kind:`opt_in`,spenderAddress:e.spender_address,shareTokenAddress:e.share_token_address,providerName:`Tempo`,vaultAddress:e.vault_address})}await f(c.id,a)}catch(e){if(a.aborted)return;s({status:`error`,message:$(e)})}},m=async n=>{let r=0;for(;!n.aborted;){if(++r>10){s({status:`error`});return}let i;try{i=await Q(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}if(n.aborted)return;switch(i.status){case`not_created`:try{await ys(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}continue;case`electronic_disclosure_required`:s({status:`disclosure-prompt`,disclosureUrl:i.disclosure_url});return;case`bank_terms_required`:s({status:`bank-terms-prompt`,bankInfo:i.bank_info});return;case`provider_terms_required`:c={kind:`provider`,url:i.tos_url},s({status:`provider-terms-prompt`});return;case`kyc_required`:c={kind:`kyc`,url:i.kyc_url},s({status:`kyc-prompt`});return;case`pending`:if(s({status:`pending`}),(await Z({operation:()=>Q(e,{environment:t}),until:e=>e.status!==`pending`,delay:0,interval:ws,attempts:60,signal:n})).status!==`success`)return;continue;case`under_review`:s({status:`under-review`});return;case`ready`:await p(n);return;case`rejected`:s({status:`rejected`,reason:i.rejection_reasons?.[0]?.reason});return;case`error`:s({status:`error`});return;default:return}}},h=async({page:n,url:r,until:i,signal:o})=>{let s=Os(r);if(!s)return n?.dismiss(),`blocked`;let c=n??a.openHostedPage(s);if(!c)return`blocked`;n&&n.navigate(s);let l=await Z({operation:()=>Q(e,{environment:t}),until:e=>i(e)||c.isClosed(),delay:0,interval:ws,attempts:60,signal:o});if(l.status===`aborted`)return c.dismiss(),`aborted`;if(l.status===`max_attempts`)return`stalled`;if(i(l.result))return c.dismiss(),`advanced`;let u=await Z({operation:()=>Q(e,{environment:t}),until:i,delay:0,interval:1e3,attempts:5,signal:o});return u.status===`aborted`?(c.dismiss(),`aborted`):u.status===`success`?`advanced`:`closed`},ee=async(n,r)=>{c=null,s({status:n===`provider`?`provider-terms-prompt`:`kyc-prompt`,pending:!0});try{let n=await Q(e,{environment:t});if(r.aborted)return;let i=Ds(n);if(i){c=i,s({status:i.kind===`provider`?`provider-terms-prompt`:`kyc-prompt`});return}}catch(e){r.aborted||s({status:`error`,message:$(e)});return}await m(r)},te=async n=>{s({status:`loading`});let r;try{r=await Q(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}if(!n.aborted)switch(r.status){case`not_created`:case`electronic_disclosure_required`:case`bank_terms_required`:case`provider_terms_required`:case`kyc_required`:case`pending`:case`ready`:s({status:`get-started`});return;case`under_review`:s({status:`under-review`});return;case`rejected`:s({status:`rejected`,reason:r.rejection_reasons?.[0]?.reason});return;case`error`:s({status:`error`});return;default:}};return{load:te,start(e){s({status:`get-started`,pending:!0}),m(e)},acceptDisclosure(n){(async()=>{s({status:`accepting-disclosure`});try{await ps(e,{environment:t,acceptElectronicDisclosure:!0})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}n.aborted||await m(n)})()},acceptBankTerms(n){let r=a.openHostedPage();(async()=>{s({status:`accepting-bank-terms`});let i;try{i=await ps(e,{environment:t,acceptBankTerms:!0})}catch(e){r?.dismiss(),n.aborted||s({status:`error`,message:$(e)});return}if(n.aborted){r?.dismiss();return}if(i.status===`provider_terms_required`){s({status:`accepting-provider-terms`});let e=await h({page:r,url:i.tos_url,until:e=>e.status!==`provider_terms_required`,signal:n});if(e===`aborted`)return;if(e===`blocked`){s({status:`error`});return}if(e===`closed`||e===`stalled`){await ee(`provider`,n);return}await m(n);return}r?.dismiss(),await m(n)})()},proceed(e){let t=c;t&&(async()=>{s({status:t.kind===`provider`?`accepting-provider-terms`:`verifying-identity`});let n=t.kind===`provider`?e=>e.status!==`provider_terms_required`:e=>e.status===`ready`||e.status===`rejected`||e.status===`pending`||e.status===`under_review`,r=await h({url:t.url,until:n,signal:e});if(r!==`aborted`){if(r===`blocked`){s({status:`error`});return}if(r===`closed`||r===`stalled`){await ee(t.kind,e);return}await m(e)}})()},approve(e){let t=l;if(!t)return;let n=o?.status===`approve-error`;(async()=>{s({status:`approve-prompt`,pending:!0,vaultProvider:u?.providerName??null});let r;try{r=d(e)}catch(e){s({status:`error`,message:$(e),cardId:t});return}if(r.kind===`unsupported`){s(r.reason?{status:`error`,message:r.reason,cardId:t}:{status:`error`,cardId:t});return}if(n){try{if(await r.isApproved()){e.aborted||s({status:`ready`,cardId:t});return}}catch{}if(e.aborted)return}try{if(await r.approve(),e.aborted)return;s({status:`ready`,cardId:t})}catch(n){if(e.aborted)return;console.error(`[privy] Card spending approval failed after card creation`,n),s({status:`approve-error`,cardId:t})}})()},retry(e){te(e)}}},As=async(e,{cardId:t,environment:n,statementPeriod:r})=>(await e.fetchPrivyRouteRaw(p,{params:{card_id:t,statement_period:r},query:{environment:n}})).blob(),js=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),Ms=e=>Number.isFinite(e)?js.format(Math.abs(e)/100):``,Ns=({amount:e,status:t})=>e===0?`none`:t===`posted`&&e>0?`credit`:`debit`,Ps=({amount:e,status:t})=>{if(!Number.isFinite(e))return{text:``,isCredit:!1};let n=Ms(e);switch(Ns({amount:e,status:t})){case`credit`:return{text:`+ ${n}`,isCredit:!0};case`debit`:return{text:`- ${n}`,isCredit:!1};case`none`:return{text:n,isCredit:!1}}},Fs={month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`},Is=new Intl.DateTimeFormat(void 0,Fs),Ls=new Intl.DateTimeFormat(void 0,{...Fs,year:`numeric`}),Rs=({unixSeconds:e})=>{let t=new Date(e*1e3);return Number.isNaN(t.getTime())?``:(t.getFullYear()===new Date().getFullYear()?Is:Ls).format(t)},zs={usdc:`USDC`,pathusd:`PathUSD`,path_usd:`PathUSD`,ousd:`OUSD`,clusd:`CLUSD`},Bs=e=>e?zs[e.toLowerCase()]??e:``,Vs=async(e,{cardId:t,environment:n})=>{let{data:r}=await bs(e,{environment:n,limit:20});return r.find(e=>e.id===t)??null},Hs=e=>`The Prepaid Debit Visa Card (the “Card”) is issued by Lead Bank pursuant to licensing by Visa U.S.A. Inc. and may be used everywhere Visa is accepted. Must be 18 or older to apply. Fees may apply. See Cardholder Agreement and ${e} website for more details.\n\nBridge Ventures LLC (“Bridge”) is not a bank. Bridge is a financial technology company and is the Program Manager responsible for managing and operating the Card on behalf of Lead Bank. ${e} is not a bank. ${e} is a financial technology company and is the Platform Provider responsible for the application, access, and management of/for the card.`,Us=async(e,{cardId:t,environment:n,nonce:r})=>{let{data:i}=await e.fetchPrivyRoute(oe,{params:{card_id:t},body:{environment:n,nonce:r}});return i.ephemeral_key_secret},Ws=async(e,{appId:t,environment:n})=>{let{data:r}=await e.fetchPrivyRoute(se,{params:{app_id:t},query:{environment:n}});return{publishableKey:r.publishable_key,cardLogoUrl:r.card_logo_url??null,stripeAccount:r.stripe_account}},Gs=`eip155:42431`,Ks=[`eip155:11155111`,`eip155:11155420`,`eip155:80002`,`eip155:84532`,`eip155:421614`,`eip155:43113`],qs=[`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,`solana:devnet`],Js={...Object.fromEntries(Ks.flatMap(e=>{let t=ua[Number.parseInt(e.replace(`eip155:`,``))];return t?[[e,{stablecoinAddress:t,spenderAddress:`0x8cc0d9e8a157b73d1172a22f5066048bda46c0e3`}]]:[]})),[Gs]:{stablecoinAddress:`0x20C0000000000000000000000000000000000000`,spenderAddress:`0x1955a82a01E8c0A31371792b3045341eB8b938e2`},...Object.fromEntries(qs.map(e=>[e,{stablecoinAddress:da.devnet,programId:`cardWArqhdV5jeRXXjUti7cHAa4mj41Nj3Apc6RPZH2`,merchantId:1n}]))},Ys=(e,t)=>{let n=Js[e];if(n)return t===`ousd`&&e===Gs&&`spenderAddress`in n?{stablecoinAddress:`0x20c0000000000000000000006a37DA5C996874BE`,spenderAddress:`0x249E4Ce1A8fd56d7C362c108aDf409eeDCb940aB`}:n},Xs={"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":`solana:mainnet`,"solana:mainnet":`solana:mainnet`,"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":`solana:devnet`,"solana:devnet":`solana:devnet`},Zs=(e,t,n)=>{let r=t??Ys(e,n);if(!r)return null;let i=Xs[e];return i?`programId`in r?{...r,kind:`svm`,chain:i,merchantId:BigInt(r.merchantId)}:Qs(e,t):e.startsWith(`eip155:`)&&`spenderAddress`in r?{kind:`evm`,...r}:Qs(e,t)},Qs=(e,t)=>(t&&console.warn(`[privy] Ignoring the spendApproval option for "${e}": its shape does not match the chain (an eip155:* chain needs an EvmDevSpendApprovalTarget, a solana:* chain an SvmDevSpendApprovalTarget), or the chain is not a recognized spend-approval target.`),null),$s=e=>e.status===`pending`?`pending`:e.status===`declined`?`declined`:e.status===`expired`?`expired`:e.status===`reversed`?`reversed`:Ns(e)===`credit`?`credit`:null,ec=({step:e,onSuccess:t,onFailure:n})=>{switch(e.status){case`ready`:case`approve-error`:t({id:e.cardId});return;case`under-review`:n(Error(`Card application is under review`));return;case`rejected`:n(Error(e.reason??`Card application was rejected`));return;case`error`:if(e.cardId){t({id:e.cardId});return}n(Error(e.message??`Card sign-up failed`));return;default:n(Error(`User cancelled card sign-up`))}},tc=({exp_month:e,exp_year:t})=>{if(e===null||t===null)return!1;let n=new Date,r=n.getFullYear(),i=n.getMonth()+1;return t<r||t===r&&e<i},nc=async(e,{cardId:t,environment:n,limit:r,cursor:i})=>e.fetchPrivyRoute(ge,{params:{card_id:t},query:{environment:n,...r===void 0?{}:{limit:r},...i?{cursor:i}:{}}}),rc=async(e,{cardId:t,environment:n,reason:r})=>e.fetchPrivyRoute(Ye,{params:{card_id:t},body:{environment:n,replacement_reason:r}}),ic=({transaction:e,unknownMerchantName:t})=>({id:e.id,amount:e.amount,merchant:{name:e.merchant.name??t},status:e.status,created:e.created,currency:e.currency,dispute:e.dispute}),ac=async(e,{cardId:t,environment:n,encryptedNumber:r})=>e.fetchPrivyRoute(ut,{params:{card_id:t},body:{environment:n,pin:{encrypted_number:r}}}),oc=async(e,{cardId:t,environment:n,status:r})=>e.fetchPrivyRoute(lt,{params:{card_id:t},body:{environment:n,status:r}}),sc=`biconomy`,cc=`coinbase_smart_wallet`,lc=`kernel`,uc=`light_account`,dc=`safe`,fc=`thirdweb`,pc=`nexus`;var mc=qi;export{Ha as ALL_WALLET_CLIENT_TYPES,sc as BICONOMY,cc as COINBASE_SMART_WALLET,fs as ConnectedStandardSolanaWallet,bn as DATA_SUFFIX_PLUGIN_ID,Rn as EmbeddedProviderError,Yi as InMemoryCache,lc as KERNEL,uc as LIGHT_ACCOUNT,xs as LIST_CARDS_MAX_LIMIT,Ji as LocalStorage,wn as MoonpayApiError,pc as NEXUS,T as PrivyApiError,E as PrivyClientError,Ln as PrivyConnectorError,Nn as PrivyEmbeddedWalletErrorCode,Wn as PrivyProviderRpcError,k as ProviderErrors,dc as SAFE,Ua as SUPPORTED_CONNECTOR_TYPES,Da as SolanaClient,da as SolanaUsdcAddressMap,fc as THIRDWEB,ua as UsdcAddressMap,ps as acceptCardConsents,cs as addSessionSigners,ms as approveSpend,hs as buildRecentMonths,Fa as buildSolanaOffchainMessage,Li as chainToMoonpayCurrency,_s as chooseTempoEarnVault,z as cookies,oa as countryCodesAndNumbers,Fr as create,vs as createCard,ks as createCardSignUp,Sn as createDataSuffixPlugin,En as createErrorFormatter,Oa as createSiwsMessage,fo as crossApp,ts as cryptoDepositAccount,mc as default,Qa as delegatedActions,To as depositAddress,Pa as deriveSolanaApplicationDomain,As as downloadCardStatement,Hn as errorIndicatesMaxMfaRetries,Dn as errorIndicatesMfaCanceled,Un as errorIndicatesMfaRateLimit,Bn as errorIndicatesMfaTimeout,Vn as errorIndicatesMfaVerificationFailed,zn as errorIndicatesRecoveryIsNeeded,qa as formatLamportsAmount,ra as formatPhoneNumber,Ps as formatSignedTransactionAmount,Ka as formatTokenAmount,Rs as formatTransactionDate,Ms as formatUsdAmount,Wa as formatWalletAddress,Ga as formatWeiAmount,Ri as fundingMethodToMoonpayPaymentMethod,P as generateAuthorizationSignature,pa as generateWalletIdempotencyKey,Xi as getAllUserEmbeddedBitcoinWallets,ai as getAllUserEmbeddedEthereumWallets,si as getAllUserEmbeddedSolanaWallets,Bs as getCardAssetDisplayName,Vs as getCardById,Q as getCardCustomer,Hs as getCardDisclosure,Us as getCardEphemeralKey,Ws as getCardsConfig,ba as getCoinbaseOnRampUrl,dn as getCountryCallingCode,xn as getDataSuffixPlugin,$i as getEntropyDetailsFromAccount,Qi as getEntropyDetailsFromUser,Ea as getFiatOnrampProviderBrand,wa as getFiatOnrampProviderId,fa as getIsTokenUsdc,pr as getJsonRpcEndpointFromChain,ys as getOrCreateCardCustomer,ca as getPhoneCountryCodeAndNumber,sa as getPlaceholderPhoneNumber,ja as getSolanaClusterDisplayName,ka as getSolanaRpcEndpointForCluster,Aa as getSolanaUsdcMintAddressForCluster,Zs as getSpendApproval,$s as getTransactionBadge,q as getUserEmbeddedEthereumWallet,ci as getUserEmbeddedSolanaWallet,oi as getUserEmbeddedWallet,ea as getUserSmartWallet,rs as getWallet,os as getWalletAction,ec as handleSignUpClose,tc as isCardExpired,ii as isEmbeddedWalletAccount,Vr as isExtensionContext,xa as isSupportedChainIdForCoinbaseOnramp,Ii as isSupportedChainIdForMoonpay,O as isUnifiedWallet,ia as lastFourDigits,nc as listCardTransactions,bs as listCards,ss as listWalletActions,Ia as parseSolanaOffchainMessage,aa as phoneNumberTypingFormatter,Z as poll,ns as rawSign,Ss as readSpendAllowance,Cs as readTempoEarnVault,ls as removeSessionSigners,rc as replaceCard,L as rpc,Hr as shouldWriteSessionCookies,mr as throwIfInvalidRecoveryUpgradePath,Ca as toCoinbaseAssetId,Sa as toCoinbaseBlockchainFromChainId,na as toE164,la as toObjectKeys,ic as toTransactionRow,vr as toWalletApiUnsignedEthTransaction,as as transfer,ac as updateCardPin,oc as updateCardStatus,is as updateWallet,ta as validatePhoneNumber};
34
+ - https://privy.io`;function ja({name:e,rpcUrl:t}){if(t)return t;switch(e){case`mainnet-beta`:return`https://api.mainnet-beta.solana.com`;case`testnet`:return`https://api.testnet.solana.com`;case`devnet`:return`https://api.devnet.solana.com`}}function Ma({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function Na(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const Pa=`solana offchain`,Fa=1232;function Ia(t){let n=e.utf8.toBytes(t),r=new Uint8Array(32);return r.set(n.slice(0,32)),r}function La({message:t,signerPublicKey:n,domain:r}){let i=e.utf8.toBytes(t);if(n.length!==32)throw Error(`Signer public key must be 32 bytes`);let a=85+i.length;if(a>Fa)throw Error(`Combined message length (${a}) exceeds maximum (${Fa})`);let o=Ia(r),s=new Uint8Array(a),c=0;s[c]=255,c+=1;let l=e.utf8.toBytes(Pa);return s.set(l,c),c+=l.length,s[c]=0,c+=1,s.set(o,c),c+=32,s[c]=1,c+=1,s[c]=1,c+=1,s.set(n,c),c+=32,s[c]=i.length&255,s[c+1]=i.length>>8&255,c+=2,s.set(i,c),s}function Ra(e){if(e.length<85)throw Error(`Message too short to contain a valid off-chain preamble`);let t=0;if(e[t]!==255)throw Error(`Invalid signing domain prefix`);if(t+=1,new TextDecoder().decode(e.slice(t,t+15))!==Pa)throw Error(`Invalid signing domain text`);t+=15;let n=e[t];t+=1;let r=e.slice(t,t+32);t+=32;let i=e[t];t+=1;let a=e[t];if(a!==1)throw Error(`Expected 1 signer, got ${a}`);t+=1;let o=e.slice(t,t+32);t+=32;let s=e[t]|e[t+1]<<8;if(t+=2,e.length<t+s)throw Error(`Message body is shorter than declared length`);return{version:n,applicationDomain:r,format:i,signerPublicKey:o,message:new TextDecoder().decode(e.slice(t,t+s))}}const za=[`privy`],Ba=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],Va=[`coinbase_wallet`],Ha=`metamask.trust.safe.rainbow.uniswap.zerion.argent.spot.omni.cryptocom.blockchain.safepal.bitget_wallet.zengo.1inch.binance.exodus.mew_wallet.alphawallet.keyring_pro.mathwallet.unstoppable.obvious.ambire.internet_money_wallet.coin98.abc_wallet.arculus_wallet.haha.cling_wallet.broearn.copiosa.burrito_wallet.enjin_wallet.plasma_wallet.avacus.bee.pitaka.pltwallet.minerva.kryptogo.prema.slingshot.kriptonio.timeless.secux.bitizen.blocto.safemoon`.split(`.`),Ua=[`unknown`],Wa=[...Ba,...Va,...Ha,...za,...Ua],Ga=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Ka(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function qa({wei:e,precision:t=3}){return parseFloat(Ut(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function Ja({amount:e,decimals:t}){return Wt(BigInt(e),t)}function Ya({lamports:e}){return Wt(e,9)}const Xa=e=>[...si(e),...li(e)],Za=(e,t)=>e.imported?e:q(t)??ui(t),Qa=e=>async({address:t,chainType:n})=>{let{user:r}=await e.user.get();if(!r)throw new E({code:`delegated_actions_before_logged_in`,error:`Must be logged in to delegate wallets`});if(n!==`solana`&&n!==`ethereum`)throw new E({code:`unsupported_chain_type`,error:`Only Solana and Ethereum embedded wallets are supported for delegation and revocation.`});let i=Xa(r).find(e=>e.chain_type===n&&e.address===t);if(!i)throw new E({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});if(O(i))throw new E({code:`unsupported_wallet_type`,error:`useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`});if(i.delegated)return{user:r};let a=Za(i,r);if(!a)throw new E({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});await e.embeddedWallet.delegateWallets({rootWallet:{address:a.address,chainType:a.chain_type,imported:a.imported},delegatedWallets:[{address:i.address,chainType:i.chain_type,walletIndex:i.wallet_index}]});let{user:o}=await e.user.get();return{user:o}},$a=e=>async()=>{let{user:t}=await e.user.get();if(!t)throw new E({code:`delegated_actions_before_logged_in`,error:`Must be logged in to revoke delegated wallets`});let n=Xa(t);if(n.some(O))throw new E({code:`unsupported_wallet_type`,error:`revokeWallets is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to manage server side access on behalf of your users. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`});if(n.every(e=>!e.delegated))throw new E({code:`delegated_actions_no_wallet_to_revoke`,error:`User has no delegated wallets to revoke.`});await e.delegated.revoke();let{user:r}=await e.user.get();return{user:r}};var eo=w({delegateWallet:()=>Qa,revokeWallets:()=>$a});const to=({client:e,openAuthSession:t})=>async({providerAppId:n,redirectUrl:r,loginOptions:i})=>{let a=`privy:${n}`,{url:o}=await e.auth.oauth.generateURL(a,r),s=await t(o,r),c=s.privy_oauth_state,l=s.privy_oauth_code;if(!c||!l)throw new E({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let u=await e.auth.oauth.loginWithCode(l,c,a,void 0,void 0,i),d=u.oauth_tokens;return d&&await e.crossApp.updateOnCrossAppAuthentication(n,d),u},no=({client:e,openAuthSession:t})=>async({providerAppId:n,redirectUrl:r})=>{let i=`privy:${n}`,{url:a}=await e.auth.oauth.generateURL(i,r),o=await t(a,r),s=o.privy_oauth_state,c=o.privy_oauth_code;if(!s||!c)throw new E({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let{user:l,oauth_tokens:u}=await e.auth.oauth.linkWithCode(c,s,i);return u&&await e.crossApp.updateOnCrossAppAuthentication(n,u),l};function ro(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const io=(e,t)=>e.linked_accounts.filter(e=>e.type===`cross_app`).find(({embedded_wallets:e,smart_wallets:n})=>[...e,...n].some(e=>e.address===t)),ao=({client:e,openAuthSession:t})=>{let n=no({client:e,openAuthSession:t});return async({providerAppId:t,redirectUrl:r})=>await e.crossApp.getProviderAccessToken(t)||(await n({providerAppId:t,redirectUrl:r}),await e.crossApp.getProviderAccessToken(t))},oo=({client:e,openAuthSession:t})=>{let n=ao({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=io(r,o);if(!s)throw new E({code:`cross_app_invalid_wallet`,error:`Cannot operate with this wallet address`});let c=s.provider_app_id,{connections:l}=await e.crossApp.getCrossAppConnections(),u=l.find(e=>e.provider_app_id===c);if(!u)throw new E({code:`cross_app_invalid_app`,error:`Invalid connected app`});if(u.read_only)throw new E({code:`cross_app_read_only`,error:`Cannot transact against a read-only provider app`});let d=await n({providerAppId:c,redirectUrl:a});if(!d)throw new E({code:`cross_app_request_error`,error:`Wallet operations require a valid token`});let f={content:{request:{request:i}},timestamp:Date.now(),callbackUrl:a},p=new URL(`${u.provider_app_custom_api_url}/oauth/transact`);p.searchParams.set(`communicationMode`,`redirect`),p.searchParams.set(`token`,d),p.searchParams.set(`request`,JSON.stringify(f));let{privy_cross_app_type:m,privy_cross_app_payload:h}=await t(p.href,a);if(!m||!h)throw new E({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(m===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new E({code:`cross_app_request_error`,error:h});if(m!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new E({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:h}}};function so(e){if(!e)throw new E({code:`attempted_cross_app_request_before_logged_in`,error:`Must be logged in to sign messages with a cross-app wallet`})}const co=({client:e,openAuthSession:t})=>{let n=oo({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{so(e);let a={method:ro(e,t)?`privy_signSmartWalletMessage`:`personal_sign`,params:[r,t]},{result:o}=await n({user:e,request:a,address:t,redirectUrl:i});return{signature:o}}};function lo(e){let t={name:`string`,version:`string`,chainId:`uint256`,verifyingContract:`address`,salt:`bytes32`},n=e.types.EIP712Domain??Object.entries(e.domain??{}).map(([e,n])=>{if(n!=null&&typeof e==`string`&&e in t)return{name:e,type:t[e]}}).filter(e=>!!e),r={...e.types};return r.EIP712Domain=n,{...e,types:r}}const uo=({client:e,openAuthSession:t})=>{let n=oo({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{so(e);let a={method:ro(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,lo(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},fo=({client:e,openAuthSession:t})=>{let n=oo({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{so(e);let a={method:ro(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var po=w({sendTransaction:()=>fo,signMessage:()=>co,signTypedData:()=>uo}),mo=w({linkWithCrossAppAuth:()=>no,loginWithCrossAppAuth:()=>to,wallet:()=>po});function ho(e){if(e.startsWith(`eip155:`))return`ethereum`;if(e.startsWith(`solana:`))return`solana`;if(e.startsWith(`bip122:`))return`bitcoin-segwit`;if(e.startsWith(`tron:`))return`tron`}function go(e,t){let n=ho(e);if(!n)return;let r=t.linked_accounts.find(e=>e.type===`wallet`&&e.chain_type===n&&`address`in e&&e.address);return r&&`address`in r?r.address:void 0}async function _o(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=go(e.caip2,t);if(n)return{ok:!0,address:n};let r=ho(e.caip2);if(!r)return{ok:!1,error:`UNSUPPORTED_CHAIN`};try{let t=await e.privy.fetchPrivyRoute(ft,{body:{chain_type:r}});return await e.privy.user.get(),await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function vo(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await _o({privy:e.privy,caip2:e.sourceChain,onWalletCreated:e.onWalletCreated});if(!t.ok)throw Error(t.error);n=t.address}let r=await e.privy.fetchPrivyRoute(u,{body:{source_chain:e.sourceChain,source_currency:e.sourceCurrency,destination_chain:e.destinationChain,destination_currency:e.destinationCurrency,destination_address:e.destinationAddress,refund_address:n,...e.slippageBps==null?{}:{slippage_bps:e.slippageBps}}});return e.privy.track({name:`sdk_deposit_address_headless_quote`,properties:{sourceChain:e.sourceChain,sourceCurrency:e.sourceCurrency,destinationChain:e.destinationChain,destinationCurrency:e.destinationCurrency,depositAddressId:r.id}}),r}function yo(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const Z=async({operation:e,until:t,delay:n,interval:r,attempts:i,signal:a})=>{n&&await yo(n);let o=0,s,c;for(;o<i;){if(a?.aborted)return{status:`aborted`,result:s,attempts:o,error:c};o++;try{if(c=void 0,s=await e(),t(s))return{status:`success`,result:s,attempts:o};o<i&&await yo(r)}catch(e){e instanceof Error&&(c=e),o<i&&await yo(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},bo=2e3,xo=1800*1e3;function So(e,t){return Math.ceil(t/e)}function Co(e){return e.status===`success`?e.result?{status:`success`,order:e.result}:{status:`timeout`}:e.status===`aborted`?{status:`aborted`,error:e.error}:{status:`timeout`,error:e.error}}async function wo(e){return await e.privy.fetchPrivyRoute(de,{params:{order_id:e.orderId}})}async function To(e){let t=e.pollIntervalMs??bo,n=e.timeoutMs??xo,r=e.signal??new AbortController().signal;return Co(await Z({operation:async()=>{let t=await e.privy.fetchPrivyRoute(pe,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(de,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:So(t,n),signal:r}))}async function Eo(e){let t=e.pollIntervalMs??bo,n=e.timeoutMs??xo,r=e.signal??new AbortController().signal;return Co(await Z({operation:()=>e.privy.fetchPrivyRoute(de,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:So(t,n),signal:r}))}var Do=w({generateDepositAddress:()=>vo,getConfig:()=>Oo,getDeposit:()=>wo,resolveRefundAddress:()=>_o,waitForCompletion:()=>Eo,waitForDeposit:()=>To});async function Oo(e){let t=await e.fetchPrivyRoute(fe,{});return{currencies:t.currencies,chains:t.chains}}function ko(e){let t=e.depositAddressStrategy===void 0?{}:{deposit_address_strategy:e.depositAddressStrategy};return e.type===`deposit_config`?{type:`deposit_config`,deposit_config_id:e.depositConfigId,...t}:{type:`inline_route`,source:e.source,destination:e.destination,...t}}async function Ao(e,t,n){let{walletId:r}=n,i=ko(n),a=e.getCompiledPath(c,{params:{wallet_id:r}}),o=String(Date.now()+F),{signature:s}=await N(t,{version:1,url:a,method:c.method,headers:{"privy-app-id":e.app.appId,[P]:o},body:i});if(Date.now()>Number(o))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});let l=await e.fetchPrivyRoute(c,{body:i,params:{wallet_id:r},headers:{"privy-authorization-signature":s,[P]:o}});return e.track({name:`sdk_deposit_address_headless_create`,properties:{version:`v3`,action:`create`,walletId:r,type:n.type,...n.type===`inline_route`?{destinationChain:n.destination.chain,destinationCurrency:n.destination.asset}:{depositConfigId:n.depositConfigId}}}),l}async function jo(e,t){let n=await e.fetchPrivyRoute(l,{body:{source:t.source,destination:t.destination,...t.inputAmount==null?{}:{input_amount:t.inputAmount},...t.slippageBps==null?{}:{slippage_bps:t.slippageBps}}});return e.track({name:`sdk_deposit_address_headless_quote`,properties:{version:`v3`,action:`quote`,sourceChain:t.source.chain,sourceCurrency:t.source.asset,destinationChain:t.destination.chain,destinationCurrency:t.destination.asset}}),n}function Mo(e){let t=Number(e.input_amount),n=Number(e.estimated_output_amount);if(!(!Number.isFinite(t)||!Number.isFinite(n)||t===0))return String(n/t)}async function No(e,t){return e.fetchPrivyRoute(Xe,{query:{q:t}})}async function Po(e,t){return e.fetchPrivyRoute(ue,{params:{wallet_id:t.walletId,order_id:t.orderId}})}async function Fo(e,t){return e.fetchPrivyRoute(le,{params:{wallet_id:t.walletId},query:{after:t.after}})}const Io={ethereum:`eip155:1`,arbitrum:`eip155:42161`,avalanche:`eip155:43114`,arc:`eip155:5042`,monad:`eip155:143`,base:`eip155:8453`,tempo:`eip155:4217`,linea:`eip155:59144`,optimism:`eip155:10`,polygon:`eip155:137`,bsc:`eip155:56`,zksync_era:`eip155:324`,solana:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,tron:`tron:mainnet`,robinhood:`eip155:4663`,unichain:`eip155:130`,worldchain:`eip155:480`,ink:`eip155:57073`,soneium:`eip155:1868`,megaeth:`eip155:4326`,hyperevm:`eip155:999`,hypercore:`eip155:1337`,"tempo_zone:00001":`eip155:421700001`,"tempo_zone:00002":`eip155:421700002`,tempo_testnet:`eip155:42431`,"tempo_testnet_zone:00003":`eip155:1424310003`,hoodi:`eip155:560048`,sepolia:`eip155:11155111`,arbitrum_sepolia:`eip155:421614`,avalanche_fuji:`eip155:43113`,base_sepolia:`eip155:84532`,linea_testnet:`eip155:59140`,optimism_sepolia:`eip155:11155420`,polygon_amoy:`eip155:80002`,bsc_testnet:`eip155:97`,solana_devnet:`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,solana_testnet:`solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`,tron_nile:`tron:nile`,robinhood_testnet:`eip155:46630`,ink_sepolia:`eip155:763373`},Lo=[{id:`eth`,symbol:`ETH`},{id:`sol`,symbol:`SOL`},{id:`pol`,symbol:`POL`},{id:`trx`,symbol:`TRX`},{id:`usdc`,symbol:`USDC`},{id:`usdc_e`,symbol:`USDC.e`},{id:`usdt`,symbol:`USDT`},{id:`usdt0`,symbol:`USDT0`},{id:`usdb`,symbol:`USDB`},{id:`eurc`,symbol:`EURC`},{id:`ousd`,symbol:`OUSD`},{id:`usdg`,symbol:`USDG`},{id:`pathusd`,symbol:`PathUSD`}],Ro=new Set([`native`,`native-token`,`0x0000000000000000000000000000000000000000`,`11111111111111111111111111111111`]);function zo(e){return Ro.has(e.toLowerCase())}function Bo(e){return e.includes(`:`)}function Vo(e){return Bo(e)?e:Io[e.toLowerCase()]||(/^\d+$/.test(e)?`eip155:${e}`:e)}function Ho(e){return zo(e)}function Uo(e){let t=e.toLowerCase();return Lo.find(e=>e.id===t||e.symbol.toLowerCase()===t)}function Wo({symbol:e,address:t}){return Uo(e)?.id??t}function Go({asset:e,symbol:t,addresses:n}){let r=e.toLowerCase();return t.toLowerCase()===r?!0:Ho(e)?n.some(zo):n.some(e=>e.toLowerCase()===r)}function Ko({config:e,chain:t,asset:n}){let r=t?Vo(t):void 0;for(let t of e.currencies){let e=r?t.chains.filter(e=>Vo(e.caip2)===r):t.chains;if(e.length!==0&&Go({asset:n,symbol:t.symbol,addresses:e.map(e=>e.address)}))return t.symbol}return n.toUpperCase()}function qo(e,t,n){return Jo(e,n)===Jo(t,n)}function Jo(e,t){if(/^eip155:\d+$/i.test(e))return e.toLowerCase();let n=Vo(e);if(n!==e||e.includes(`:`))return n;let r=e.toLowerCase();for(let n of Object.values(t.chains))if(n.caip2===e||n.display_name.toLowerCase()===r||String(n.chain_id)===e)return n.caip2;return n}function Yo(e,t){return t.asset===`*`||Go({asset:t.asset,symbol:e.symbol,addresses:e.chains.map(e=>e.address)})}function Xo({caip2:e,asset:t,config:n}){return!t.chain||t.chain===`*`||qo(t.chain,e,n)}function Zo({currency:e,source:t,config:n}){switch(t.mode){case`all`:return e.chains;case`include`:{let r=t.values.filter(t=>Yo(e,t));return r.length===0?[]:e.chains.filter(e=>r.some(t=>Xo({caip2:e.caip2,asset:t,config:n})))}case`exclude`:{let r=t.values.filter(t=>Yo(e,t));return r.length===0?e.chains:e.chains.filter(e=>!r.some(t=>Xo({caip2:e.caip2,asset:t,config:n})))}default:return e.chains}}function Qo(e,t){return{currencies:e.currencies.map(n=>({...n,chains:Zo({currency:n,source:t,config:e})})).filter(e=>e.chains.length>0),chains:e.chains}}const $o=/^T[1-9A-HJ-NP-Za-km-z]{33}$/,es=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function ts(e,t){switch(t){case`evm`:case`hypevm`:return Kt(e,{strict:!1});case`svm`:return es.test(e)&&!$o.test(e);case`tron`:case`tvm`:return $o.test(e);default:return!1}}function ns({accounts:e,selectedChain:t}){return e.find(e=>ts(e.deposit_address,t.vmType))?.deposit_address}var rs=w({createCryptoDepositAccount:()=>Ao,filterDepositConfig:()=>Qo,findCatalogSymbol:()=>Ko,getCryptoDepositAccountNextOrder:()=>Fo,getCryptoDepositAccountOrder:()=>Po,getCryptoDepositAccountQuote:()=>jo,indicativeRateFromQuote:()=>Mo,isNativeAssetAlias:()=>Ho,pickDepositAddressForChain:()=>ns,quoteSourceAsset:()=>Wo,resolveChainAlias:()=>Vo,searchCryptoDepositAccountConfig:()=>No});async function is(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(gt,{params:{wallet_id:n}}),a=String(Date.now()+F),{signature:o}=await N(t,{version:1,url:i,method:gt.method,headers:{"privy-app-id":e.app.appId,[P]:a},body:{...r}});if(Date.now()>Number(a))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(gt,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[P]:a}})}async function as(e,{wallet_id:t}){return await e.fetchPrivyRoute(pt,{params:{wallet_id:t}})}async function os(e,{wallet_id:t},n,r){let i=e.getCompiledPath(yt,{params:{wallet_id:t}}),a=String(Date.now()+F),{signature:o}=await N(n,{version:1,url:i,method:yt.method,headers:{"privy-app-id":e.app.appId,[P]:a},body:r});if(Date.now()>Number(a))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(yt,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":o,[P]:a}})}async function ss(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(vt,{params:{wallet_id:n}}),a=String(Date.now()+F),{signature:o}=await N(t,{version:1,url:i,method:vt.method,headers:{"privy-app-id":e.app.appId,[P]:a},body:{...r}});if(Date.now()>Number(a))throw new E({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(vt,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[P]:a}})}async function cs(e,{wallet_id:t,action_id:n}){return await e.fetchPrivyRoute(mt,{params:{wallet_id:t,action_id:n}})}async function ls(e,{wallet_id:t,...n}){return await e.fetchPrivyRoute(ht,{params:{wallet_id:t},query:{...n.cursor?{cursor:n.cursor}:{},...n.limit===void 0||n.limit===null?{}:{limit:n.limit},...n.type?{type:n.type}:{}}})}async function us({client:e,wallet:t,signers:n}){if(t.chain_type!==`ethereum`&&t.chain_type!==`solana`)throw Error(`Session signers are only supported for Ethereum and Solana wallets`);if(O(t)){if(n.length===0)throw Error(`Must specify at least one signer to add.`);let r={wallet_id:t.id},i=await as(e,r);await os(e,r,ps(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return fs(e);if(n.length>0)throw Error(`Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide`);let{user:r}=await e.user.get(),i=Za(t,r);if(!i)throw Error(`Unable to determine root address for delegated address.`);await e.embeddedWallet.delegateWallets({rootWallet:{address:i.address,chainType:i.chain_type,imported:i.imported??!1},delegatedWallets:[{address:t.address,chainType:t.chain_type,walletIndex:t.wallet_index}]})}return fs(e)}async function ds({client:e,wallet:t}){return O(t)?await os(e,{wallet_id:t.id},ps(e),{additional_signers:[]}):await e.delegated.revoke(),fs(e)}async function fs(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function ps(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var ms=class{#e;#t;get standardWallet(){return this.#e}get address(){return this.#t.address}constructor({wallet:e,account:t}){this.#e=e,this.#t=t}async disconnect(){if(!this.#e.features[`standard:disconnect`]?.disconnect)throw Error(`Wallet does not support disconnect`);await this.#e.features[`standard:disconnect`].disconnect()}async signMessage(...e){if(!this.#e.features[`solana:signMessage`]?.signMessage)throw Error(`Wallet does not support signMessage`);let t=await this.#e.features[`solana:signMessage`].signMessage(...e.map(e=>({...e,account:this.#t})));return e.length===1?t[0]:[...t]}async signTransaction(...e){if(!this.#e.features[`solana:signTransaction`]?.signTransaction)throw Error(`Wallet does not support signTransaction`);let t=await this.#e.features[`solana:signTransaction`].signTransaction(...e.map(e=>({...e,account:this.#t})));return e.length===1?t[0]:[...t]}async signAndSendTransaction(...e){if(!this.#e.features[`solana:signAndSendTransaction`]?.signAndSendTransaction)throw Error(`Wallet does not support signAndSendTransaction`);let t=await this.#e.features[`solana:signAndSendTransaction`].signAndSendTransaction(...e.map(e=>({...e,account:this.#t})));return e.length===1?t[0]:[...t]}async signAndSendAllTransactions(e){if(!this.#e.features[`solana:signAndSendTransaction`]?.signAndSendTransaction)throw Error(`Wallet does not support signAndSendTransaction`);return[...await this.#e.features[`solana:signAndSendTransaction`].signAndSendTransaction(...e.map(e=>({...e,account:this.#t})))]}};const hs=async(e,{environment:n,acceptElectronicDisclosure:r,acceptBankTerms:i})=>{let{data:a}=await e.fetchPrivyRoute(t,{body:{environment:n,accept_electronic_disclosure:r,accept_bank_terms:i}});return a},gs=async({sendTransaction:e,evmChainId:t,stablecoinAddress:n,spenderAddress:r})=>{let i={to:n,chainId:t,data:Vt({abi:Ht,functionName:`approve`,args:[r,Jt]})};try{return await e(i,{sponsor:!0})}catch(t){return console.warn(`[privy] Sponsored card approval failed; retrying pre-funded.`,t instanceof Error?t.message:String(t)),e(i,{sponsor:!1})}},_s=({cardCreatedAt:e,environment:t,now:n=new Date})=>{let r=new Intl.DateTimeFormat(void 0,{month:`long`,year:`numeric`,timeZone:`UTC`}),i=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1),a=+(t===`production`),o=[];for(let e=0;e<24;e++){let t=Date.UTC(n.getUTCFullYear(),n.getUTCMonth()-a-e,1);if(t<i)break;let s=new Date(t),c=`${s.getUTCFullYear()}-${String(s.getUTCMonth()+1).padStart(2,`0`)}`;o.push({value:c,label:r.format(s)})}return o},vs=85.6,ys=53.98,bs=18.872,xs=6.095,Ss=3,Cs=3,ws=11,Ts=.14,Es=128,Ds=360,Os=1.5,ks={cardNumber:{widthFraction:16/360,minPx:16,maxPx:16*Os},fieldValue:{widthFraction:14/360,minPx:14,maxPx:14*Os},fieldLabel:{widthFraction:10/360,minPx:10,maxPx:10*Os}},As=(e,t)=>{let n=e&&e.width>0&&e.height>0?e.width/e.height:1,r=3*(t.widthPx/vs),i=Math.min(Math.round(t.heightPx*Ts),(t.widthPx-2*r)/n);return{widthPx:i*n,heightPx:i}},js=e=>{let t=e/vs,n=ys*t,r=({widthFraction:t,minPx:n,maxPx:r})=>Math.min(r,Math.max(n,t*e));return{widthPx:e,heightPx:n,edgeInsetPx:3*t,logoHeightPx:Math.round(n*Ts),visaMarkWidthPx:bs*t,visaMarkHeightPx:xs*t,debitSizePx:11*.35277777777777775*t,debitGapPx:3*t,textSizePx:{cardNumber:r(ks.cardNumber),fieldValue:r(ks.fieldValue),fieldLabel:r(ks.fieldLabel)}}},Ms=[{type:`function`,name:`publicCall`,stateMutability:`nonpayable`,inputs:[{name:`data`,type:`bytes`}],outputs:[]},{type:`function`,name:`publicGetCall`,stateMutability:`view`,inputs:[{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bytes`}]}],Ns=async({sendTransaction:e,evmChainId:t,spenderAddress:n,vaultAddress:r})=>{let i={to:n,chainId:t,data:Vt({abi:Ms,functionName:`publicCall`,args:[Lt([Yt(`TEUP`),r])]})};try{return await e(i,{sponsor:!0})}catch(t){return console.warn(`[privy] Sponsored card vault choice failed; retrying pre-funded.`,t instanceof Error?t.message:String(t)),e(i,{sponsor:!1})}},Ps=async(e,{environment:t,walletId:n,chainId:r,asset:i})=>e.fetchPrivyRoute(s,{body:{environment:t,wallet_id:n,chain_id:r,asset:i}}),Q=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(ae,{query:{environment:t}});return n},Fs=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(dt,{body:{environment:t}});return n},Is=async(e,{environment:t,limit:n,cursor:r})=>e.fetchPrivyRoute(_e,{query:{environment:t,...n===void 0?{}:{limit:n},...r?{cursor:r}:{}}}),Ls=20,Rs=async({provider:e,evmChainId:t,owner:n,stablecoinAddress:r,spenderAddress:i})=>{await e.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${t.toString(16)}`}]});let a=await e.request({method:`eth_call`,params:[{to:r,data:Vt({abi:Ht,functionName:`allowance`,args:[n,i]})},`latest`]});if(!qt(a)||a===`0x`)throw Error(`Could not read the spend approval`);return Bt({abi:Ht,functionName:`allowance`,data:a})},zs=async({provider:e,evmChainId:t,owner:n,spenderAddress:r})=>{await e.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${t.toString(16)}`}]});let i=await e.request({method:`eth_call`,params:[{to:r,data:Vt({abi:Ms,functionName:`publicGetCall`,args:[Lt([Yt(`TEGP`),n])]})},`latest`]});if(!qt(i)||i===`0x`)throw Error(`Could not read the card vault choice`);let[a]=zt([{type:`address`}],Bt({abi:Ms,functionName:`publicGetCall`,data:i}));return a},Bs=2e3,Vs=1e3,Hs=new Map([[`morpho`,`Morpho`],[`aave`,`Aave`]]),Us=e=>{switch(e.status){case`kyc_required`:return{kind:`kyc`,url:e.kyc_url};case`provider_terms_required`:return{kind:`provider`,url:e.tos_url};default:return null}},Ws=e=>{try{return new URL(e).protocol===`https:`?e:null}catch{return null}},$=e=>e instanceof Error&&e.message?e.message:void 0,Gs=({client:e,environment:t,walletId:n,chainId:r,asset:i,platform:a})=>{let o=null,s=e=>{o=e,a.setStep(e)},c=null,l=null,u=null,d=i=>{let o=u;if(!o)return a.resolveSpendApproval();if(!r.startsWith(`eip155:`))return{kind:`unsupported`};let{spenderAddress:s,shareTokenAddress:c}=o,d=a.resolveEvmWallet(),f=Number(r.slice(7)),p=async()=>Rs({provider:await d.getProvider(),evmChainId:f,owner:d.address,stablecoinAddress:c,spenderAddress:s}),m=async()=>zs({provider:await d.getProvider(),evmChainId:f,owner:d.address,spenderAddress:s});return{kind:`supported`,isApproved:async()=>await p()>0n&&(o.kind!==`opt_in`||await m()!==Zt),approve:async()=>{if(await gs({sendTransaction:d.sendTransaction,evmChainId:f,stablecoinAddress:c,spenderAddress:s}),o.kind!==`opt_in`)return;let a=await Z({operation:p,until:e=>e>0n,delay:0,interval:Vs,attempts:60,signal:i});if(a.status===`aborted`)return;if(a.status===`max_attempts`)throw Error(`The share approval did not land in time`,{cause:a.error});let u=await m();if(i.aborted||u!==Zt)return;await Ns({sendTransaction:d.sendTransaction,evmChainId:f,spenderAddress:s,vaultAddress:o.vaultAddress});let h=await Z({operation:m,until:e=>e.toLowerCase()===o.vaultAddress.toLowerCase(),delay:0,interval:Vs,attempts:60,signal:i});if(h.status===`max_attempts`)throw Error(`The vault choice did not land in time`,{cause:h.error});h.status===`success`&&l&&e.track({name:`sdk_card_sign_up_tempo_earn_opt_in`,properties:{cardId:l,walletId:n,chainId:r,environment:t,vaultAddress:o.vaultAddress}})}}},f=async(e,t)=>{if(t.aborted)return;l=e;let n={status:`approve-prompt`,vaultProvider:u?.providerName??null},r;try{r=d(t)}catch{s(n);return}if(r.kind===`unsupported`){s(r.reason?{status:`error`,message:r.reason,cardId:e}:{status:`error`,cardId:e});return}try{let i=await r.isApproved();if(t.aborted)return;s(i?{status:`ready`,cardId:e}:n)}catch{t.aborted||s(n)}},p=async a=>{if(!a.aborted)try{let o=await Is(e,{environment:t,limit:20});if(a.aborted)return;let c=o.data.find(e=>e.wallet_id===n&&e.chain_id===r&&e.asset===i&&e.status!==`replaced`);if(c||=(s({status:`creating-card`}),await Ps(e,{environment:t,walletId:n,chainId:r,asset:i})),a.aborted)return;let l=c.funding_sources,d=l?.find(e=>e.selected),p;if(d?.type===`erc4626_vault`?p=Hs.get(d.provider):d?.type===`tempo_earn_vault`&&(p=`Tempo`),l&&!d||d&&d.type!==`wallet`&&!p){console.warn(`[privy] Card funding source is not supported by this SDK version`,{type:d?.type,provider:d?.type===`erc4626_vault`?d.provider:void 0}),s({status:`error`,cardId:c.id});return}if(u=null,d&&d.type!==`wallet`&&p)u={kind:`selected`,spenderAddress:d.spender_address,shareTokenAddress:d.share_token_address,providerName:p};else{let e=c.funding_sources?.find(e=>e.type===`tempo_earn_vault`);e&&(u={kind:`opt_in`,spenderAddress:e.spender_address,shareTokenAddress:e.share_token_address,providerName:`Tempo`,vaultAddress:e.vault_address})}await f(c.id,a)}catch(e){if(a.aborted)return;s({status:`error`,message:$(e)})}},m=async n=>{let r=0;for(;!n.aborted;){if(++r>10){s({status:`error`});return}let i;try{i=await Q(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}if(n.aborted)return;switch(i.status){case`not_created`:try{await Fs(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}continue;case`electronic_disclosure_required`:s({status:`disclosure-prompt`,disclosureUrl:i.disclosure_url});return;case`bank_terms_required`:s({status:`bank-terms-prompt`,bankInfo:i.bank_info});return;case`provider_terms_required`:c={kind:`provider`,url:i.tos_url},s({status:`provider-terms-prompt`});return;case`kyc_required`:c={kind:`kyc`,url:i.kyc_url},s({status:`kyc-prompt`});return;case`pending`:if(s({status:`pending`}),(await Z({operation:()=>Q(e,{environment:t}),until:e=>e.status!==`pending`,delay:0,interval:Bs,attempts:60,signal:n})).status!==`success`)return;continue;case`under_review`:s({status:`under-review`});return;case`ready`:await p(n);return;case`rejected`:s({status:`rejected`,reason:i.rejection_reasons?.[0]?.reason});return;case`error`:s({status:`error`});return;default:return}}},h=async({page:n,url:r,until:i,signal:o})=>{let s=Ws(r);if(!s)return n?.dismiss(),`blocked`;let c=n??a.openHostedPage(s);if(!c)return`blocked`;n&&n.navigate(s);let l=await Z({operation:()=>Q(e,{environment:t}),until:e=>i(e)||c.isClosed(),delay:0,interval:Bs,attempts:60,signal:o});if(l.status===`aborted`)return c.dismiss(),`aborted`;if(l.status===`max_attempts`)return`stalled`;if(i(l.result))return c.dismiss(),`advanced`;let u=await Z({operation:()=>Q(e,{environment:t}),until:i,delay:0,interval:1e3,attempts:5,signal:o});return u.status===`aborted`?(c.dismiss(),`aborted`):u.status===`success`?`advanced`:`closed`},ee=async(n,r)=>{c=null,s({status:n===`provider`?`provider-terms-prompt`:`kyc-prompt`,pending:!0});try{let n=await Q(e,{environment:t});if(r.aborted)return;let i=Us(n);if(i){c=i,s({status:i.kind===`provider`?`provider-terms-prompt`:`kyc-prompt`});return}}catch(e){r.aborted||s({status:`error`,message:$(e)});return}await m(r)},te=async n=>{s({status:`loading`});let r;try{r=await Q(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}if(!n.aborted)switch(r.status){case`not_created`:case`electronic_disclosure_required`:case`bank_terms_required`:case`provider_terms_required`:case`kyc_required`:case`pending`:case`ready`:s({status:`get-started`});return;case`under_review`:s({status:`under-review`});return;case`rejected`:s({status:`rejected`,reason:r.rejection_reasons?.[0]?.reason});return;case`error`:s({status:`error`});return;default:}};return{load:te,start(e){s({status:`get-started`,pending:!0}),m(e)},acceptDisclosure(n){(async()=>{s({status:`accepting-disclosure`});try{await hs(e,{environment:t,acceptElectronicDisclosure:!0})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}n.aborted||await m(n)})()},acceptBankTerms(n){let r=a.openHostedPage();(async()=>{s({status:`accepting-bank-terms`});let i;try{i=await hs(e,{environment:t,acceptBankTerms:!0})}catch(e){r?.dismiss(),n.aborted||s({status:`error`,message:$(e)});return}if(n.aborted){r?.dismiss();return}if(i.status===`provider_terms_required`){s({status:`accepting-provider-terms`});let e=await h({page:r,url:i.tos_url,until:e=>e.status!==`provider_terms_required`,signal:n});if(e===`aborted`)return;if(e===`blocked`){s({status:`error`});return}if(e===`closed`||e===`stalled`){await ee(`provider`,n);return}await m(n);return}r?.dismiss(),await m(n)})()},proceed(e){let t=c;t&&(async()=>{s({status:t.kind===`provider`?`accepting-provider-terms`:`verifying-identity`});let n=t.kind===`provider`?e=>e.status!==`provider_terms_required`:e=>e.status===`ready`||e.status===`rejected`||e.status===`pending`||e.status===`under_review`,r=await h({url:t.url,until:n,signal:e});if(r!==`aborted`){if(r===`blocked`){s({status:`error`});return}if(r===`closed`||r===`stalled`){await ee(t.kind,e);return}await m(e)}})()},approve(e){let t=l;if(!t)return;let n=o?.status===`approve-error`;(async()=>{s({status:`approve-prompt`,pending:!0,vaultProvider:u?.providerName??null});let r;try{r=d(e)}catch(e){s({status:`error`,message:$(e),cardId:t});return}if(r.kind===`unsupported`){s(r.reason?{status:`error`,message:r.reason,cardId:t}:{status:`error`,cardId:t});return}if(n){try{if(await r.isApproved()){e.aborted||s({status:`ready`,cardId:t});return}}catch{}if(e.aborted)return}try{if(await r.approve(),e.aborted)return;s({status:`ready`,cardId:t})}catch(n){if(e.aborted)return;console.error(`[privy] Card spending approval failed after card creation`,n),s({status:`approve-error`,cardId:t})}})()},retry(e){te(e)}}},Ks=async(e,{cardId:t,environment:n,statementPeriod:r})=>(await e.fetchPrivyRouteRaw(p,{params:{card_id:t,statement_period:r},query:{environment:n}})).blob(),qs=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),Js=e=>Number.isFinite(e)?qs.format(Math.abs(e)/100):``,Ys=({amount:e,status:t})=>e===0?`none`:t===`posted`&&e>0?`credit`:`debit`,Xs=({amount:e,status:t})=>{if(!Number.isFinite(e))return{text:``,isCredit:!1};let n=Js(e);switch(Ys({amount:e,status:t})){case`credit`:return{text:`+ ${n}`,isCredit:!0};case`debit`:return{text:`- ${n}`,isCredit:!1};case`none`:return{text:n,isCredit:!1}}},Zs={month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`},Qs=new Intl.DateTimeFormat(void 0,Zs),$s=new Intl.DateTimeFormat(void 0,{...Zs,year:`numeric`}),ec=({unixSeconds:e})=>{let t=new Date(e*1e3);return Number.isNaN(t.getTime())?``:(t.getFullYear()===new Date().getFullYear()?Qs:$s).format(t)},tc={usdc:`USDC`,pathusd:`PathUSD`,path_usd:`PathUSD`,ousd:`OUSD`,clusd:`CLUSD`},nc=e=>e?tc[e.toLowerCase()]??e:``,rc=async(e,{cardId:t,environment:n})=>{let{data:r}=await Is(e,{environment:n,limit:20});return r.find(e=>e.id===t)??null},ic=e=>`The Prepaid Debit Visa Card (the “Card”) is issued by Lead Bank pursuant to licensing by Visa U.S.A. Inc. and may be used everywhere Visa is accepted. Must be 18 or older to apply. Fees may apply. See Cardholder Agreement and ${e} website for more details.\n\nBridge Ventures LLC (“Bridge”) is not a bank. Bridge is a financial technology company and is the Program Manager responsible for managing and operating the Card on behalf of Lead Bank. ${e} is not a bank. ${e} is a financial technology company and is the Platform Provider responsible for the application, access, and management of/for the card.`,ac=async(e,{cardId:t,environment:n,nonce:r})=>{let{data:i}=await e.fetchPrivyRoute(oe,{params:{card_id:t},body:{environment:n,nonce:r}});return i.ephemeral_key_secret},oc=async(e,{appId:t,environment:n})=>{let{data:r}=await e.fetchPrivyRoute(se,{params:{app_id:t},query:{environment:n}});return{publishableKey:r.publishable_key,cardLogoUrl:r.card_logo_url??null,stripeAccount:r.stripe_account}},sc=`eip155:42431`,cc=[`eip155:11155111`,`eip155:11155420`,`eip155:80002`,`eip155:84532`,`eip155:421614`,`eip155:43113`],lc=[`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,`solana:devnet`],uc={...Object.fromEntries(cc.flatMap(e=>{let t=fa[Number.parseInt(e.replace(`eip155:`,``))];return t?[[e,{stablecoinAddress:t,spenderAddress:`0x8cc0d9e8a157b73d1172a22f5066048bda46c0e3`}]]:[]})),[sc]:{stablecoinAddress:`0x20C0000000000000000000000000000000000000`,spenderAddress:`0x1955a82a01E8c0A31371792b3045341eB8b938e2`},...Object.fromEntries(lc.map(e=>[e,{stablecoinAddress:pa.devnet,programId:`cardWArqhdV5jeRXXjUti7cHAa4mj41Nj3Apc6RPZH2`,merchantId:1n}]))},dc=(e,t)=>{let n=uc[e];if(n)return t===`ousd`&&e===sc&&`spenderAddress`in n?{stablecoinAddress:`0x20c0000000000000000000006a37DA5C996874BE`,spenderAddress:`0x249E4Ce1A8fd56d7C362c108aDf409eeDCb940aB`}:n},fc={"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":`solana:mainnet`,"solana:mainnet":`solana:mainnet`,"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":`solana:devnet`,"solana:devnet":`solana:devnet`},pc=(e,t,n)=>{let r=t??dc(e,n);if(!r)return null;let i=fc[e];return i?`programId`in r?{...r,kind:`svm`,chain:i,merchantId:BigInt(r.merchantId)}:mc(e,t):e.startsWith(`eip155:`)&&`spenderAddress`in r?{kind:`evm`,...r}:mc(e,t)},mc=(e,t)=>(t&&console.warn(`[privy] Ignoring the spendApproval option for "${e}": its shape does not match the chain (an eip155:* chain needs an EvmDevSpendApprovalTarget, a solana:* chain an SvmDevSpendApprovalTarget), or the chain is not a recognized spend-approval target.`),null),hc=e=>e.status===`pending`?`pending`:e.status===`declined`?`declined`:e.status===`expired`?`expired`:e.status===`reversed`?`reversed`:Ys(e)===`credit`?`credit`:null,gc=({step:e,onSuccess:t,onFailure:n})=>{switch(e.status){case`ready`:case`approve-error`:t({id:e.cardId});return;case`under-review`:n(Error(`Card application is under review`));return;case`rejected`:n(Error(e.reason??`Card application was rejected`));return;case`error`:if(e.cardId){t({id:e.cardId});return}n(Error(e.message??`Card sign-up failed`));return;default:n(Error(`User cancelled card sign-up`))}},_c=({exp_month:e,exp_year:t})=>{if(e===null||t===null)return!1;let n=new Date,r=n.getFullYear(),i=n.getMonth()+1;return t<r||t===r&&e<i},vc=async(e,{cardId:t,environment:n,limit:r,cursor:i})=>e.fetchPrivyRoute(ge,{params:{card_id:t},query:{environment:n,...r===void 0?{}:{limit:r},...i?{cursor:i}:{}}}),yc=async(e,{cardId:t,environment:n,reason:r})=>e.fetchPrivyRoute(Ye,{params:{card_id:t},body:{environment:n,replacement_reason:r}}),bc=({transaction:e,unknownMerchantName:t})=>({id:e.id,amount:e.amount,merchant:{name:e.merchant.name??t},status:e.status,created:e.created,currency:e.currency,dispute:e.dispute}),xc=async(e,{cardId:t,environment:n,encryptedNumber:r})=>e.fetchPrivyRoute(ut,{params:{card_id:t},body:{environment:n,pin:{encrypted_number:r}}}),Sc=async(e,{cardId:t,environment:n,status:r})=>e.fetchPrivyRoute(lt,{params:{card_id:t},body:{environment:n,status:r}}),Cc=`biconomy`,wc=`coinbase_smart_wallet`,Tc=`kernel`,Ec=`light_account`,Dc=`safe`,Oc=`thirdweb`,kc=`nexus`;var Ac=Yi;export{Wa as ALL_WALLET_CLIENT_TYPES,Cc as BICONOMY,Ds as CARD_FACE_TEXT_REFERENCE_WIDTH_PX,ks as CARD_FACE_TEXT_SIZES,ys as CARD_HEIGHT_MM,vs as CARD_WIDTH_MM,wc as COINBASE_SMART_WALLET,ms as ConnectedStandardSolanaWallet,xn as DATA_SUFFIX_PLUGIN_ID,Cs as DEBIT_IDENTIFIER_GAP_MM,ws as DEBIT_IDENTIFIER_MIN_SIZE_PT,zn as EmbeddedProviderError,Zi as InMemoryCache,Tc as KERNEL,Ec as LIGHT_ACCOUNT,Es as LIGHT_CARD_BRIGHTNESS_CUTOFF,Ls as LIST_CARDS_MAX_LIMIT,Ts as LOGO_HEIGHT_FRACTION,Xi as LocalStorage,Tn as MoonpayApiError,kc as NEXUS,T as PrivyApiError,E as PrivyClientError,Rn as PrivyConnectorError,Pn as PrivyEmbeddedWalletErrorCode,Gn as PrivyProviderRpcError,k as ProviderErrors,Dc as SAFE,Ga as SUPPORTED_CONNECTOR_TYPES,ka as SolanaClient,pa as SolanaUsdcAddressMap,Oc as THIRDWEB,fa as UsdcAddressMap,Ss as VISA_BRAND_MARK_EDGE_CLEARANCE_MM,xs as VISA_BRAND_MARK_HEIGHT_MM,bs as VISA_BRAND_MARK_WIDTH_MM,hs as acceptCardConsents,us as addSessionSigners,gs as approveSpend,_s as buildRecentMonths,La as buildSolanaOffchainMessage,zi as chainToMoonpayCurrency,Ns as chooseTempoEarnVault,z as cookies,ca as countryCodesAndNumbers,Rr as create,Ps as createCard,Gs as createCardSignUp,Cn as createDataSuffixPlugin,Dn as createErrorFormatter,Aa as createSiwsMessage,mo as crossApp,rs as cryptoDepositAccount,Ac as default,eo as delegatedActions,Do as depositAddress,Ia as deriveSolanaApplicationDomain,Ks as downloadCardStatement,Un as errorIndicatesMaxMfaRetries,On as errorIndicatesMfaCanceled,Wn as errorIndicatesMfaRateLimit,Vn as errorIndicatesMfaTimeout,Hn as errorIndicatesMfaVerificationFailed,Bn as errorIndicatesRecoveryIsNeeded,As as fitLogoSize,Ya as formatLamportsAmount,aa as formatPhoneNumber,Xs as formatSignedTransactionAmount,Ja as formatTokenAmount,ec as formatTransactionDate,Js as formatUsdAmount,Ka as formatWalletAddress,qa as formatWeiAmount,Bi as fundingMethodToMoonpayPaymentMethod,N as generateAuthorizationSignature,ha as generateWalletIdempotencyKey,Qi as getAllUserEmbeddedBitcoinWallets,si as getAllUserEmbeddedEthereumWallets,li as getAllUserEmbeddedSolanaWallets,nc as getCardAssetDisplayName,rc as getCardById,Q as getCardCustomer,ic as getCardDisclosure,ac as getCardEphemeralKey,js as getCardFaceLayout,oc as getCardsConfig,Sa as getCoinbaseOnRampUrl,fn as getCountryCallingCode,Sn as getDataSuffixPlugin,ta as getEntropyDetailsFromAccount,ea as getEntropyDetailsFromUser,Oa as getFiatOnrampProviderBrand,Ea as getFiatOnrampProviderId,ma as getIsTokenUsdc,hr as getJsonRpcEndpointFromChain,Fs as getOrCreateCardCustomer,ua as getPhoneCountryCodeAndNumber,la as getPlaceholderPhoneNumber,Na as getSolanaClusterDisplayName,ja as getSolanaRpcEndpointForCluster,Ma as getSolanaUsdcMintAddressForCluster,pc as getSpendApproval,hc as getTransactionBadge,q as getUserEmbeddedEthereumWallet,ui as getUserEmbeddedSolanaWallet,ci as getUserEmbeddedWallet,na as getUserSmartWallet,as as getWallet,cs as getWalletAction,gc as handleSignUpClose,_c as isCardExpired,R as isEmbeddedWalletAccount,Wr as isExtensionContext,Ca as isSupportedChainIdForCoinbaseOnramp,Ri as isSupportedChainIdForMoonpay,O as isUnifiedWallet,oa as lastFourDigits,vc as listCardTransactions,Is as listCards,ls as listWalletActions,Ra as parseSolanaOffchainMessage,sa as phoneNumberTypingFormatter,Z as poll,is as rawSign,Rs as readSpendAllowance,zs as readTempoEarnVault,ds as removeSessionSigners,yc as replaceCard,I as rpc,Gr as shouldWriteSessionCookies,gr as throwIfInvalidRecoveryUpgradePath,Ta as toCoinbaseAssetId,wa as toCoinbaseBlockchainFromChainId,ia as toE164,da as toObjectKeys,bc as toTransactionRow,br as toWalletApiUnsignedEthTransaction,ss as transfer,xc as updateCardPin,Sc as updateCardStatus,os as updateWallet,ra as validatePhoneNumber};
35
35
  //# sourceMappingURL=index.mjs.map