@privy-io/js-sdk-core 0.73.0 → 0.74.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +4 -4
- package/dist/cjs/index.js.map +1 -1
- package/dist/dts/index.d.mts +32 -2
- package/dist/dts/index.d.ts +32 -2
- package/dist/esm/index.mjs +4 -4
- package/dist/esm/index.mjs.map +1 -1
- package/package.json +8 -8
package/dist/esm/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AcceptTermsOnUser as e,AnalyticsEvent as t,AppConfig as n,CoinbaseOnRampInit as r,CoinbaseOnRampStatus as i,CreateDepositAddressQuote as a,CustomJWTAuthenticate as o,CustomJWTLink as s,FarcasterAuthenticate as c,FarcasterInit as l,FarcasterLink as u,FarcasterStatus as ee,FarcasterUnlink as te,FarcasterV2Authenticate as d,FarcasterV2Init as f,GetCrossAppConnections as p,GetDepositAddressOrder as ne,GetDepositConfig as re,GetNextDepositAddressOrder as ie,GetSmartWalletConfig as ae,GuestAuthenticate as oe,Logout as se,MfaPasskeyInit as ce,MfaPasswordlessSmsInit as le,MoonpayOnRampSign as ue,OAuthAuthenticate as de,OAuthInit as fe,OAuthLink as pe,OAuthUnlink as me,PasskeyAuthenticate as he,PasskeyAuthenticateInit as ge,PasskeyLink as _e,PasskeyLinkInit as ve,PasskeyRegister as ye,PasskeyRegisterInit as be,PasswordlessAuthenticate as xe,PasswordlessInit as Se,PasswordlessLink as Ce,PasswordlessSmsAuthenticate as we,PasswordlessSmsInit as Te,PasswordlessSmsLink as Ee,PasswordlessSmsUnlink as De,PasswordlessSmsUpdate as Oe,PasswordlessUnlink as ke,PasswordlessUpdate as Ae,RecoveryConfigurationICloud as je,RecoveryKeyMaterial as Me,RecoveryOAuthAuthenticate as Ne,RecoveryOAuthInit as Pe,RecoveryOAuthInitICloud as Fe,RefreshSession as Ie,RefreshUser as Le,SiweAuthenticate as Re,SiweInit as ze,SiweLink as Be,SiweLinkSmartWallet as Ve,SiweUnlink as He,SiwsAuthenticate as Ue,SiwsInit as We,SiwsLink as Ge,SiwsUnlink as Ke,TelegramAuthenticate as qe,TelegramLink as Je,TelegramUnlink as Ye,WalletCreate as Xe,WalletGet as Ze,WalletRawSign as Qe,WalletRpc as $e,WalletUpdate as et,WalletsRevoke as tt,getPathWithParams as nt}from"@privy-io/routes";import*as rt from"jose";import{base64url as it}from"jose";import{DEFAULT_SUPPORTED_CHAINS as at,arbitrum as m,arbitrumSepolia as ot,avalanche as h,avalancheFuji as st,base as g,baseSepolia as ct,celo as lt,dedupeSupportedChains as ut,mainnet as _,monadMainnet as v,optimism as y,optimismSepolia as dt,polygon as b,polygonAmoy as ft,sepolia as pt}from"@privy-io/chains";import mt from"eventemitter3";import{createPublicClient as ht,formatEther as gt,formatUnits as _t,http as vt,toHex as yt}from"viem";import{STRING_TO_NUMBER_TXN_TYPE as bt,TEMPO_TXN_TYPE_NUMBER as xt,isTempoTransactionRequest as x,normalizeViemPreparedTempoTransaction as St,toViemTempoTransactionSerializable as Ct,toViemTransactionSerializable as wt}from"@privy-io/ethereum";import Tt from"canonicalize";import{encoding as S}from"@privy-io/encoding";import{tempo as Et,tempoModerato as Dt}from"viem/chains";import{PrivyErrorCode as Ot}from"@privy-io/api-base";import kt from"js-cookie";import At from"fetch-retry";import jt from"libphonenumber-js/examples.mobile.json";import{AsYouType as Mt,getCountries as Nt,getCountryCallingCode as Pt,getExampleNumber as Ft,isPossiblePhoneNumber as It,parsePhoneNumberFromString as Lt}from"libphonenumber-js/min";export*from"@privy-io/chains";var Rt=Object.defineProperty,C=(e,t)=>{let n={};for(var r in e)Rt(n,r,{get:e[r],enumerable:!0});return t||Rt(n,Symbol.toStringTag,{value:`Module`}),n};function zt(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}var Bt=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(ae,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},w=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=rt.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}},Vt=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=e.providerAccessTokenStorageKey(t);await this._storage.put(i,r)}async getProviderAccessToken(t){let n=e.providerAccessTokenStorageKey(t),r=await this._storage.get(n);if(typeof r!=`string`)return null;try{if(new w(r).isExpired())throw Error(`JWT is expired`);return r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(p,{params:{app_id:this._privyInternal.appId}})}},Ht=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(tt,{})}},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}},Ut=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 Wt(e){return e instanceof T||e instanceof E?e.code:`unknown_error`}const Gt=e=>t=>e[Wt(t)]??e.default;function Kt(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}const D=e=>!!e.id&&e.recovery_method===`privy-v2`,qt=[`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 Jt=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 Yt=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}]`:``}`}},Xt=class extends Yt{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},Zt=class extends Error{type;constructor(e,t){super(t),this.type=e}},Qt=class extends Yt{type=`connector_error`;constructor(e,t,n){super(e,t,n)}},$t=class extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}};const O={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 k(e){let t=e.type;return typeof t==`string`&&qt.includes(t)}function A(e){return k(e)&&e.type===`wallet_not_on_device`}function en(e){return k(e)&&e.type===`mfa_timeout`}function tn(e){return k(e)&&e.type===`missing_or_invalid_mfa`}function nn(e){return k(e)&&e.type===`mfa_verification_max_attempts_reached`}function rn(e){return k(e)&&e.message.includes(`code 429`)}var an=class extends Xt{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(O).find(e=>e.eipCode===t.code);this.details=n||O.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=O.E32002_CONNECTION_ALREADY_PENDING:this.details=O.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=O.E32002_WALLET_LOCKED))}};const j=e=>/^0x[0-9a-fA-F]*$/.test(e),on=e=>Buffer.from(e,`utf8`),M=e=>`0x${e.toString(`hex`)}`;async function N(e,t){let n;if(t instanceof Uint8Array)n=S.base64.fromBytes(t);else{let e=Tt(t);if(e===void 0)throw new E({error:`Failed to prepare the payload for signing`,code:`invalid_input`});n=S.base64.fromBytes(S.utf8.toBytes(e))}let{signature:r}=await e({message:n});return{signature:r}}const P=`privy-request-expiry`,sn=1800*1e3;async function F(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath($e,{params:{wallet_id:n}}),o=String(Date.now()+sn),{signature:s}=await N(t,{version:1,url:a,method:$e.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($e,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[P]:o,...r??{}}})}function cn(e){return x(e)?un(e):ln(e)}function ln(e){return{from:e.from,to:e.to??void 0,nonce:I(e.nonce),chain_id:I(e.chainId),data:mn(e.data),value:I(e.value),type:gn(e.type),gas_limit:I(e.gasLimit??e.gas),gas_price:I(e.gasPrice),max_fee_per_gas:I(e.maxFeePerGas),max_priority_fee_per_gas:I(e.maxPriorityFeePerGas)}}function un(e){return{type:xt,from:e.from,chain_id:I(e.chainId),nonce:I(e.nonce),nonce_key:I(e.nonceKey),gas_limit:I(e.gasLimit),max_fee_per_gas:I(e.maxFeePerGas),max_priority_fee_per_gas:I(e.maxPriorityFeePerGas),fee_token:e.feeToken,valid_after:I(e.validAfter),valid_before:I(e.validBefore),fee_payer_signature:fn(e.feePayerSignature),access_list:dn(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:I(e.value)}))}}function dn(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 fn(e){if(!e)return;let t=pn(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 pn(e){if(e.yParity!==void 0)return e.yParity;if(e.v!==void 0)return Number(e.v)-27}function mn(e){if(e!==void 0)return typeof e==`string`?j(e)?e:M(on(e)):M(Buffer.from(Uint8Array.from(e)))}const hn=[0,1,2,4];function gn(e){if(e==null)return;let t=Number(e);if(!_n(t))throw Error(`Invalid transaction type: expected ${hn.join(`, `)} as a number or hex string, got "${e}".`);return t}function _n(e){return hn.includes(e)}function I(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(j(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 vn(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 yn({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return bn({context:e,account:t,rpcRequest:n.request});case`solana`:return xn({context:e,account:t,rpcRequest:n.request})}}async function bn({context:e,account:t,rpcRequest:n}){switch(n.method){case`personal_sign`:{let[r]=n.params,i=await F(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 F(e,e.signRequest,{chain_type:`ethereum`,method:`eth_signTransaction`,wallet_id:t.id,params:{transaction:cn(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 F(e,e.signRequest,{chain_type:`ethereum`,method:n.method,wallet_id:t.id,params:{typed_data:vn(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 F(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:j(r)?r:M(on(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 F(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:j(r)?r:M(on(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 xn({context:e,account:t,rpcRequest:n}){switch(n.method){case`signMessage`:{let{message:r}=n.params,i=await F(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}}}}const Sn=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new Qt(`Unsupported chainId ${e}`,4901);let o=wn(a,n,r.appId);if(i===Et.id||i===Dt.id){let e=i===Et.id?Et:Dt;return ht({transport:vt(o),chain:e})}return ht({transport:vt(o),chain:a})};function Cn(e){return e===Et.id||e===Dt.id}const wn=(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 Qt(`No RPC url found for ${r}`);return a};function Tn({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 En=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var Dn=class extends mt{_walletProxy;_privyInternal;_account;_entropyId;_entropyIdVerifier;_chainId;_chains;_onNeedsRecovery;_client;_appApi;constructor({walletProxy:e,privyInternal:t,account:n,entropyId:r,entropyIdVerifier:i,chains:a,onNeedsRecovery:o,chainId:s=a[0].id,appApi:c}){super(),this._walletProxy=e,this._privyInternal=t,this._account=n,this._entropyId=r,this._entropyIdVerifier=i,this._chainId=s,this._chains=a,this._onNeedsRecovery=o,this._client=Sn(s,a,{rpcUrls:[]},{appId:c.appId}),this._appApi=c}async request(e){if(En.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=e.params?.[0];return this.handleSignTransaction(t)}case`eth_sendTransaction`:{let t=e.params?.[0];return this.handleSendTransaction(t)}case`eth_populateTransactionRequest`:{let t=e.params?.[0];return this.handlePopulateTransaction(t)}default:return this.handleJsonRpc(e)}}ensureChainId(e){let t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),t}internalSwitchEthereumChain(e){!e||Number(e)===this._chainId||(this._chainId=Number(e),this._client=Sn(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit(`chainChanged`,e))}async handlePopulateTransaction(e){let t=this.ensureChainId(e);if(x(t)){let e=Ct(t),n=St(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:xt}}let n=wt(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:bt[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 x(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=this.ensureChainId(t);if(x(n)){let e=Ct(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=wt(n);return await this._client.estimateGas({account:n.from??this._account.address,...r})}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new $t(`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 $t(`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`);this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address});let n=this._account;if(D(n)){let{data:r}=await yn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:e})=>this._walletProxy.signWithUserSigner({accessToken:t,message:e})},account:n,rpcRequest:{chainType:`ethereum`,request:e}});return r}try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t})}catch(e){let n=A(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}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(!Cn(this._chainId))throw new $t(`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] }`}};function On(e){return`version`in e}function kn(e,t){let n=(On(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 An=class{_proxy;_privyInternal;_app;_entropyId;_entropyIdVerifier;_account;_onNeedsRecovery;constructor({proxy:e,privyInternal:t,account:n,entropyId:r,entropyIdVerifier:i,onNeedsRecovery:a,app:o}){this._proxy=e,this._privyInternal=t,this._account=n,this._entropyId=r,this._entropyIdVerifier=i,this._onNeedsRecovery=a,this._app=o}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 connectAndRecover(e){if(this._account.recovery_method!==`privy-v2`)try{await this._proxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:e})}catch(t){let n=A(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){let n=this._account;if(D(n)){let{data:r}=await yn({context:{app:this._app,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:e})=>this._proxy.signWithUserSigner({accessToken:t,message:e})},account:n,rpcRequest:{chainType:`solana`,request:e}});return{signature:r}}else 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 handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),await this.connectAndRecover(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`);this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),await this.connectAndRecover(t);let{transaction:n,connection:r,options:i}=e.params,a=kn(n,this._account.address),o=On(n)?Buffer.from(n.message.serialize()):n.serializeMessage(),{signature:s}=await this.signMessageRpc({method:`signMessage`,params:{message:o.toString(`base64`)}},t);return n.addSignature(a,Buffer.from(s,`base64`)),{signature:await r.sendRawTransaction(n.serialize(),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`);this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),await this.connectAndRecover(t);let{transaction:n}=e.params,r=kn(n,this._account.address),i=On(n)?Buffer.from(n.message.serialize()):n.serializeMessage(),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:i.toString(`base64`)}},t);return n.addSignature(r,Buffer.from(a,`base64`)),{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.wallet_index,error:n}),new E({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},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(D(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 this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),(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}`)}}};async function Nn(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new Zt(`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 Zt(`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 Zt(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function Pn(e){return e.error!==void 0}const Fn=(function(e){return()=>`id-${e++}`})(0),In=(e,t)=>typeof t==`bigint`?t.toString():t,Ln=(e,t)=>`${e}${JSON.stringify(t,In)}`,L=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)}},Rn=new Mn;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 L(Nn(n=>L(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,Rn.flush(Error(`Embedded wallet WebView was reloaded`)),this.cache.clear(),this._embeddedWalletMessagePoster.reload()}onBackground(){this.ready=!1}ping(e=15e3){return L(this.invoke(`privy:iframe:ready`,{}),{msg:`Ping reached timeout`,ms:e})}create(e){return L(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 L(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`}):L(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 L(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 L(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 L(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=Rn.dequeue(e.event,e.id);if(t)return Pn(e)?t.reject(new Zt(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=Ln(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=Fn();Rn.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}};async function Bn(e,{request:t,headers:n}){return await e.fetchPrivyRoute(Xe,{body:t,headers:n})}async function Vn({context:e,chainType:t,idempotencyKey:n}){return{wallet:await Bn(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}var Hn=class{_privyInternal;_proxy;_chains=Array.from(at);_mfa;_mfaPromises;_appApi;constructor(e,t,n,r,i,a){if(this._privyInternal=e,t&&(this._proxy=new zn(t,i),r.setProxy(this._proxy)),n){let e=ut(n);this._chains=e}this._mfa=r,this._mfaPromises=i,this._appApi=a}setMessagePoster(e){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._proxy)throw Error(`Embedded wallet proxy not initialized`);if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await Vn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:e.chainType});else{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 D(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._proxy)throw Error(`Embedded wallet proxy not initialized`);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 Vn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`ethereum`,idempotencyKey:c})}else{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._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await Vn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`solana`,idempotencyKey:e?.idempotencyKey});else{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(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return D(e)||await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new Dn({account:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,appApi:this._appApi})}async getEthereumProvider({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o,onNeedsRecovery:s}){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 D(e)||(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new Dn({account:e,entropyId:t,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,onNeedsRecovery:s,appApi:this._appApi})}async getSolanaProvider(e,t,n,r,i,a,o){if(!this._proxy)throw new E({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return D(e)||(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new An({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:o,app:this._appApi})}async setRecovery(e){let{wallet:t,...n}=e;if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(D(t))throw new E({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});Tn({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 Dn({account:t,entropyId:t.address,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,appApi:this._appApi}):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(A(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}}},Un=class extends mt{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const Wn=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let Gn=!1;const Kn=()=>{if(Gn)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;Gn=typeof t==`string`&&t.length>0||typeof n==`string`&&Wn.includes(n)}catch{Gn=!0}return Gn},R={get(e){return kt.get(e)},set(e,t,n){Kn()||kt.set(e,t,n)},remove(e){kt.remove(e)}},qn=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!Kn(),z=`privy:active-user`,Jn=`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`,Yn=e=>e?`privy-${e}-token`:`privy-token`,Xn=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,Zn=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}))))),Qn=[`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 $n=class extends mt{static events=Qn;_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 qn({useServerCookies:this._isUsingServerCookies,cookieWriteBehavior:this._cookieWriteBehavior})}writeCookie(e,t,n){this.shouldWriteCookies()&&R.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 w(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 w(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=R.get(W(e));if(t!==void 0&&t.length>0)return!0;let n=R.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=w.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(z)];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),R.remove(Yn(null)),R.remove(Xn(null)),R.remove(Zn(null)),R.remove(W(null)),t&&(R.remove(Yn(t)),R.remove(Xn(t)),R.remove(Zn(t)),R.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=Yn(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=w.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),R.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=Xn(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),R.remove(r),R.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=w.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=Zn(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=w.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),R.remove(r),e!==null&&this.emit(`identity_token_cleared`,{reason:`set_with_non_string_value`})}}async getOrCreateGuestCredential(){let e=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&typeof e==`string`)return e;let t=it.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,t),t}async getActiveUserId(){let e=await this._storage.get(z);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(z,e)}async getSavedUserIds(){let e=await this._storage.get(Jn);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(Jn,JSON.stringify(t)):await this._storage.del(Jn),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(z,e)}};const er=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function tr(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 K=()=>void 0,q={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},nr=({level:e,logger:t})=>({get level(){return e},error:q[e]>=q.ERROR?t.error:K,warn:q[e]>=q.WARN?t.warn:K,info:q[e]>=q.INFO?t.info:K,debug:q[e]>=q.DEBUG?t.debug:K});function J(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const rr=e=>3**e*500,ir=[408,409,425,500,502,503,504];function ar(e){return async(t,n)=>{let r=t instanceof Request?t:new Request(t,n),i,a=!1,o;for(let t=0;t<=3;t++){let s=new Headers(n?.headers??r.headers);s.set(`privy-retry-attempt`,String(t));try{let t=await e(r.clone(),{...n,headers:s});if(!ir.includes(t.status))return t;o=t,a=!1}catch(e){i===void 0&&(i=e),a=!0}t<3&&await J(rr(t))}if(a)throw i;return o}}const or=`privy:caid`;var sr=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.73.0`;_fetch;nativeAppIdentifier;_crypto;isMultiUserModeEnabled;_cache=new Map;constructor(e){this.logger=nr({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 $n({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=ar(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(`react-auth:`)||this.createAnalyticsEvent(`sdk_initialize`,{})}getPath(e,{params:t,query:n}){return`${this.baseUrl}${nt(e.path,t)}${tr(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,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),l=await c.json();if(c.status>299)throw new T({...l,status:c.status});return l}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:er(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:er(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(n,{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(or);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(or,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(or)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,n){try{await this.fetch(t,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:n},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:Ot.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});try{this.logger.debug(`[privy:refresh] fetching: ${Ie.path}`);let n=await this.fetch(Ie,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),r=n.session_update_action;return this.logger.debug(`[privy:refresh] response: ${r}`),r===`set`&&(await this.session.updateWithTokensResponse(n),this.logger.debug(`[privy:refresh] tokens stored`)),r===`clear`&&(await this.session.destroyLocalState(),this.logger.debug(`[privy:refresh] tokens cleared`),!t&&this.callbacks?.setUser?.(null)),r===`ignore`&&(n.token&&(await this.session.storeCustomerAccessToken(n.token),this.logger.debug(`[privy:refresh] token stored (CAT)`)),n.privy_access_token&&(await this.session.storePrivyAccessToken(n.privy_access_token),this.logger.debug(`[privy:refresh] token stored (PAT)`)),n.identity_token&&(this.logger.debug(`[privy:refresh] token stored (IDT)`),await this.session.storeIdentityToken(n.identity_token))),this.logger.debug(`[privy:refresh] returning response`),!t&&this.callbacks?.setUser?.(n.user),n}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??`unknown error`}`),e instanceof T&&e.code===Ot.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),!t&&this.callbacks?.setUser?.(null)),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}}},cr=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(){return{user:await this._privyInternal.fetch(e,{})}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(Le,{});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 Y=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`,lr=e=>e?e.linked_accounts.filter(Y).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],X=e=>lr(e).find(e=>e.wallet_index===0)??null,ur=X,dr=e=>e?e.linked_accounts.filter(Y).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],fr=e=>dr(e).find(e=>e.wallet_index===0)??null,pr=(e,t)=>t===`off`||lr(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,mr=(e,t)=>t===`off`||dr(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,hr=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),Z=async(e,t,n)=>{let r=pr(t.user,n?.ethereum?.createOnLogin??`off`),i=mr(t.user,n?.solana?.createOnLogin??`off`);if(r&&i){let n=await e.create({recoveryMethod:`privy`,skipCallbacks:!0}),r=await e.createSolana({ethereumAccount:X(n.user)??void 0});return hr(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:fr(t.user)??void 0});return hr(n,t)}if(i){let n=await e.createSolana({ethereumAccount:X(t.user)??void 0});return hr(n,t)}return t};var gr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async syncWithToken(e,t,n){let r=await this._privyInternal.fetchForLogin(o,{body:{token:e,mode:n}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await Z(this._embedded,r,t?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithToken(e){await this._privyInternal.fetch(s,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},_r=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Se,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(xe,{body:{email:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Ce,{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(Ae,{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(ke,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},vr=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(l,{body:{relying_party:e,redirect_url:t,token:n}})}async getFarcasterStatus({channel_token:e}){return await this._privyInternal.fetch(ee,{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(c,{body:{channel_token:e,message:t,signature:n,fid:r,mode:i}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await Z(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(u,{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(te,{body:{fid:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},yr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(f,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(d,{body:{message:e,signature:t,fid:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}},br=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(oe,{body:{guest_credential:t}});await this._privyInternal.session.updateWithTokensResponse(n);let r=await Z(this._embedded,n,e?.embedded);return this._privyInternal.callbacks?.setUser?.(r.user),r}};const Q=`privy:state_code`,$=`privy:code_verifier`;async function xr(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function Sr(e){return crypto.getRandomValues(new Uint8Array(e))}function Cr(){return it.encode(Sr(36))}function wr(){return Cr()}async function Tr({codeVerifier:e,method:t=`S256`,digest:n}){if(t==`S256`){let t=await xr(e,n);return it.encode(t)}else return e}var Er=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=Cr(),r=wr(),i=await Tr({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put($,n),this._storage.put(Q,r)]),this._privyInternal.fetchForLogin(fe,{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($),this._storage.get(Q)]);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(de,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let l=await Z(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del($),this._storage.del(Q)]),this._privyInternal.callbacks?.setUser?.(l.user),l}async linkWithCode(e,t,n,r){let[i,a]=await Promise.all([this._storage.get($),this._storage.get(Q)]);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(pe,{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($),this._storage.del(Q)]),{user:s.user,identity_token:s.identity_token}}async unlink(e,t){await this._privyInternal.fetch(me,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},Dr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(ve,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(ge,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(be,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(he,{body:{relying_party:n,challenge:t,authenticator_response:this._transformAuthenticationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async signupWithPasskey(e,t,n){let r=await this._privyInternal.fetchForLogin(ye,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await Z(this._embedded,r,n?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithPasskey(e,t){await this._privyInternal.fetch(_e,{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}}}},Or=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Te,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(we,{body:{phoneNumber:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Ee,{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(Oe,{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(De,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},kr=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(He,{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(Be,{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(Re,{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 Z(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(ze,{body:{address:e.address}}),i=Ar({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 Ar(e){return`${e.domain} wants you to sign in with your Ethereum account:
|
|
1
|
+
import{AcceptTermsOnUser as e,AnalyticsEvent as t,AppConfig as n,CoinbaseOnRampInit as r,CoinbaseOnRampStatus as i,CreateDepositAddressQuote as a,CustomJWTAuthenticate as o,CustomJWTLink as s,FarcasterAuthenticate as c,FarcasterInit as l,FarcasterLink as u,FarcasterStatus as ee,FarcasterUnlink as te,FarcasterV2Authenticate as d,FarcasterV2Init as f,GetCrossAppConnections as ne,GetDepositAddressOrder as re,GetDepositConfig as ie,GetNextDepositAddressOrder as ae,GetSmartWalletConfig as oe,GuestAuthenticate as se,Logout as ce,MfaPasskeyInit as le,MfaPasswordlessSmsInit as ue,MoonpayOnRampSign as de,OAuthAuthenticate as fe,OAuthInit as pe,OAuthLink as me,OAuthUnlink as he,PasskeyAuthenticate as ge,PasskeyAuthenticateInit as _e,PasskeyLink as ve,PasskeyLinkInit as ye,PasskeyRegister as be,PasskeyRegisterInit as xe,PasswordlessAuthenticate as Se,PasswordlessInit as Ce,PasswordlessLink as we,PasswordlessSmsAuthenticate as Te,PasswordlessSmsInit as Ee,PasswordlessSmsLink as De,PasswordlessSmsUnlink as Oe,PasswordlessSmsUpdate as ke,PasswordlessUnlink as Ae,PasswordlessUpdate as je,RecoveryConfigurationICloud as Me,RecoveryKeyMaterial as Ne,RecoveryOAuthAuthenticate as Pe,RecoveryOAuthInit as Fe,RecoveryOAuthInitICloud as Ie,RefreshSession as Le,RefreshUser as Re,SiweAuthenticate as ze,SiweInit as Be,SiweLink as Ve,SiweLinkSmartWallet as He,SiweUnlink as Ue,SiwsAuthenticate as We,SiwsInit as Ge,SiwsLink as Ke,SiwsUnlink as qe,TelegramAuthenticate as Je,TelegramLink as Ye,TelegramUnlink as Xe,WalletCreate as Ze,WalletGet as Qe,WalletRawSign as $e,WalletRpc as et,WalletUpdate as tt,WalletsRevoke as nt,getPathWithParams as rt}from"@privy-io/routes";import*as it from"jose";import{base64url as at}from"jose";import{DEFAULT_SUPPORTED_CHAINS as ot,arbitrum as p,arbitrumSepolia as st,avalanche as m,avalancheFuji as ct,base as h,baseSepolia as lt,celo as ut,dedupeSupportedChains as dt,mainnet as g,monadMainnet as _,optimism as v,optimismSepolia as ft,polygon as y,polygonAmoy as pt,sepolia as mt}from"@privy-io/chains";import ht from"eventemitter3";import{createPublicClient as gt,formatEther as _t,formatUnits as vt,http as yt,toHex as bt}from"viem";import{STRING_TO_NUMBER_TXN_TYPE as xt,TEMPO_TXN_TYPE_NUMBER as St,isTempoTransactionRequest as b,normalizeViemPreparedTempoTransaction as Ct,toViemTempoTransactionSerializable as wt,toViemTransactionSerializable as Tt}from"@privy-io/ethereum";import Et from"canonicalize";import{encoding as x}from"@privy-io/encoding";import{tempo as Dt,tempoModerato as Ot}from"viem/chains";import{PrivyErrorCode as kt}from"@privy-io/api-base";import At from"js-cookie";import jt from"fetch-retry";import Mt from"libphonenumber-js/examples.mobile.json";import{AsYouType as Nt,getCountries as Pt,getCountryCallingCode as Ft,getExampleNumber as It,isPossiblePhoneNumber as Lt,parsePhoneNumberFromString as Rt}from"libphonenumber-js/min";export*from"@privy-io/chains";var zt=Object.defineProperty,S=(e,t)=>{let n={};for(var r in e)zt(n,r,{get:e[r],enumerable:!0});return t||zt(n,Symbol.toStringTag,{value:`Module`}),n};function Bt(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}const C=e=>/^0x[0-9a-fA-F]*$/.test(e),Vt=e=>Buffer.from(e,`utf8`),w=e=>`0x${e.toString(`hex`)}`,Ht=Symbol(`data-suffix-plugin`);function Ut(e=[]){return e.find(e=>e.id===Ht)}function Wt(e){let t=e.startsWith(`0x`)?e:`0x${e}`;if(!C(t))throw Error(`[Privy] dataSuffix: Invalid suffix "${e}" is not valid hex`);let n=t.slice(2);return{id:Ht,suffix:t,appendDataSuffix:({data:e})=>!e||e===`0x`?t:`${e}${n}`}}var Gt=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(oe,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},T=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=it.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}},Kt=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=e.providerAccessTokenStorageKey(t);await this._storage.put(i,r)}async getProviderAccessToken(t){let n=e.providerAccessTokenStorageKey(t),r=await this._storage.get(n);if(typeof r!=`string`)return null;try{if(new T(r).isExpired())throw Error(`JWT is expired`);return r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(ne,{params:{app_id:this._privyInternal.appId}})}},qt=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(nt,{})}},E=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}},D=class extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}},Jt=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 Yt(e){return e instanceof E||e instanceof D?e.code:`unknown_error`}const Xt=e=>t=>e[Yt(t)]??e.default;function Zt(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}const O=e=>!!e.id&&e.recovery_method===`privy-v2`,Qt=[`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 $t=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 en=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}]`:``}`}},tn=class extends en{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},k=class extends Error{type;constructor(e,t){super(t),this.type=e}},nn=class extends en{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 A={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 j(e){let t=e.type;return typeof t==`string`&&Qt.includes(t)}function M(e){return j(e)&&e.type===`wallet_not_on_device`}function an(e){return j(e)&&e.type===`mfa_timeout`}function on(e){return j(e)&&e.type===`missing_or_invalid_mfa`}function sn(e){return j(e)&&e.type===`mfa_verification_max_attempts_reached`}function cn(e){return j(e)&&e.message.includes(`code 429`)}var ln=class extends tn{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(A).find(e=>e.eipCode===t.code);this.details=n||A.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=A.E32002_CONNECTION_ALREADY_PENDING:this.details=A.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=A.E32002_WALLET_LOCKED))}};async function N(e,t){let n;if(t instanceof Uint8Array)n=x.base64.fromBytes(t);else{let e=Et(t);if(e===void 0)throw new D({error:`Failed to prepare the payload for signing`,code:`invalid_input`});n=x.base64.fromBytes(x.utf8.toBytes(e))}let{signature:r}=await e({message:n});return{signature:r}}const P=`privy-request-expiry`,un=1800*1e3;async function F(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath(et,{params:{wallet_id:n}}),o=String(Date.now()+un),{signature:s}=await N(t,{version:1,url:a,method:et.method,headers:{"privy-app-id":e.app.appId,[P]:o},body:{...i}});if(Date.now()>Number(o))throw new D({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(et,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[P]:o,...r??{}}})}function dn(e){return b(e)?pn(e):fn(e)}function fn(e){return{from:e.from,to:e.to??void 0,nonce:I(e.nonce),chain_id:I(e.chainId),data:_n(e.data),value:I(e.value),type:yn(e.type),gas_limit:I(e.gasLimit??e.gas),gas_price:I(e.gasPrice),max_fee_per_gas:I(e.maxFeePerGas),max_priority_fee_per_gas:I(e.maxPriorityFeePerGas)}}function pn(e){return{type:St,from:e.from,chain_id:I(e.chainId),nonce:I(e.nonce),nonce_key:I(e.nonceKey),gas_limit:I(e.gasLimit),max_fee_per_gas:I(e.maxFeePerGas),max_priority_fee_per_gas:I(e.maxPriorityFeePerGas),fee_token:e.feeToken,valid_after:I(e.validAfter),valid_before:I(e.validBefore),fee_payer_signature:hn(e.feePayerSignature),access_list:mn(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:I(e.value)}))}}function mn(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 hn(e){if(!e)return;let t=gn(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 gn(e){if(e.yParity!==void 0)return e.yParity;if(e.v!==void 0)return Number(e.v)-27}function _n(e){if(e!==void 0)return typeof e==`string`?C(e)?e:w(Vt(e)):w(Buffer.from(Uint8Array.from(e)))}const vn=[0,1,2,4];function yn(e){if(e==null)return;let t=Number(e);if(!bn(t))throw Error(`Invalid transaction type: expected ${vn.join(`, `)} as a number or hex string, got "${e}".`);return t}function bn(e){return vn.includes(e)}function I(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(C(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 xn(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 Sn({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return Cn({context:e,account:t,rpcRequest:n.request});case`solana`:return wn({context:e,account:t,rpcRequest:n.request})}}async function Cn({context:e,account:t,rpcRequest:n}){switch(n.method){case`personal_sign`:{let[r]=n.params,i=await F(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 F(e,e.signRequest,{chain_type:`ethereum`,method:`eth_signTransaction`,wallet_id:t.id,params:{transaction:dn(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 F(e,e.signRequest,{chain_type:`ethereum`,method:n.method,wallet_id:t.id,params:{typed_data:xn(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 F(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:C(r)?r:w(Vt(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 F(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:C(r)?r:w(Vt(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 wn({context:e,account:t,rpcRequest:n}){switch(n.method){case`signMessage`:{let{message:r}=n.params,i=await F(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}}}}const Tn=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new nn(`Unsupported chainId ${e}`,4901);let o=Dn(a,n,r.appId);if(i===Dt.id||i===Ot.id){let e=i===Dt.id?Dt:Ot;return gt({transport:yt(o),chain:e})}return gt({transport:yt(o),chain:a})};function En(e){return e===Dt.id||e===Ot.id}const Dn=(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 nn(`No RPC url found for ${r}`);return a};function On({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 kn=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var An=class extends ht{_walletProxy;_privyInternal;_account;_entropyId;_entropyIdVerifier;_chainId;_chains;_onNeedsRecovery;_client;_appApi;_dataSuffixPlugin;constructor({walletProxy:e,privyInternal:t,account:n,entropyId:r,entropyIdVerifier:i,chains:a,onNeedsRecovery:o,chainId:s=a[0].id,appApi:c,dataSuffixPlugin:l}){super(),this._walletProxy=e,this._privyInternal=t,this._account=n,this._entropyId=r,this._entropyIdVerifier=i,this._chainId=s,this._chains=a,this._onNeedsRecovery=o,this._client=Tn(s,a,{rpcUrls:[]},{appId:c.appId}),this._appApi=c,this._dataSuffixPlugin=l}async request(e){if(kn.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||b(e))return e;let t=typeof e.data==`string`?e.data:`0x`;return{...e,data:this._dataSuffixPlugin.appendDataSuffix({data:t})}}ensureChainId(e){let t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),t}internalSwitchEthereumChain(e){!e||Number(e)===this._chainId||(this._chainId=Number(e),this._client=Tn(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit(`chainChanged`,e))}async handlePopulateTransaction(e){let t=this.ensureChainId(e);if(b(t)){let e=wt(t),n=Ct(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:St}}let n=Tt(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:xt[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]=bt(n))}return b(t)&&(t.calls=t.calls.map(e=>({...e,value:typeof e.value==`bigint`?bt(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=this.ensureChainId(t);if(b(n)){let e=wt(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=Tt(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`);this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address});let n=this._account;if(O(n)){let{data:r}=await Sn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:e})=>this._walletProxy.signWithUserSigner({accessToken:t,message:e})},account:n,rpcRequest:{chainType:`ethereum`,request:e}});return r}try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t})}catch(e){let n=M(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 D({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}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 D({code:`embedded_wallet_request_error`,error:n})}}async handleJsonRpc(e){return this._client.request(e)}requireTempoClient(){if(!En(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] }`}};function jn(e){return`version`in e}function Mn(e,t){let n=(jn(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 Nn=class{_proxy;_privyInternal;_app;_entropyId;_entropyIdVerifier;_account;_onNeedsRecovery;constructor({proxy:e,privyInternal:t,account:n,entropyId:r,entropyIdVerifier:i,onNeedsRecovery:a,app:o}){this._proxy=e,this._privyInternal=t,this._account=n,this._entropyId=r,this._entropyIdVerifier=i,this._onNeedsRecovery=a,this._app=o}async request(e){if(!await this._privyInternal.getAccessTokenInternal())throw new D({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 connectAndRecover(e){if(this._account.recovery_method!==`privy-v2`)try{await this._proxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:e})}catch(t){let n=M(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 D({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){let n=this._account;if(O(n)){let{data:r}=await Sn({context:{app:this._app,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:e})=>this._proxy.signWithUserSigner({accessToken:t,message:e})},account:n,rpcRequest:{chainType:`solana`,request:e}});return{signature:r}}else 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 handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),await this.connectAndRecover(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 D({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`);this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),await this.connectAndRecover(t);let{transaction:n,connection:r,options:i}=e.params,a=Mn(n,this._account.address),o=jn(n)?Buffer.from(n.message.serialize()):n.serializeMessage(),{signature:s}=await this.signMessageRpc({method:`signMessage`,params:{message:o.toString(`base64`)}},t);return n.addSignature(a,Buffer.from(s,`base64`)),{signature:await r.sendRawTransaction(n.serialize(),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 D({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`);this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),await this.connectAndRecover(t);let{transaction:n}=e.params,r=Mn(n,this._account.address),i=jn(n)?Buffer.from(n.message.serialize()):n.serializeMessage(),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:i.toString(`base64`)}},t);return n.addSignature(r,Buffer.from(a,`base64`)),{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.wallet_index,error:n}),new D({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},Pn=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 D({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 D({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 this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_started`,{method:e.method,address:this._account.address}),(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 D({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedBitcoinProvider { address: '${this._account.address}', request: [Function] }`}},Fn=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}`)}}};async function In(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new k(`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 k(`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 k(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function Ln(e){return e.error!==void 0}const Rn=(function(e){return()=>`id-${e++}`})(0),zn=(e,t)=>typeof t==`bigint`?t.toString():t,Bn=(e,t)=>`${e}${JSON.stringify(t,zn)}`,L=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)}},Vn=new Fn;var Hn=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 L(In(n=>L(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,Vn.flush(Error(`Embedded wallet WebView was reloaded`)),this.cache.clear(),this._embeddedWalletMessagePoster.reload()}onBackground(){this.ready=!1}ping(e=15e3){return L(this.invoke(`privy:iframe:ready`,{}),{msg:`Ping reached timeout`,ms:e})}create(e){return L(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 L(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`}):L(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 L(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 L(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 L(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=Vn.dequeue(e.event,e.id);if(t)return Ln(e)?t.reject(new k(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=Bn(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=Rn();Vn.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}};async function Un(e,{request:t,headers:n}){return await e.fetchPrivyRoute(Ze,{body:t,headers:n})}async function Wn({context:e,chainType:t,idempotencyKey:n}){return{wallet:await Un(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}var Gn=class{_privyInternal;_proxy;_chains=Array.from(ot);_mfa;_mfaPromises;_appApi;_dataSuffixPlugin;constructor(e,t,n,r,i,a,o){if(this._privyInternal=e,t&&(this._proxy=new Hn(t,i),r.setProxy(this._proxy)),n){let e=dt(n);this._chains=e}this._mfa=r,this._mfaPromises=i,this._appApi=a,this._dataSuffixPlugin=o}setMessagePoster(e){this._proxy=new Hn(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 D({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._proxy)throw Error(`Embedded wallet proxy not initialized`);if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await Wn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:e.chainType});else{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new D({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 Pn({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._proxy)throw Error(`Embedded wallet proxy not initialized`);if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`){if(t&&!t.startsWith(`privy`))throw new D({error:`User-controlled server wallets do not support custom recovery methods`,code:`embedded_wallet_creation_error`});await Wn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`ethereum`,idempotencyKey:c})}else{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 D({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 D({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 D({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._proxy)throw new D({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await Wn({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`solana`,idempotencyKey:e?.idempotencyKey});else{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new D({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 D({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 D({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new D({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(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return O(e)||await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new An({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(!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)||(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new An({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(!this._proxy)throw new D({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return O(e)||(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new Nn({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:o,app:this._appApi})}async setRecovery(e){let{wallet:t,...n}=e;if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(O(t))throw new D({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});On({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 An({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(M(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}}},Kn=class extends ht{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const qn=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let Jn=!1;const Yn=()=>{if(Jn)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;Jn=typeof t==`string`&&t.length>0||typeof n==`string`&&qn.includes(n)}catch{Jn=!0}return Jn},R={get(e){return At.get(e)},set(e,t,n){Yn()||At.set(e,t,n)},remove(e){At.remove(e)}},Xn=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!Yn(),Zn=`privy:active-user`,Qn=`privy:saved-users`,z=e=>e?`privy:${e}:token`:`privy:token`,B=e=>e?`privy:${e}:pat`:`privy:pat`,V=e=>e?`privy:${e}:refresh_token`:`privy:refresh_token`,H=e=>e?`privy:${e}:id-token`:`privy:id-token`,$n=e=>e?`privy-${e}-token`:`privy-token`,er=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,tr=e=>e?`privy-${e}-id-token`:`privy-id-token`,U=e=>e?`privy-${e}-session`:`privy-session`,W=Promise.allSettled.bind(Promise)??(e=>Promise.all(e.map(e=>e.then(e=>({status:`fulfilled`,value:e})).catch(e=>({status:`rejected`,reason:e}))))),nr=[`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 rr=class extends ht{static events=nr;_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 Xn({useServerCookies:this._isUsingServerCookies,cookieWriteBehavior:this._cookieWriteBehavior})}writeCookie(e,t,n){this.shouldWriteCookies()&&R.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(z(e));try{return typeof t==`string`?new T(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(B(e));try{return typeof t==`string`?new T(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(V(e));return typeof t==`string`?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(H(e));return typeof t==`string`?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=R.get(U(e));if(t!==void 0&&t.length>0)return!0;let n=R.get(U(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=T.parse(e);return t!==null&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),n=[this._storage.del(z(null)),this._storage.del(B(null)),this._storage.del(V(null)),this._storage.del(H(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(Zn)];t&&n.push(this._storage.del(z(t)),this._storage.del(B(t)),this._storage.del(V(t)),this._storage.del(H(t)),this.removeSavedUserId(t)),await W(n),R.remove($n(null)),R.remove(er(null)),R.remove(tr(null)),R.remove(U(null)),t&&(R.remove($n(t)),R.remove(er(t)),R.remove(tr(t)),R.remove(U(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=z(e),r=$n(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=T.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),R.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=B(e);typeof t==`string`?await this._storage.put(n,t):await this._storage.del(n)}async storeRefreshTokenForUser(e,t){let n=V(e),r=er(e),i=U(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),R.remove(r),R.remove(i),this.emit(`refresh_token_cleared`,{reason:`set_with_non_string_value`}))}async updateWithTokensResponse(e){let t=e.user.id,n=(await W([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 W([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 W([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(z(null)),this._storage.get(B(null)),this._storage.get(V(null)),this._storage.get(H(null))]);if(typeof e!=`string`||typeof n!=`string`)return;let i=T.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 W(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=H(e),r=tr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=T.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),R.remove(r),e!==null&&this.emit(`identity_token_cleared`,{reason:`set_with_non_string_value`})}}async getOrCreateGuestCredential(){let e=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&typeof e==`string`)return e;let t=at.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,t),t}async getActiveUserId(){let e=await this._storage.get(Zn);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(Zn,e)}async getSavedUserIds(){let e=await this._storage.get(Qn);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(Qn,JSON.stringify(t)):await this._storage.del(Qn),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 D({code:`invalid_input`,error:`Cannot switch active user because the user ID is not saved on this device`});await this._storage.put(Zn,e)}};const ir=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function ar(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 G=()=>void 0,K={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},or=({level:e,logger:t})=>({get level(){return e},error:K[e]>=K.ERROR?t.error:G,warn:K[e]>=K.WARN?t.warn:G,info:K[e]>=K.INFO?t.info:G,debug:K[e]>=K.DEBUG?t.debug:G});function q(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const sr=e=>3**e*500,cr=[408,409,425,500,502,503,504];function lr(e){return async(t,n)=>{let r=t instanceof Request?t:new Request(t,n),i,a=!1,o;for(let t=0;t<=3;t++){let s=new Headers(n?.headers??r.headers);s.set(`privy-retry-attempt`,String(t));try{let t=await e(r.clone(),{...n,headers:s});if(!cr.includes(t.status))return t;o=t,a=!1}catch(e){i===void 0&&(i=e),a=!0}t<3&&await q(sr(t))}if(a)throw i;return o}}const ur=`privy:caid`;var dr=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.74.0`;_fetch;nativeAppIdentifier;_crypto;isMultiUserModeEnabled;_cache=new Map;constructor(e){this.logger=or({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 rr({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=lr(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 D({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}${rt(e.path,t)}${ar(n)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new D({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,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),l=await c.json();if(c.status>299)throw new E({...l,status:c.status});return l}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 E({...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:ir(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:ir(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(n,{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(ur);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(ur,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(ur)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,n){try{await this.fetch(t,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:n},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch{}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new D({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 E({code:kt.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});try{this.logger.debug(`[privy:refresh] fetching: ${Le.path}`);let n=await this.fetch(Le,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),r=n.session_update_action;return this.logger.debug(`[privy:refresh] response: ${r}`),r===`set`&&(await this.session.updateWithTokensResponse(n),this.logger.debug(`[privy:refresh] tokens stored`)),r===`clear`&&(await this.session.destroyLocalState(),this.logger.debug(`[privy:refresh] tokens cleared`),!t&&this.callbacks?.setUser?.(null)),r===`ignore`&&(n.token&&(await this.session.storeCustomerAccessToken(n.token),this.logger.debug(`[privy:refresh] token stored (CAT)`)),n.privy_access_token&&(await this.session.storePrivyAccessToken(n.privy_access_token),this.logger.debug(`[privy:refresh] token stored (PAT)`)),n.identity_token&&(this.logger.debug(`[privy:refresh] token stored (IDT)`),await this.session.storeIdentityToken(n.identity_token))),this.logger.debug(`[privy:refresh] returning response`),!t&&this.callbacks?.setUser?.(n.user),n}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??`unknown error`}`),e instanceof E&&e.code===kt.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),!t&&this.callbacks?.setUser?.(null)),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}}},fr=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(){return{user:await this._privyInternal.fetch(e,{})}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(Re,{});return await this._privyInternal.session.storeIdentityToken(t),this._privyInternal.callbacks?.setUser?.(e),{user:e}}async switchActiveUser(e){if(!this._isMultiUserModeEnabled)throw new D({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 D({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 J=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`,Y=e=>e?e.linked_accounts.filter(J).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],X=e=>Y(e).find(e=>e.wallet_index===0)??null,pr=X,mr=e=>e?e.linked_accounts.filter(J).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],hr=e=>mr(e).find(e=>e.wallet_index===0)??null,gr=(e,t)=>t===`off`||Y(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,_r=(e,t)=>t===`off`||mr(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,vr=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),Z=async(e,t,n)=>{let r=gr(t.user,n?.ethereum?.createOnLogin??`off`),i=_r(t.user,n?.solana?.createOnLogin??`off`);if(r&&i){let n=await e.create({recoveryMethod:`privy`,skipCallbacks:!0}),r=await e.createSolana({ethereumAccount:X(n.user)??void 0});return vr(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:hr(t.user)??void 0});return vr(n,t)}if(i){let n=await e.createSolana({ethereumAccount:X(t.user)??void 0});return vr(n,t)}return t};var yr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async syncWithToken(e,t,n){let r=await this._privyInternal.fetchForLogin(o,{body:{token:e,mode:n}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await Z(this._embedded,r,t?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithToken(e){await this._privyInternal.fetch(s,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},br=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Ce,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Se,{body:{email:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(we,{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(je,{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(Ae,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},xr=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(l,{body:{relying_party:e,redirect_url:t,token:n}})}async getFarcasterStatus({channel_token:e}){return await this._privyInternal.fetch(ee,{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(c,{body:{channel_token:e,message:t,signature:n,fid:r,mode:i}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await Z(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(u,{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(te,{body:{fid:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Sr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(f,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(d,{body:{message:e,signature:t,fid:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}},Cr=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(se,{body:{guest_credential:t}});await this._privyInternal.session.updateWithTokensResponse(n);let r=await Z(this._embedded,n,e?.embedded);return this._privyInternal.callbacks?.setUser?.(r.user),r}};const Q=`privy:state_code`,$=`privy:code_verifier`;async function wr(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function Tr(e){return crypto.getRandomValues(new Uint8Array(e))}function Er(){return at.encode(Tr(36))}function Dr(){return Er()}async function Or({codeVerifier:e,method:t=`S256`,digest:n}){if(t==`S256`){let t=await wr(e,n);return at.encode(t)}else return e}var kr=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=Er(),r=Dr(),i=await Or({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put($,n),this._storage.put(Q,r)]),this._privyInternal.fetchForLogin(pe,{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($),this._storage.get(Q)]);if(s!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:s??``,returnedStateCode:t??``}),new D({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let c=await this._privyInternal.fetchForLogin(fe,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let l=await Z(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del($),this._storage.del(Q)]),this._privyInternal.callbacks?.setUser?.(l.user),l}async linkWithCode(e,t,n,r){let[i,a]=await Promise.all([this._storage.get($),this._storage.get(Q)]);if(a!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:a??``,returnedStateCode:t??``}),new D({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let o=await this._privyInternal.fetch(me,{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($),this._storage.del(Q)]),{user:s.user,identity_token:s.identity_token}}async unlink(e,t){await this._privyInternal.fetch(he,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},Ar=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(ye,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(_e,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(xe,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(ge,{body:{relying_party:n,challenge:t,authenticator_response:this._transformAuthenticationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async signupWithPasskey(e,t,n){let r=await this._privyInternal.fetchForLogin(be,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await Z(this._embedded,r,n?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithPasskey(e,t){await this._privyInternal.fetch(ve,{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}}}},jr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Ee,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Te,{body:{phoneNumber:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await Z(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(De,{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(ke,{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(Oe,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Mr=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(Ue,{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(Ve,{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 Z(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(Be,{body:{address:e.address}}),i=Nr({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 Nr(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
|
|
12
|
+
- https://privy.io`}var Pr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlink({address:e}){await this._privyInternal.fetch(qe,{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(Ke,{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(We,{body:{signature:n,message:t,walletClientType:r??null,connectorType:i??null,mode:e}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await Z(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async fetchNonce({address:e}){let{nonce:t}=await this._privyInternal.fetch(Ge,{body:{address:e}});return{nonce:t}}},Fr=class{_privyInternal;constructor(e){this._privyInternal=e}async link(e,t,n,r){await this._privyInternal.fetch(He,{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(Be,{body:{address:e.address}});return{nonce:t,message:Ir({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 Ir(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 Pr=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(qe,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n,mode:r}});await this._privyInternal.session.updateWithTokensResponse(a);let o=await Z(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(Je,{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(Ye,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Fr=class{_privyInternal;_mfa;customProvider;phone;email;oauth;siwe;siws;smartWallet;passkey;farcaster;farcasterV2;guest;telegram;constructor(e,t,n,r,i){this._privyInternal=e,this._mfa=i,this.customProvider=new gr(this._privyInternal,t),this.phone=new Or(this._privyInternal,t),this.email=new _r(this._privyInternal,t),this.oauth=new Er(this._privyInternal,t,n,r),this.guest=new br(this._privyInternal,t),this.siwe=new kr(this._privyInternal,t),this.siws=new jr(this._privyInternal,t),this.smartWallet=new Mr(this._privyInternal),this.passkey=new Dr(this._privyInternal,t),this.farcaster=new vr(this._privyInternal,t),this.farcasterV2=new yr(this._privyInternal,t),this.telegram=new Pr(this._privyInternal,t)}async logout(e){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})]),this._privyInternal.callbacks?.setUser?.(null),t&&this._privyInternal.fetch(se,{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}}},Ir=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(r,{body:e})}async getStatus(e){return await this._privyInternal.fetch(i,{query:{partnerUserId:e}})}};const Lr={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},Rr=new Set([_.id,m.id,g.id,b.id,h.id,lt.id,v.id]),zr=new Set([_.id,m.id,y.id,g.id,b.id,h.id]);function Br(e,t){switch(t){case`native-currency`:return Rr.has(e);case`USDC`:return zr.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function Vr(e,t){switch(e){case m.id:return t===`native-currency`?`ETH_ARBITRUM`:`USDC_ARBITRUM`;case h.id:return t===`native-currency`?`AVAX_CCHAIN`:`USDC_CCHAIN`;case g.id:return t===`native-currency`?`ETH_BASE`:`USDC_BASE`;case lt.id:return`CELO_CELO`;case b.id:return t===`native-currency`?`MATIC_POLYGON`:`USDC_POLYGON`;case v.id:return`MON_MON`;case _.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 Hr(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var Ur=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(ue,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=Lr[t?`sandbox`:`prod`],i=await At(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new Ut({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}},Wr=class{moonpay;coinbase;constructor(e){this.moonpay=new Ur(e),this.coinbase=new Ir(e)}},Gr=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(ce,{body:e})}},Kr=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(le,{body:e})}},qr=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new Kr(e),this.passkey=new Gr(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)}},Jr=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(Fe,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(je,{body:{client_type:e}})}},Yr=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=Cr(),n=wr(),r=await Tr({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put($,t),this._storage.put(Q,n)]),this._privyInternal.fetch(Pe,{body:{redirect_to:e,code_challenge:r,state_code:n}})}async authorize(e,t){let[n,r]=await Promise.all([this._storage.get($),this._storage.get(Q)]);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(Ne,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del($),this._storage.del(Q)]),i}},Xr=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new Yr(this._privyInternal,t,n),this.icloudAuth=new Jr(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(Me,{body:{chain_type:t},params:{address:e}})}},Zr=class{auth;user;embeddedWallet;recovery;mfa;app;mfaPromises;funding;delegated;crossApp;isMultiUserModeEnabled;_privyInternal;constructor({clientId:e,sessions:t,...n}){let r=zt(n.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this._privyInternal=new sr({...n,appClientId:e,crypto:r,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new qr(this._privyInternal),this.mfaPromises=new Un,this.app=new Bt(this._privyInternal),this.embeddedWallet=new Hn(this._privyInternal,n.embeddedWalletMessagePoster,n.supportedChains,this.mfa,this.mfaPromises,this.app),this.user=new cr(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new Fr(this._privyInternal,this.embeddedWallet,n.storage,r,this.mfa),this.recovery=new Xr(this._privyInternal,n.storage,r),this.funding=new Wr(this._privyInternal),this.delegated=new Ht(this._privyInternal),this.crossApp=new Vt(this._privyInternal,n.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}},Qr=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)}},$r=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 ei=e=>e?e.linked_accounts.filter(Y).filter(ti).sort((e,t)=>e.wallet_index-t.wallet_index):[],ti=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,ni=(e,t)=>{if(!e)return null;if(t?.imported)return ri(t);let n=X(e)??fr(e);return n?ri(n):null},ri=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`)},ii=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,ai=(e,t)=>It(String(e),t),oi=e=>Lt(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),si=(e,t)=>`+${Pt(t)} ${e}`,ci=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,li=e=>new Mt(e),ui=Nt().map(e=>({code:e,callCode:Pt(e)})),di=e=>{let t=Ft(e,jt)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},fi=e=>{let t=new Mt;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},pi=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),mi={[_.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[pt.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[y.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[dt.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[b.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[ft.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[g.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[ct.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[h.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[st.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[m.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[ot.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},hi={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function gi(e,t){return e===mi[t.id]}async function _i(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 vi=new Set([_.id,g.id,y.id,b.id,m.id,h.id,v.id]),yi=new Set([_.id,g.id,b.id,y.id,m.id,h.id,v.id]),bi={buy:`CARD`,send:`CRYPTO_ACCOUNT`},xi={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`},Si={[_.id]:`ethereum`,[g.id]:`base`,[y.id]:`optimism`,[b.id]:`polygon`,[m.id]:`arbitrum`,[h.id]:`avacchain`,[v.id]:`monad`};function Ci(e){return e.startsWith(`.`)?`0${e}`:e}function wi({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`,Ci(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,bi[a]),o.searchParams.set(`defaultAsset`,xi[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const Ti=(e,t)=>{switch(t){case`native-currency`:return vi.has(e);case`USDC`:return yi.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function Ei(e){return Si[e]}function Di(e,t){return t===`USDC`?`USDC`:e===b.id?`POL`:e===v.id?`MON`:`ETH`}var Oi=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=zt(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 ki=({address:e,nonce:t,domain:n,uri:r})=>`${n} wants you to sign in with your Solana account:
|
|
23
|
+
- https://privy.io`}var Lr=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(Je,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n,mode:r}});await this._privyInternal.session.updateWithTokensResponse(a);let o=await Z(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(Ye,{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(Xe,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Rr=class{_privyInternal;_mfa;customProvider;phone;email;oauth;siwe;siws;smartWallet;passkey;farcaster;farcasterV2;guest;telegram;constructor(e,t,n,r,i){this._privyInternal=e,this._mfa=i,this.customProvider=new yr(this._privyInternal,t),this.phone=new jr(this._privyInternal,t),this.email=new br(this._privyInternal,t),this.oauth=new kr(this._privyInternal,t,n,r),this.guest=new Cr(this._privyInternal,t),this.siwe=new Mr(this._privyInternal,t),this.siws=new Pr(this._privyInternal,t),this.smartWallet=new Fr(this._privyInternal),this.passkey=new Ar(this._privyInternal,t),this.farcaster=new xr(this._privyInternal,t),this.farcasterV2=new Sr(this._privyInternal,t),this.telegram=new Lr(this._privyInternal,t)}async logout(e){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})]),this._privyInternal.callbacks?.setUser?.(null),t&&this._privyInternal.fetch(ce,{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}}},zr=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(r,{body:e})}async getStatus(e){return await this._privyInternal.fetch(i,{query:{partnerUserId:e}})}};const Br={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},Vr=new Set([g.id,p.id,h.id,y.id,m.id,ut.id,_.id]),Hr=new Set([g.id,p.id,v.id,h.id,y.id,m.id]);function Ur(e,t){switch(t){case`native-currency`:return Vr.has(e);case`USDC`:return Hr.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function Wr(e,t){switch(e){case p.id:return t===`native-currency`?`ETH_ARBITRUM`:`USDC_ARBITRUM`;case m.id:return t===`native-currency`?`AVAX_CCHAIN`:`USDC_CCHAIN`;case h.id:return t===`native-currency`?`ETH_BASE`:`USDC_BASE`;case ut.id:return`CELO_CELO`;case y.id:return t===`native-currency`?`MATIC_POLYGON`:`USDC_POLYGON`;case _.id:return`MON_MON`;case g.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 Gr(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var Kr=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(de,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=Br[t?`sandbox`:`prod`],i=await jt(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new Jt({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}},qr=class{moonpay;coinbase;constructor(e){this.moonpay=new Kr(e),this.coinbase=new zr(e)}},Jr=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(le,{body:e})}},Yr=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(ue,{body:e})}},Xr=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new Yr(e),this.passkey=new Jr(e)}setProxy(e){this.proxy=e}async getAccessTokenInternal(){let e=await this.privyInternal.getAccessTokenInternal();if(!e)throw new D({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return e}async verifyMfa(){if(!this.proxy)throw new D({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 D({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 D({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 D({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 D({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 D({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.clearMfa(e)}},Zr=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(Ie,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(Me,{body:{client_type:e}})}},Qr=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=Er(),n=Dr(),r=await Or({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put($,t),this._storage.put(Q,n)]),this._privyInternal.fetch(Fe,{body:{redirect_to:e,code_challenge:r,state_code:n}})}async authorize(e,t){let[n,r]=await Promise.all([this._storage.get($),this._storage.get(Q)]);if(r!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`recovery_oauth`,storedStateCode:r??``,returnedStateCode:t??``}),new D({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let i=await this._privyInternal.fetch(Pe,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del($),this._storage.del(Q)]),i}},$r=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new Qr(this._privyInternal,t,n),this.icloudAuth=new Zr(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(Ne,{body:{chain_type:t},params:{address:e}})}},ei=class{plugins;auth;user;embeddedWallet;recovery;mfa;app;mfaPromises;funding;delegated;crossApp;isMultiUserModeEnabled;_privyInternal;constructor({clientId:e,sessions:t,plugins:n=[],...r}){let i=Bt(r.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this.plugins=[...n],this._privyInternal=new dr({...r,appClientId:e,crypto:i,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new Xr(this._privyInternal),this.mfaPromises=new Kn,this.app=new Gt(this._privyInternal),this.embeddedWallet=new Gn(this._privyInternal,r.embeddedWalletMessagePoster,r.supportedChains,this.mfa,this.mfaPromises,this.app,Ut(this.plugins)),this.user=new fr(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new Rr(this._privyInternal,this.embeddedWallet,r.storage,i,this.mfa),this.recovery=new $r(this._privyInternal,r.storage,i),this.funding=new qr(this._privyInternal),this.delegated=new qt(this._privyInternal),this.crossApp=new Kt(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}},ti=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)}},ni=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 ri=e=>e?e.linked_accounts.filter(J).filter(ii).sort((e,t)=>e.wallet_index-t.wallet_index):[],ii=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,ai=(e,t)=>{if(!e)return null;if(t?.imported)return oi(t);let n=X(e)??hr(e);return n?oi(n):null},oi=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`)},si=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,ci=(e,t)=>Lt(String(e),t),li=e=>Rt(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),ui=(e,t)=>`+${Ft(t)} ${e}`,di=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,fi=e=>new Nt(e),pi=Pt().map(e=>({code:e,callCode:Ft(e)})),mi=e=>{let t=It(e,Mt)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},hi=e=>{let t=new Nt;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},gi=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),_i={[g.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[mt.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[v.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[ft.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[y.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[pt.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[h.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[lt.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[m.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[ct.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[p.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[st.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},vi={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function yi(e,t){return e===_i[t.id]}async function bi(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 xi=new Set([g.id,h.id,v.id,y.id,p.id,m.id,_.id]),Si=new Set([g.id,h.id,y.id,v.id,p.id,m.id,_.id]),Ci={buy:`CARD`,send:`CRYPTO_ACCOUNT`},wi={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`},Ti={[g.id]:`ethereum`,[h.id]:`base`,[v.id]:`optimism`,[y.id]:`polygon`,[p.id]:`arbitrum`,[m.id]:`avacchain`,[_.id]:`monad`};function Ei(e){return e.startsWith(`.`)?`0${e}`:e}function Di({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`,Ei(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,Ci[a]),o.searchParams.set(`defaultAsset`,wi[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const Oi=(e,t)=>{switch(t){case`native-currency`:return xi.has(e);case`USDC`:return Si.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function ki(e){return Ti[e]}function Ai(e,t){return t===`USDC`?`USDC`:e===y.id?`POL`:e===_.id?`MON`:`ETH`}var ji=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=Bt(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 Mi=({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 Ai({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 ji({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function Mi(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const Ni=`solana offchain`,Pi=1232;function Fi(e){let t=S.utf8.toBytes(e),n=new Uint8Array(32);return n.set(t.slice(0,32)),n}function Ii({message:e,signerPublicKey:t,domain:n}){let r=S.utf8.toBytes(e);if(t.length!==32)throw Error(`Signer public key must be 32 bytes`);let i=85+r.length;if(i>Pi)throw Error(`Combined message length (${i}) exceeds maximum (${Pi})`);let a=Fi(n),o=new Uint8Array(i),s=0;o[s]=255,s+=1;let c=S.utf8.toBytes(Ni);return o.set(c,s),s+=c.length,o[s]=0,s+=1,o.set(a,s),s+=32,o[s]=1,s+=1,o[s]=1,s+=1,o.set(t,s),s+=32,o[s]=r.length&255,o[s+1]=r.length>>8&255,s+=2,o.set(r,s),o}function Li(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))!==Ni)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 Ri=[`privy`],zi=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],Bi=[`coinbase_wallet`],Vi=`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(`.`),Hi=[`unknown`],Ui=[...zi,...Bi,...Vi,...Ri,...Hi],Wi=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Gi(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function Ki({wei:e,precision:t=3}){return parseFloat(gt(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function qi({amount:e,decimals:t}){return _t(BigInt(e),t)}function Ji({lamports:e}){return _t(e,9)}const Yi=e=>[...lr(e),...dr(e)],Xi=(e,t)=>e.imported?e:X(t)??fr(t),Zi=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=Yi(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(D(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=Xi(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}},Qi=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=Yi(t);if(n.some(D))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 $i=C({delegateWallet:()=>Zi,revokeWallets:()=>Qi});const ea=({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 l=await e.auth.oauth.loginWithCode(c,s,i),u=l.oauth_tokens;return u&&await e.crossApp.updateOnCrossAppAuthentication(n,u),l},ta=({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 l=e.addOAuthTokensListener(t=>{e.crossApp.updateOnCrossAppAuthentication(n,t)}),{user:u}=await e.auth.oauth.linkWithCode(c,s,i);return l.unsubscribe(),u};function na(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const ra=(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)),ia=({client:e,openAuthSession:t})=>{let n=ta({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))},aa=({client:e,openAuthSession:t})=>{let n=ia({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=ra(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 ee=await n({providerAppId:c,redirectUrl:a});if(!ee)throw new E({code:`cross_app_request_error`,error:`Wallet operations require a valid token`});let te={content:{request:{request:i}},timestamp:Date.now(),callbackUrl:a},d=new URL(`${u.provider_app_custom_api_url}/oauth/transact`);d.searchParams.set(`communicationMode`,`redirect`),d.searchParams.set(`token`,ee),d.searchParams.set(`request`,JSON.stringify(te));let{privy_cross_app_type:f,privy_cross_app_payload:p}=await t(d.href,a);if(!f||!p)throw new E({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(f===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new E({code:`cross_app_request_error`,error:p});if(f!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new E({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:p}}};function oa(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 sa=({client:e,openAuthSession:t})=>{let n=aa({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{oa(e);let a={method:na(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 ca(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 la=({client:e,openAuthSession:t})=>{let n=aa({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{oa(e);let a={method:na(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,ca(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},ua=({client:e,openAuthSession:t})=>{let n=aa({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{oa(e);let a={method:na(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var da=C({sendTransaction:()=>ua,signMessage:()=>sa,signTypedData:()=>la}),fa=C({linkWithCrossAppAuth:()=>ta,loginWithCrossAppAuth:()=>ea,wallet:()=>da});function pa(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 ma(e,t){let n=pa(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 ha(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=ma(e.caip2,t);if(n)return{ok:!0,address:n};let r=pa(e.caip2);if(!r)return{ok:!1,error:`UNSUPPORTED_CHAIN`};try{let t=await e.privy.fetchPrivyRoute(Xe,{body:{chain_type:r}});return await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function ga(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await ha({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(a,{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}const _a=async({operation:e,until:t,delay:n,interval:r,attempts:i,signal:a})=>{n&&await J(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 J(r)}catch(e){e instanceof Error&&(c=e),o<i&&await J(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},va=2e3,ya=1800*1e3;function ba(e,t){return Math.ceil(t/e)}function xa(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 Sa(e){return await e.privy.fetchPrivyRoute(ne,{params:{order_id:e.orderId}})}async function Ca(e){let t=e.pollIntervalMs??va,n=e.timeoutMs??ya,r=e.signal??new AbortController().signal;return xa(await _a({operation:async()=>{let t=await e.privy.fetchPrivyRoute(ie,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(ne,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:ba(t,n),signal:r}))}async function wa(e){let t=e.pollIntervalMs??va,n=e.timeoutMs??ya,r=e.signal??new AbortController().signal;return xa(await _a({operation:()=>e.privy.fetchPrivyRoute(ne,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:ba(t,n),signal:r}))}var Ta=C({generateDepositAddress:()=>ga,getConfig:()=>Ea,getDeposit:()=>Sa,resolveRefundAddress:()=>ha,waitForCompletion:()=>wa,waitForDeposit:()=>Ca});async function Ea(e){let t=await e.fetchPrivyRoute(re,{});return{currencies:t.currencies,chains:t.chains}}async function Da(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(Qe,{params:{wallet_id:n}}),a=String(Date.now()+sn),{signature:o}=await N(t,{version:1,url:i,method:Qe.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(Qe,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[P]:a}})}async function Oa(e,{wallet_id:t}){return await e.fetchPrivyRoute(Ze,{params:{wallet_id:t}})}async function ka(e,{wallet_id:t},n,r){let{signature:i}=await N(n,{version:1,url:e.getCompiledPath(et,{params:{wallet_id:t}}),method:et.method,headers:{"privy-app-id":e.app.appId},body:r});return await e.fetchPrivyRoute(et,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":i}})}async function Aa({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(D(t)){if(n.length===0)throw Error(`Must specify at least one signer to add.`);let r={wallet_id:t.id},i=await Oa(e,r);await ka(e,r,Na(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return Ma(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=Xi(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 Ma(e)}async function ja({client:e,wallet:t}){return D(t)?await ka(e,{wallet_id:t.id},Na(e),{additional_signers:[]}):await e.delegated.revoke(),Ma(e)}async function Ma(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function Na(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var Pa=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 Fa=`biconomy`,Ia=`coinbase_smart_wallet`,La=`kernel`,Ra=`light_account`,za=`safe`,Ba=`thirdweb`,Va=`nexus`;var Ha=Zr;export{Ui as ALL_WALLET_CLIENT_TYPES,Fa as BICONOMY,Ia as COINBASE_SMART_WALLET,Pa as ConnectedStandardSolanaWallet,$t as EmbeddedProviderError,$r as InMemoryCache,La as KERNEL,Ra as LIGHT_ACCOUNT,Qr as LocalStorage,Ut as MoonpayApiError,Va as NEXUS,T as PrivyApiError,E as PrivyClientError,Qt as PrivyConnectorError,Jt as PrivyEmbeddedWalletErrorCode,an as PrivyProviderRpcError,O as ProviderErrors,za as SAFE,Wi as SUPPORTED_CONNECTOR_TYPES,Oi as SolanaClient,hi as SolanaUsdcAddressMap,Ba as THIRDWEB,mi as UsdcAddressMap,Aa as addSessionSigners,Ii as buildSolanaOffchainMessage,Vr as chainToMoonpayCurrency,R as cookies,ui as countryCodesAndNumbers,Bn as create,Gt as createErrorFormatter,ki as createSiwsMessage,fa as crossApp,Ha as default,$i as delegatedActions,Ta as depositAddress,Fi as deriveSolanaApplicationDomain,nn as errorIndicatesMaxMfaRetries,Kt as errorIndicatesMfaCanceled,rn as errorIndicatesMfaRateLimit,en as errorIndicatesMfaTimeout,tn as errorIndicatesMfaVerificationFailed,A as errorIndicatesRecoveryIsNeeded,Ji as formatLamportsAmount,si as formatPhoneNumber,qi as formatTokenAmount,Gi as formatWalletAddress,Ki as formatWeiAmount,Hr as fundingMethodToMoonpayPaymentMethod,N as generateAuthorizationSignature,_i as generateWalletIdempotencyKey,ei as getAllUserEmbeddedBitcoinWallets,lr as getAllUserEmbeddedEthereumWallets,dr as getAllUserEmbeddedSolanaWallets,wi as getCoinbaseOnRampUrl,Pt as getCountryCallingCode,ri as getEntropyDetailsFromAccount,ni as getEntropyDetailsFromUser,gi as getIsTokenUsdc,wn as getJsonRpcEndpointFromChain,fi as getPhoneCountryCodeAndNumber,di as getPlaceholderPhoneNumber,Mi as getSolanaClusterDisplayName,Ai as getSolanaRpcEndpointForCluster,ji as getSolanaUsdcMintAddressForCluster,X as getUserEmbeddedEthereumWallet,fr as getUserEmbeddedSolanaWallet,ur as getUserEmbeddedWallet,ii as getUserSmartWallet,Oa as getWallet,Y as isEmbeddedWalletAccount,Kn as isExtensionContext,Ti as isSupportedChainIdForCoinbaseOnramp,Br as isSupportedChainIdForMoonpay,D as isUnifiedWallet,ci as lastFourDigits,Li as parseSolanaOffchainMessage,li as phoneNumberTypingFormatter,_a as poll,Da as rawSign,ja as removeSessionSigners,F as rpc,qn as shouldWriteSessionCookies,Tn as throwIfInvalidRecoveryUpgradePath,Di as toCoinbaseAssetId,Ei as toCoinbaseBlockchainFromChainId,oi as toE164,pi as toObjectKeys,cn as toWalletApiUnsignedEthTransaction,ka as updateWallet,ai as validatePhoneNumber};
|
|
34
|
+
- https://privy.io`;function Ni({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 Pi({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function Fi(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const Ii=`solana offchain`,Li=1232;function Ri(e){let t=x.utf8.toBytes(e),n=new Uint8Array(32);return n.set(t.slice(0,32)),n}function zi({message:e,signerPublicKey:t,domain:n}){let r=x.utf8.toBytes(e);if(t.length!==32)throw Error(`Signer public key must be 32 bytes`);let i=85+r.length;if(i>Li)throw Error(`Combined message length (${i}) exceeds maximum (${Li})`);let a=Ri(n),o=new Uint8Array(i),s=0;o[s]=255,s+=1;let c=x.utf8.toBytes(Ii);return o.set(c,s),s+=c.length,o[s]=0,s+=1,o.set(a,s),s+=32,o[s]=1,s+=1,o[s]=1,s+=1,o.set(t,s),s+=32,o[s]=r.length&255,o[s+1]=r.length>>8&255,s+=2,o.set(r,s),o}function Bi(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))!==Ii)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 Vi=[`privy`],Hi=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],Ui=[`coinbase_wallet`],Wi=`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(`.`),Gi=[`unknown`],Ki=[...Hi,...Ui,...Wi,...Vi,...Gi],qi=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Ji(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function Yi({wei:e,precision:t=3}){return parseFloat(_t(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function Xi({amount:e,decimals:t}){return vt(BigInt(e),t)}function Zi({lamports:e}){return vt(e,9)}const Qi=e=>[...Y(e),...mr(e)],$i=(e,t)=>e.imported?e:X(t)??hr(t),ea=e=>async({address:t,chainType:n})=>{let{user:r}=await e.user.get();if(!r)throw new D({code:`delegated_actions_before_logged_in`,error:`Must be logged in to delegate wallets`});if(n!==`solana`&&n!==`ethereum`)throw new D({code:`unsupported_chain_type`,error:`Only Solana and Ethereum embedded wallets are supported for delegation and revocation.`});let i=Qi(r).find(e=>e.chain_type===n&&e.address===t);if(!i)throw new D({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});if(O(i))throw new D({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=$i(i,r);if(!a)throw new D({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}},ta=e=>async()=>{let{user:t}=await e.user.get();if(!t)throw new D({code:`delegated_actions_before_logged_in`,error:`Must be logged in to revoke delegated wallets`});let n=Qi(t);if(n.some(O))throw new D({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 D({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 na=S({delegateWallet:()=>ea,revokeWallets:()=>ta});const ra=({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 D({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let l=await e.auth.oauth.loginWithCode(c,s,i),u=l.oauth_tokens;return u&&await e.crossApp.updateOnCrossAppAuthentication(n,u),l},ia=({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 D({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let l=e.addOAuthTokensListener(t=>{e.crossApp.updateOnCrossAppAuthentication(n,t)}),{user:u}=await e.auth.oauth.linkWithCode(c,s,i);return l.unsubscribe(),u};function aa(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const oa=(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)),sa=({client:e,openAuthSession:t})=>{let n=ia({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))},ca=({client:e,openAuthSession:t})=>{let n=sa({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=oa(r,o);if(!s)throw new D({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 D({code:`cross_app_invalid_app`,error:`Invalid connected app`});if(u.read_only)throw new D({code:`cross_app_read_only`,error:`Cannot transact against a read-only provider app`});let ee=await n({providerAppId:c,redirectUrl:a});if(!ee)throw new D({code:`cross_app_request_error`,error:`Wallet operations require a valid token`});let te={content:{request:{request:i}},timestamp:Date.now(),callbackUrl:a},d=new URL(`${u.provider_app_custom_api_url}/oauth/transact`);d.searchParams.set(`communicationMode`,`redirect`),d.searchParams.set(`token`,ee),d.searchParams.set(`request`,JSON.stringify(te));let{privy_cross_app_type:f,privy_cross_app_payload:ne}=await t(d.href,a);if(!f||!ne)throw new D({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(f===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new D({code:`cross_app_request_error`,error:ne});if(f!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new D({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:ne}}};function la(e){if(!e)throw new D({code:`attempted_cross_app_request_before_logged_in`,error:`Must be logged in to sign messages with a cross-app wallet`})}const ua=({client:e,openAuthSession:t})=>{let n=ca({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{la(e);let a={method:aa(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 da(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 fa=({client:e,openAuthSession:t})=>{let n=ca({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{la(e);let a={method:aa(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,da(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},pa=({client:e,openAuthSession:t})=>{let n=ca({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{la(e);let a={method:aa(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var ma=S({sendTransaction:()=>pa,signMessage:()=>ua,signTypedData:()=>fa}),ha=S({linkWithCrossAppAuth:()=>ia,loginWithCrossAppAuth:()=>ra,wallet:()=>ma});function ga(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 _a(e,t){let n=ga(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 va(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=_a(e.caip2,t);if(n)return{ok:!0,address:n};let r=ga(e.caip2);if(!r)return{ok:!1,error:`UNSUPPORTED_CHAIN`};try{let t=await e.privy.fetchPrivyRoute(Ze,{body:{chain_type:r}});return await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function ya(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await va({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(a,{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}const ba=async({operation:e,until:t,delay:n,interval:r,attempts:i,signal:a})=>{n&&await q(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 q(r)}catch(e){e instanceof Error&&(c=e),o<i&&await q(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},xa=2e3,Sa=1800*1e3;function Ca(e,t){return Math.ceil(t/e)}function wa(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 Ta(e){return await e.privy.fetchPrivyRoute(re,{params:{order_id:e.orderId}})}async function Ea(e){let t=e.pollIntervalMs??xa,n=e.timeoutMs??Sa,r=e.signal??new AbortController().signal;return wa(await ba({operation:async()=>{let t=await e.privy.fetchPrivyRoute(ae,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(re,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:Ca(t,n),signal:r}))}async function Da(e){let t=e.pollIntervalMs??xa,n=e.timeoutMs??Sa,r=e.signal??new AbortController().signal;return wa(await ba({operation:()=>e.privy.fetchPrivyRoute(re,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:Ca(t,n),signal:r}))}var Oa=S({generateDepositAddress:()=>ya,getConfig:()=>ka,getDeposit:()=>Ta,resolveRefundAddress:()=>va,waitForCompletion:()=>Da,waitForDeposit:()=>Ea});async function ka(e){let t=await e.fetchPrivyRoute(ie,{});return{currencies:t.currencies,chains:t.chains}}async function Aa(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath($e,{params:{wallet_id:n}}),a=String(Date.now()+un),{signature:o}=await N(t,{version:1,url:i,method:$e.method,headers:{"privy-app-id":e.app.appId,[P]:a},body:{...r}});if(Date.now()>Number(a))throw new D({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute($e,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[P]:a}})}async function ja(e,{wallet_id:t}){return await e.fetchPrivyRoute(Qe,{params:{wallet_id:t}})}async function Ma(e,{wallet_id:t},n,r){let{signature:i}=await N(n,{version:1,url:e.getCompiledPath(tt,{params:{wallet_id:t}}),method:tt.method,headers:{"privy-app-id":e.app.appId},body:r});return await e.fetchPrivyRoute(tt,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":i}})}async function Na({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 ja(e,r);await Ma(e,r,Ia(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return Fa(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=$i(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 Fa(e)}async function Pa({client:e,wallet:t}){return O(t)?await Ma(e,{wallet_id:t.id},Ia(e),{additional_signers:[]}):await e.delegated.revoke(),Fa(e)}async function Fa(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function Ia(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var La=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 Ra=`biconomy`,za=`coinbase_smart_wallet`,Ba=`kernel`,Va=`light_account`,Ha=`safe`,Ua=`thirdweb`,Wa=`nexus`;var Ga=ei;export{Ki as ALL_WALLET_CLIENT_TYPES,Ra as BICONOMY,za as COINBASE_SMART_WALLET,La as ConnectedStandardSolanaWallet,Ht as DATA_SUFFIX_PLUGIN_ID,rn as EmbeddedProviderError,ni as InMemoryCache,Ba as KERNEL,Va as LIGHT_ACCOUNT,ti as LocalStorage,Jt as MoonpayApiError,Wa as NEXUS,E as PrivyApiError,D as PrivyClientError,nn as PrivyConnectorError,$t as PrivyEmbeddedWalletErrorCode,ln as PrivyProviderRpcError,A as ProviderErrors,Ha as SAFE,qi as SUPPORTED_CONNECTOR_TYPES,ji as SolanaClient,vi as SolanaUsdcAddressMap,Ua as THIRDWEB,_i as UsdcAddressMap,Na as addSessionSigners,zi as buildSolanaOffchainMessage,Wr as chainToMoonpayCurrency,R as cookies,pi as countryCodesAndNumbers,Un as create,Wt as createDataSuffixPlugin,Xt as createErrorFormatter,Mi as createSiwsMessage,ha as crossApp,Ga as default,na as delegatedActions,Oa as depositAddress,Ri as deriveSolanaApplicationDomain,sn as errorIndicatesMaxMfaRetries,Zt as errorIndicatesMfaCanceled,cn as errorIndicatesMfaRateLimit,an as errorIndicatesMfaTimeout,on as errorIndicatesMfaVerificationFailed,M as errorIndicatesRecoveryIsNeeded,Zi as formatLamportsAmount,ui as formatPhoneNumber,Xi as formatTokenAmount,Ji as formatWalletAddress,Yi as formatWeiAmount,Gr as fundingMethodToMoonpayPaymentMethod,N as generateAuthorizationSignature,bi as generateWalletIdempotencyKey,ri as getAllUserEmbeddedBitcoinWallets,Y as getAllUserEmbeddedEthereumWallets,mr as getAllUserEmbeddedSolanaWallets,Di as getCoinbaseOnRampUrl,Ft as getCountryCallingCode,Ut as getDataSuffixPlugin,oi as getEntropyDetailsFromAccount,ai as getEntropyDetailsFromUser,yi as getIsTokenUsdc,Dn as getJsonRpcEndpointFromChain,hi as getPhoneCountryCodeAndNumber,mi as getPlaceholderPhoneNumber,Fi as getSolanaClusterDisplayName,Ni as getSolanaRpcEndpointForCluster,Pi as getSolanaUsdcMintAddressForCluster,X as getUserEmbeddedEthereumWallet,hr as getUserEmbeddedSolanaWallet,pr as getUserEmbeddedWallet,si as getUserSmartWallet,ja as getWallet,J as isEmbeddedWalletAccount,Yn as isExtensionContext,Oi as isSupportedChainIdForCoinbaseOnramp,Ur as isSupportedChainIdForMoonpay,O as isUnifiedWallet,di as lastFourDigits,Bi as parseSolanaOffchainMessage,fi as phoneNumberTypingFormatter,ba as poll,Aa as rawSign,Pa as removeSessionSigners,F as rpc,Xn as shouldWriteSessionCookies,On as throwIfInvalidRecoveryUpgradePath,Ai as toCoinbaseAssetId,ki as toCoinbaseBlockchainFromChainId,li as toE164,gi as toObjectKeys,dn as toWalletApiUnsignedEthTransaction,Ma as updateWallet,ci as validatePhoneNumber};
|
|
35
35
|
//# sourceMappingURL=index.mjs.map
|