@privy-io/js-sdk-core 0.78.1 → 0.78.3
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 +532 -8
- package/dist/dts/index.d.ts +532 -8
- package/dist/esm/index.mjs +4 -4
- package/dist/esm/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/esm/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AcceptCardConsents as e,AcceptTermsOnUser as t,AnalyticsEvent as n,AppConfig as r,CoinbaseOnRampInit as i,CoinbaseOnRampStatus as a,CreateCard as o,CreateCryptoDepositAccount as s,CreateCryptoDepositAccountQuote as c,CreateDepositAddressQuote as l,CustomJWTAuthenticate as u,CustomJWTLink as d,DownloadCardStatement as ee,FarcasterAuthenticate as f,FarcasterInit as te,FarcasterLink as p,FarcasterStatus as ne,FarcasterUnlink as re,FarcasterV2Authenticate as ie,FarcasterV2Init as ae,GetCardCustomer as oe,GetCardEphemeralKey as se,GetCardsConfig as ce,GetCrossAppConnections as le,GetCryptoDepositAccountNextOrder as ue,GetCryptoDepositAccountOrder as de,GetDepositAddressOrder as fe,GetDepositConfig as pe,GetNextDepositAddressOrder as me,GetSmartWalletConfig as he,GuestAuthenticate as ge,ListCardTransactions as _e,ListCards as ve,Logout as ye,MfaPasskeyInit as be,MfaPasswordlessSmsInit as xe,MoonpayOnRampSign as Se,OAuthAuthenticate as Ce,OAuthInit as we,OAuthLink as Te,OAuthUnlink as Ee,PasskeyAuthenticate as De,PasskeyAuthenticateInit as Oe,PasskeyLink as ke,PasskeyLinkInit as Ae,PasskeyRegister as je,PasskeyRegisterInit as Me,PasswordlessAuthenticate as Ne,PasswordlessInit as Pe,PasswordlessLink as Fe,PasswordlessSmsAuthenticate as Ie,PasswordlessSmsInit as Le,PasswordlessSmsLink as Re,PasswordlessSmsUnlink as ze,PasswordlessSmsUpdate as Be,PasswordlessUnlink as Ve,PasswordlessUpdate as He,RecoveryConfigurationICloud as Ue,RecoveryKeyMaterial as We,RecoveryOAuthAuthenticate as Ge,RecoveryOAuthInit as Ke,RecoveryOAuthInitICloud as qe,RefreshSession as Je,RefreshUser as Ye,ReplaceCard as Xe,SiweAuthenticate as Ze,SiweInit as Qe,SiweLink as $e,SiweLinkSmartWallet as et,SiweUnlink as tt,SiwsAuthenticate as nt,SiwsInit as rt,SiwsLink as it,SiwsUnlink as at,TelegramAuthenticate as ot,TelegramLink as st,TelegramUnlink as ct,UpdateCard as lt,UpdateCardPin as ut,UpsertCardCustomer as dt,WalletCreate as ft,WalletGet as pt,WalletGetAction as mt,WalletListActions as ht,WalletRawSign as gt,WalletRpc as _t,WalletTransfer as vt,WalletUpdate as yt,WalletsRevoke as bt,getPathWithParams as xt}from"@privy-io/routes";import*as St from"jose";import{DEFAULT_SUPPORTED_CHAINS as Ct,arbitrum as m,arbitrumSepolia as wt,avalanche as h,avalancheFuji as Tt,base as g,baseSepolia as Et,celo as Dt,dedupeSupportedChains as Ot,mainnet as _,monadMainnet as v,optimism as y,optimismSepolia as kt,polygon as b,polygonAmoy as At,sepolia as jt}from"@privy-io/chains";import Mt from"eventemitter3";import{createPublicClient as Nt,formatEther as Pt,formatUnits as Ft,http as It,toHex as Lt}from"viem";import{STRING_TO_NUMBER_TXN_TYPE as Rt,TEMPO_TXN_TYPE_NUMBER as zt,isTempoTransactionRequest as x,normalizeViemPreparedTempoTransaction as Bt,toViemTempoTransactionSerializable as Vt,toViemTransactionSerializable as Ht}from"@privy-io/ethereum";import Ut from"canonicalize";import{encoding as S}from"@privy-io/encoding";import{tempo as C,tempoModerato as Wt}from"viem/chains";import{base58 as Gt}from"@scure/base";import{PrivyErrorCode as Kt}from"@privy-io/api-base";import{retryFetch as qt}from"@privy-io/std/retry-fetch";import Jt from"js-cookie";import Yt from"fetch-retry";import Xt from"libphonenumber-js/examples.mobile.json";import{AsYouType as Zt,getCountries as Qt,getCountryCallingCode as $t,getExampleNumber as en,isPossiblePhoneNumber as tn,parsePhoneNumberFromString as nn}from"libphonenumber-js/min";export*from"@privy-io/chains";var rn=Object.defineProperty,w=(e,t)=>{let n={};for(var r in e)rn(n,r,{get:e[r],enumerable:!0});return t||rn(n,Symbol.toStringTag,{value:`Module`}),n};function an(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}const T=e=>/^0x[0-9a-fA-F]*$/.test(e),on=e=>Buffer.from(e,`utf8`),E=e=>`0x${e.toString(`hex`)}`,sn=Symbol(`data-suffix-plugin`);function cn(e=[]){return e.find(e=>e.id===sn)}function ln(e){let t=e.startsWith(`0x`)?e:`0x${e}`;if(!T(t))throw Error(`[Privy] dataSuffix: Invalid suffix "${e}" is not valid hex`);let n=t.slice(2);return{id:sn,suffix:t,appendDataSuffix:({data:e})=>!e||e===`0x`?t:`${e}${n}`}}var un=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(he,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},D=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=St.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=(this.expiration-e)*1e3}},dn=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 D(r).isExpired())throw Error(`JWT is expired`);return r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(le,{params:{app_id:this._privyInternal.appId}})}},fn=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(bt,{})}},O=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}},k=class extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}},pn=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 mn(e){return e instanceof O||e instanceof k?e.code:`unknown_error`}const hn=e=>t=>e[mn(t)]??e.default;function gn(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}const A=e=>!!e.id&&e.recovery_method===`privy-v2`,_n=[`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 vn=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 yn=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}]`:``}`}},bn=class extends yn{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},xn=class extends Error{type;constructor(e,t){super(t),this.type=e}},Sn=class extends yn{type=`connector_error`;constructor(e,t,n){super(e,t,n)}},j=class extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}};const M={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 N(e){let t=e.type;return typeof t==`string`&&_n.includes(t)}function Cn(e){return N(e)&&e.type===`wallet_not_on_device`}function wn(e){return N(e)&&e.type===`mfa_timeout`}function Tn(e){return N(e)&&e.type===`missing_or_invalid_mfa`}function En(e){return N(e)&&e.type===`mfa_verification_max_attempts_reached`}function Dn(e){return N(e)&&e.message.includes(`code 429`)}var On=class extends bn{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(M).find(e=>e.eipCode===t.code);this.details=n||M.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=M.E32002_CONNECTION_ALREADY_PENDING:this.details=M.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=M.E32002_WALLET_LOCKED))}};async function P(e,t){let n;if(t instanceof Uint8Array)n=S.base64.fromBytes(t);else{let e=Ut(t);if(e===void 0)throw new k({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 F=`privy-request-expiry`,I=1800*1e3;async function L(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath(_t,{params:{wallet_id:n}}),o=String(Date.now()+I),{signature:s}=await P(t,{version:1,url:a,method:_t.method,headers:{"privy-app-id":e.app.appId,[F]:o},body:{...i}});if(Date.now()>Number(o))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(_t,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[F]:o,...r??{}}})}function kn(e){return x(e)?jn(e):An(e)}function An(e){return{from:e.from,to:e.to??void 0,nonce:R(e.nonce),chain_id:R(e.chainId),data:Fn(e.data),value:R(e.value),type:Ln(e.type),gas_limit:R(e.gasLimit??e.gas),gas_price:R(e.gasPrice),max_fee_per_gas:R(e.maxFeePerGas),max_priority_fee_per_gas:R(e.maxPriorityFeePerGas)}}function jn(e){return{type:zt,from:e.from,chain_id:R(e.chainId),nonce:R(e.nonce),nonce_key:R(e.nonceKey),gas_limit:R(e.gasLimit),max_fee_per_gas:R(e.maxFeePerGas),max_priority_fee_per_gas:R(e.maxPriorityFeePerGas),fee_token:e.feeToken,valid_after:R(e.validAfter),valid_before:R(e.validBefore),fee_payer_signature:Nn(e.feePayerSignature),access_list:Mn(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:R(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 Nn(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 Fn(e){if(e!==void 0)return typeof e==`string`?T(e)?e:E(on(e)):E(Buffer.from(Uint8Array.from(e)))}const In=[0,1,2,4];function Ln(e){if(e==null)return;let t=Number(e);if(!Rn(t))throw Error(`Invalid transaction type: expected ${In.join(`, `)} as a number or hex string, got "${e}".`);return t}function Rn(e){return In.includes(e)}function R(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(T(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 zn(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 Bn({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return Vn({context:e,account:t,rpcRequest:n.request});case`solana`:return Hn({context:e,account:t,rpcRequest:n.request})}}async function Vn({context:e,account:t,rpcRequest:n}){switch(n.method){case`personal_sign`:{let[r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:`personal_sign`,wallet_id:t.id,params:r.startsWith(`0x`)?{message:r.slice(2),encoding:`hex`}:{message:r,encoding:`utf-8`}});if(i.method!==`personal_sign`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`eth_signTransaction`:{let[r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:`eth_signTransaction`,wallet_id:t.id,params:{transaction:kn(r)}});if(i.method!==`eth_signTransaction`)throw Error(`Unable to sign transaction`);return{data:i.data.signed_transaction}}case`eth_signTypedData_v4`:{let[,r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:n.method,wallet_id:t.id,params:{typed_data:zn(r)}});if(i.method!==`eth_signTypedData_v4`)throw Error(`Unable to sign typed data`);return{data:i.data.signature}}case`eth_sign`:{let[,r]=n.params,i=await L(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:T(r)?r:E(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 L(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:T(r)?r:E(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 Hn({context:e,account:t,rpcRequest:n}){switch(n.method){case`signMessage`:{let{message:r}=n.params,i=await L(e,e.signRequest,{chain_type:`solana`,method:`signMessage`,wallet_id:t.id,params:{message:r,encoding:`base64`}});if(i.method!==`signMessage`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`signTransaction`:{let{transaction:r}=n.params,i=await L(e,e.signRequest,{chain_type:`solana`,method:`signTransaction`,wallet_id:t.id,params:{transaction:r,encoding:`base64`}});if(i.method!==`signTransaction`)throw Error(`Unable to sign transaction`);return{data:i.data.signed_transaction}}}}const Un=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new Sn(`Unsupported chainId ${e}`,4901);let o=Gn(a,n,r.appId);if(i===C.id||i===Wt.id){let e=i===C.id?C:Wt;return Nt({transport:It(o),chain:e})}return Nt({transport:It(o),chain:a})};function Wn(e){return e===C.id||e===Wt.id}const Gn=(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 Sn(`No RPC url found for ${r}`);return a};function Kn({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 qn=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var Jn=class extends Mt{_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=Un(s,a,{rpcUrls:[]},{appId:c.appId}),this._appApi=c,this._dataSuffixPlugin=l}async request(e){if(qn.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||x(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=Un(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=Vt(t),n=Bt(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:zt}}let n=Ht(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:Rt[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]=Lt(n))}return x(t)&&(t.calls=t.calls.map(e=>({...e,value:typeof e.value==`bigint`?Lt(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=Vt(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=Ht(n);return await this._client.estimateGas({account:n.from??this._account.address,...r})}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new j(`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 j(`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`);let n=this._account;if(A(n)){let{data:r}=await Bn({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=Cn(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 k({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 k({code:`embedded_wallet_request_error`,error:n})}}async handleJsonRpc(e){return this._client.request(e)}requireTempoClient(){if(!Wn(this._chainId))throw new j(`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 Yn(e){return`version`in e}function Xn(e,t){let n=(Yn(e)?e.message:e.compileMessage()).staticAccountKeys.find(e=>e.toBase58()===t);if(!n)throw Error(`Transaction does not contain public key ${t}`);return n}function Zn({transaction:e,address:t}){let{messageBytes:n,signerAddresses:r}=$n(e),i=r.indexOf(t);if(i===-1)throw Error(`Transaction does not require a signature from ${t}`);return{messageBytes:new Uint8Array(n),signerIndex:i}}function Qn({transaction:e,signerIndex:t,signature:n}){if(n.length!==64)throw Error(`Solana signatures must be 64 bytes`);let{signaturesOffset:r,signerAddresses:i}=$n(e);if(!Number.isInteger(t)||t<0||t>=i.length)throw Error(`Invalid signer index ${t}`);let a=new Uint8Array(e);return a.set(n,r+t*64),a}function $n(e){if(e.length===0)throw Error(`Cannot decode an empty Solana transaction`);return e[0]===129?er(e):tr(e)}function er(e){let t=z(e,1),n=e.length-t*64;if(n<=41)throw Error(`Malformed V1 Solana transaction`);let r=e.subarray(0,n);if(z(r,41)<t)throw Error(`Malformed V1 Solana transaction`);return{messageBytes:r,signaturesOffset:n,signerAddresses:rr(r,42,t)}}function tr(e){let[t,n]=nr(e,0),r=n+t*64,i=z(e,r),a=r;if(i&128){let e=i&-129;if(e!==0)throw Error(`Unsupported Solana transaction version ${e}`);a+=1}let o=z(e,a);if(o!==t)throw Error(`Solana transaction signature count does not match its message header`);let[s,c]=nr(e,a+3);if(s<o)throw Error(`Malformed Solana transaction`);return{messageBytes:e.subarray(r),signaturesOffset:n,signerAddresses:rr(e,c,o)}}function z(e,t){let n=e[t];if(n===void 0)throw Error(`Malformed Solana transaction`);return n}function nr(e,t){let n=0;for(let r=0;r<3;r++){let i=z(e,t+r);if(n|=(i&127)<<7*r,!(i&128))return[n,t+r+1]}throw Error(`Malformed Solana transaction`)}function rr(e,t,n){if(t+n*32>e.length)throw Error(`Malformed Solana transaction`);return Array.from({length:n},(n,r)=>Gt.encode(e.subarray(t+r*32,t+(r+1)*32)))}var ir=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 k({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=Cn(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 k({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}}walletRpcContext(e){return{app:this._app,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:t})=>this._proxy.signWithUserSigner({accessToken:e,message:t})}}async signMessageRpc(e,t){let n=this._account;if(A(n)){let{data:r}=await Bn({context:this.walletRpcContext(t),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 signSerializedTransaction(e,t){let n=this._account;if(A(n)){let{data:r}=await Bn({context:this.walletRpcContext(t),account:n,rpcRequest:{chainType:`solana`,request:{method:`signTransaction`,params:{transaction:S.base64.fromBytes(e)}}}});return new Uint8Array(S.base64.toBytes(r))}let{messageBytes:r,signerIndex:i}=Zn({transaction:e,address:n.address}),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:S.base64.fromBytes(r)}},t);return Qn({transaction:e,signerIndex:i,signature:S.base64.toBytes(a)})}async signTransactionObject(e,t){if(Yn(e)&&e.version===1)throw Error(`V1 transactions cannot be serialized by web3.js. Pass the serialized transaction as a Uint8Array instead.`);let n=Xn(e,this._account.address),r=Yn(e)?Buffer.from(e.message.serialize()):e.serializeMessage(),{signature:i}=await this.signMessageRpc({method:`signMessage`,params:{message:r.toString(`base64`)}},t);e.addSignature(n,Buffer.from(i,`base64`))}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.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 k({code:`embedded_wallet_request_error`,error:n})}}async handleSignAndSendTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.connectAndRecover(t);let{transaction:n,connection:r,options:i}=e.params,a;return n instanceof Uint8Array?a=await this.signSerializedTransaction(n,t):(await this.signTransactionObject(n,t),a=n.serialize()),{signature:await r.sendRawTransaction(a,i)}}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new k({code:`embedded_wallet_request_error`,error:n})}}async handleSignTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.connectAndRecover(t);let{transaction:n}=e.params;return n instanceof Uint8Array?{signedTransaction:await this.signSerializedTransaction(n,t)}:(await this.signTransactionObject(n,t),{signedTransaction:n})}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.wallet_index,error:n}),new k({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},ar=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(A(this._account))throw new k({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 k({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return this.handleIFrameRpc(e)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing access token. User must be authenticated.`);return(await this._proxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:this._account.chain_type})).response.data}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new k({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedBitcoinProvider { address: '${this._account.address}', request: [Function] }`}},or=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 sr(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new xn(`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 xn(`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 xn(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function cr(e){return e.error!==void 0}const lr=(function(e){return()=>`id-${e++}`})(0),ur=(e,t)=>typeof t==`bigint`?t.toString():t,dr=(e,t)=>`${e}${JSON.stringify(t,ur)}`,B=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)}},fr=new or;var pr=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 B(sr(n=>B(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,fr.flush(Error(`Embedded wallet WebView was reloaded`)),this.cache.clear(),this._embeddedWalletMessagePoster.reload()}onBackground(){this.ready=!1}ping(e=15e3){return B(this.invoke(`privy:iframe:ready`,{}),{msg:`Ping reached timeout`,ms:e})}create(e){return B(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 B(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`}):B(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 B(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 B(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 B(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=fr.dequeue(e.event,e.id);if(t)return cr(e)?t.reject(new xn(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=dr(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=lr();fr.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 mr(e,{request:t,headers:n}){return await e.fetchPrivyRoute(ft,{body:t,headers:n})}async function hr({context:e,chainType:t,idempotencyKey:n}){return{wallet:await mr(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}var gr=class{_privyInternal;_proxy;_chains=Array.from(Ct);_mfa;_mfaPromises;_appApi;_dataSuffixPlugin;constructor(e,t,n,r,i,a,o){if(this._privyInternal=e,t&&(this._proxy=new pr(t,i),r.setProxy(this._proxy)),n){let e=Ot(n);this._chains=e}this._mfa=r,this._mfaPromises=i,this._appApi=a,this._dataSuffixPlugin=o}setMessagePoster(e){this._proxy=new pr(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 k({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 hr({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:e.chainType});else{if(!e.entropyId)throw new k({error:`Missing entropy details for wallet creation`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new k({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 A(e)||await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new ar({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 k({error:`User-controlled server wallets do not support custom recovery methods`,code:`embedded_wallet_creation_error`});await hr({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 k({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 k({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 k({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 k({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 hr({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 k({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 k({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 k({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new k({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 A(e)||await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new Jn({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 A(e)||(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new Jn({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 k({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return A(e)||(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new ir({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(A(t))throw new k({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});Kn({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 Jn({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(Cn(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}}},_r=class extends Mt{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const vr=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let yr=!1;const br=()=>{if(yr)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;yr=typeof t==`string`&&t.length>0||typeof n==`string`&&vr.includes(n)}catch{yr=!0}return yr},V={get(e){return Jt.get(e)},set(e,t,n){br()||Jt.set(e,t,n)},remove(e){Jt.remove(e)}},xr=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!br(),Sr=`privy:active-user`,Cr=`privy:saved-users`,H=e=>e?`privy:${e}:token`:`privy:token`,U=e=>e?`privy:${e}:pat`:`privy:pat`,W=e=>e?`privy:${e}:refresh_token`:`privy:refresh_token`,G=e=>e?`privy:${e}:id-token`:`privy:id-token`,wr=e=>e?`privy-${e}-token`:`privy-token`,Tr=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,Er=e=>e?`privy-${e}-id-token`:`privy-id-token`,K=e=>e?`privy-${e}-session`:`privy-session`,q=Promise.allSettled.bind(Promise)??(e=>Promise.all(e.map(e=>e.then(e=>({status:`fulfilled`,value:e})).catch(e=>({status:`rejected`,reason:e}))))),Dr=[`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 Or=class extends Mt{static events=Dr;_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 xr({useServerCookies:this._isUsingServerCookies,cookieWriteBehavior:this._cookieWriteBehavior})}writeCookie(e,t,n){this.shouldWriteCookies()&&V.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(H(e));try{return typeof t==`string`?new D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(U(e));try{return typeof t==`string`?new D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async getRefreshToken(){let e=await this.getActiveUserId(),t=await this._storage.get(W(e));return typeof t==`string`?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(G(e));return typeof t==`string`?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=V.get(K(e));if(t!==void 0&&t.length>0)return!0;let n=V.get(K(null));return n!==void 0&&n.length>0}catch(e){console.error(e)}return!1}async hasRefreshCredentials(e,t){return await this.mightHaveServerCookies()||typeof e==`string`&&typeof t==`string`}tokenIsActive(e){if(!e)return!1;let t=D.parse(e);return t!==null&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),n=[this._storage.del(H(null)),this._storage.del(U(null)),this._storage.del(W(null)),this._storage.del(G(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(Sr)];t&&n.push(this._storage.del(H(t)),this._storage.del(U(t)),this._storage.del(W(t)),this._storage.del(G(t)),this.removeSavedUserId(t)),await q(n),V.remove(wr(null)),V.remove(Tr(null)),V.remove(Er(null)),V.remove(K(null)),t&&(V.remove(wr(t)),V.remove(Tr(t)),V.remove(Er(t)),V.remove(K(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=H(e),r=wr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),V.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=U(e);typeof t==`string`?await this._storage.put(n,t):await this._storage.del(n)}async storeRefreshTokenForUser(e,t){let n=W(e),r=Tr(e),i=K(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),V.remove(r),V.remove(i),this.emit(`refresh_token_cleared`,{reason:`set_with_non_string_value`}))}async updateWithTokensResponse(e){let t=e.user.id,n=(await q([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 q([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 q([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(H(null)),this._storage.get(U(null)),this._storage.get(W(null)),this._storage.get(G(null))]);if(typeof e!=`string`||typeof n!=`string`)return;let i=D.parse(e)?.subject;if(typeof i!=`string`||i.length===0)return;let a=[this.storeCustomerAccessTokenForUser(i,e),this.storeRefreshTokenForUser(i,n)];typeof t==`string`&&a.push(this.storePrivyAccessTokenForUser(i,t)),typeof r==`string`&&a.push(this.storeIdentityTokenForUser(i,r));let o=(await q(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=G(e),r=Er(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`identity_token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),V.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=S.base64urlnopad.fromBytes(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(Sr);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(Sr,e)}async getSavedUserIds(){let e=await this._storage.get(Cr);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(Cr,JSON.stringify(t)):await this._storage.del(Cr),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 k({code:`invalid_input`,error:`Cannot switch active user because the user ID is not saved on this device`});await this._storage.put(Sr,e)}};const kr=e=>{let t=new AbortController,n=e.filter(e=>!!e),r=()=>{for(let e of n)e.removeEventListener(`abort`,r);t.abort(n.find(e=>e.aborted)?.reason)};if(n.some(e=>e.aborted))r();else for(let e of n)e.addEventListener(`abort`,r);return t.signal},Ar=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function jr(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 Mr=()=>void 0,J={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},Nr=({level:e,logger:t})=>({get level(){return e},error:J[e]>=J.ERROR?t.error:Mr,warn:J[e]>=J.WARN?t.warn:Mr,info:J[e]>=J.INFO?t.info:Mr,debug:J[e]>=J.DEBUG?t.debug:Mr}),Pr=`privy:caid`;var Fr=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.78.1`;_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 Or({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=qt(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 k({code:`storage_error`,error:`Unable to access storage`});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.isMultiUserModeEnabled&&await this.session.backfillLegacySession(),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith(`js-sdk-core:`)&&this.createAnalyticsEvent(`sdk_initialize`,{})}getPath(e,{params:t,query:n}){return`${this.baseUrl}${xt(e.path,t)}${jr(n)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new k({code:`invalid_input`,error:`Unauthenticated requests require sessions.mode to be set to "multi-user"`});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:n,query:r,headers:i,signal:a,onRequest:o=this._beforeRequest.bind(this)}){let s=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),c=await o(s);a&&(c.signal=kr([a,c.signal]));let l=await this._fetch(s,c),u=await l.json();if(l.status>299)throw new O({...u,status:l.status});return u}async fetchRaw(e,{body:t,params:n,query:r,headers:i,onRequest:a=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),s=await a(o),c=await this._fetch(o,s);if(c.status>299)throw new O({...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:Ar(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:Ar(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(r,{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(Pr);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(Pr,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(Pr)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,t){try{await this.fetch(n,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch{}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new k({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 O({code:Kt.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});try{this.logger.debug(`[privy:refresh] fetching: ${Je.path}`);let n=await this.fetch(Je,{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 O&&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}}},Ir=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(t,{})}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(Ye,{});return await this._privyInternal.session.storeIdentityToken(t),this._privyInternal.callbacks?.setUser?.(e),{user:e}}async switchActiveUser(e){if(!this._isMultiUserModeEnabled)throw new k({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 k({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 Lr=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`,Rr=e=>e?e.linked_accounts.filter(Lr).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],Y=e=>Rr(e).find(e=>e.wallet_index===0)??null,zr=Y,Br=e=>e?e.linked_accounts.filter(Lr).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],Vr=e=>Br(e).find(e=>e.wallet_index===0)??null,Hr=(e,t)=>t===`off`||Rr(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,Ur=(e,t)=>t===`off`||Br(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,Wr=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),X=async(e,t,n)=>{let r=Hr(t.user,n?.ethereum?.createOnLogin??`off`),i=Ur(t.user,n?.solana?.createOnLogin??`off`);if(r&&i){let n=await e.create({recoveryMethod:`privy`,skipCallbacks:!0}),r=await e.createSolana({ethereumAccount:Y(n.user)??void 0});return Wr(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:Vr(t.user)??void 0});return Wr(n,t)}if(i){let n=await e.createSolana({ethereumAccount:Y(t.user)??void 0});return Wr(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(u,{body:{token:e,mode:n}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await X(this._embedded,r,t?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithToken(e){await this._privyInternal.fetch(d,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Kr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Pe,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Ne,{body:{email:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await X(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Fe,{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(He,{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(Ve,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},qr=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(te,{body:{relying_party:e,redirect_url:t,token:n}})}async getFarcasterStatus({channel_token:e}){return await this._privyInternal.fetch(ne,{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(f,{body:{channel_token:e,message:t,signature:n,fid:r,mode:i}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await X(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(p,{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(re,{body:{fid:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Jr=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(ae,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(ie,{body:{message:e,signature:t,fid:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await X(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}},Yr=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(ge,{body:{guest_credential:t}});await this._privyInternal.session.updateWithTokensResponse(n);let r=await X(this._embedded,n,e?.embedded);return this._privyInternal.callbacks?.setUser?.(r.user),r}};const Z=`privy:state_code`,Q=`privy:code_verifier`;async function Xr(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function Zr(e){return crypto.getRandomValues(new Uint8Array(e))}function Qr(){return S.base64urlnopad.fromBytes(Zr(36))}function $r(){return Qr()}async function ei({codeVerifier:e,method:t=`S256`,digest:n}){if(t==`S256`){let t=await Xr(e,n);return S.base64urlnopad.fromBytes(t)}else return e}var ti=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=Qr(),r=$r(),i=await ei({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put(Q,n),this._storage.put(Z,r)]),this._privyInternal.fetchForLogin(we,{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(Q),this._storage.get(Z)]);if(s!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:s??``,returnedStateCode:t??``}),new k({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let c=await this._privyInternal.fetchForLogin(Ce,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let l=await X(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del(Q),this._storage.del(Z)]),this._privyInternal.callbacks?.setUser?.(l.user),l}async linkWithCode(e,t,n,r){let[i,a]=await Promise.all([this._storage.get(Q),this._storage.get(Z)]);if(a!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:a??``,returnedStateCode:t??``}),new k({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let o=await this._privyInternal.fetch(Te,{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(Q),this._storage.del(Z)]),{user:s.user,identity_token:s.identity_token}}async unlink(e,t){await this._privyInternal.fetch(Ee,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},ni=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(Ae,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(Oe,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(Me,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(De,{body:{relying_party:n,challenge:t,authenticator_response:this._transformAuthenticationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await X(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async signupWithPasskey(e,t,n){let r=await this._privyInternal.fetchForLogin(je,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await X(this._embedded,r,n?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithPasskey(e,t){await this._privyInternal.fetch(ke,{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}}}},ri=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Le,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Ie,{body:{phoneNumber:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await X(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Re,{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(Be,{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(ze,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},ii=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(tt,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}async linkWithSiwe(e,t,n){let r=t||this._wallet,i=n||this._preparedMessage;if(!r)throw Error(`A wallet must be provided in the init step or as an argument to linkWithSiwe`);if(!i)throw Error(`A message must be generated and signed before being used to link a wallet to privy`);await this._privyInternal.fetch($e,{body:{message:i,signature:e,chainId:r.chainId,walletClientType:r.walletClientType??null,connectorType:r.connectorType??null}});let a=await this._privyInternal.refreshSession();return{user:a.user,identity_token:a.identity_token}}async loginWithSiwe(e,t,n,r,i){let a=t||this._wallet,o=n||this._preparedMessage;if(!a)throw Error(`A wallet must be provided in the init step or as an argument to loginWithSiwe`);if(!o)throw Error(`A message must be generated and signed before being used to login to privy with a wallet`);let s=await this._privyInternal.fetchForLogin(Ze,{body:{signature:e,message:o,chainId:a.chainId,walletClientType:a.walletClientType??null,connectorType:a.connectorType??null,mode:r}});await this._privyInternal.session.updateWithTokensResponse(s);let c=await X(this._embedded,s,i?.embedded);return this._privyInternal.callbacks?.setUser?.(c.user),c}async init(e,t,n){this._wallet=e;let{nonce:r}=await this._privyInternal.fetch(Qe,{body:{address:e.address}}),i=ai({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 ai(e){return`${e.domain} wants you to sign in with your Ethereum account:
|
|
1
|
+
import{AcceptCardConsents as e,AcceptTermsOnUser as t,AnalyticsEvent as n,AppConfig as r,CoinbaseOnRampInit as i,CoinbaseOnRampStatus as a,CreateCard as o,CreateCryptoDepositAccount as s,CreateCryptoDepositAccountQuote as c,CreateDepositAddressQuote as l,CustomJWTAuthenticate as u,CustomJWTLink as d,DownloadCardStatement as f,FarcasterAuthenticate as p,FarcasterInit as m,FarcasterLink as h,FarcasterStatus as ee,FarcasterUnlink as te,FarcasterV2Authenticate as ne,FarcasterV2Init as re,GetCardCustomer as ie,GetCardEphemeralKey as ae,GetCardsConfig as oe,GetCrossAppConnections as se,GetCryptoDepositAccountNextOrder as ce,GetCryptoDepositAccountOrder as le,GetDepositAddressOrder as ue,GetDepositConfig as de,GetNextDepositAddressOrder as fe,GetSmartWalletConfig as pe,GuestAuthenticate as me,ListCardTransactions as he,ListCards as ge,Logout as _e,MfaPasskeyInit as ve,MfaPasswordlessSmsInit as ye,MoonpayOnRampSign as be,OAuthAuthenticate as xe,OAuthInit as Se,OAuthLink as Ce,OAuthUnlink as we,PasskeyAuthenticate as Te,PasskeyAuthenticateInit as Ee,PasskeyLink as De,PasskeyLinkInit as Oe,PasskeyRegister as ke,PasskeyRegisterInit as Ae,PasswordlessAuthenticate as je,PasswordlessInit as Me,PasswordlessLink as Ne,PasswordlessSmsAuthenticate as Pe,PasswordlessSmsInit as Fe,PasswordlessSmsLink as Ie,PasswordlessSmsUnlink as Le,PasswordlessSmsUpdate as Re,PasswordlessUnlink as ze,PasswordlessUpdate as Be,RecoveryConfigurationICloud as Ve,RecoveryKeyMaterial as He,RecoveryOAuthAuthenticate as Ue,RecoveryOAuthInit as We,RecoveryOAuthInitICloud as Ge,RefreshSession as Ke,RefreshUser as qe,ReplaceCard as Je,SearchCryptoDepositAccountConfig as Ye,SiweAuthenticate as Xe,SiweInit as Ze,SiweLink as Qe,SiweLinkSmartWallet as $e,SiweUnlink as et,SiwsAuthenticate as tt,SiwsInit as nt,SiwsLink as rt,SiwsUnlink as it,TelegramAuthenticate as at,TelegramLink as ot,TelegramUnlink as st,UpdateCard as ct,UpdateCardPin as lt,UpsertCardCustomer as ut,WalletCreate as dt,WalletGet as ft,WalletGetAction as pt,WalletListActions as mt,WalletRawSign as ht,WalletRpc as gt,WalletTransfer as _t,WalletUpdate as vt,WalletsRevoke as yt,getPathWithParams as bt}from"@privy-io/routes";import*as xt from"jose";import{DEFAULT_SUPPORTED_CHAINS as St,arbitrum as g,arbitrumSepolia as Ct,avalanche as _,avalancheFuji as wt,base as v,baseSepolia as Tt,celo as Et,dedupeSupportedChains as Dt,mainnet as y,monadMainnet as b,optimism as x,optimismSepolia as Ot,polygon as S,polygonAmoy as kt,sepolia as At}from"@privy-io/chains";import jt from"eventemitter3";import{concat as Mt,createPublicClient as Nt,decodeAbiParameters as Pt,decodeFunctionResult as Ft,encodeFunctionData as It,erc20Abi as Lt,formatEther as Rt,formatUnits as zt,http as Bt,isHex as Vt,maxUint256 as Ht,stringToHex as Ut,toHex as Wt,zeroAddress as Gt}from"viem";import{STRING_TO_NUMBER_TXN_TYPE as Kt,TEMPO_TXN_TYPE_NUMBER as qt,isTempoTransactionRequest as C,normalizeViemPreparedTempoTransaction as Jt,toViemTempoTransactionSerializable as Yt,toViemTransactionSerializable as Xt}from"@privy-io/ethereum";import Zt from"canonicalize";import{encoding as w}from"@privy-io/encoding";import{tempo as Qt,tempoModerato as $t}from"viem/chains";import{base58 as en}from"@scure/base";import{PrivyErrorCode as tn}from"@privy-io/api-base";import{retryFetch as nn}from"@privy-io/std/retry-fetch";import rn from"js-cookie";import an from"fetch-retry";import on from"libphonenumber-js/examples.mobile.json";import{AsYouType as sn,getCountries as cn,getCountryCallingCode as ln,getExampleNumber as un,isPossiblePhoneNumber as dn,parsePhoneNumberFromString as fn}from"libphonenumber-js/min";export*from"@privy-io/chains";var pn=Object.defineProperty,T=(e,t)=>{let n={};for(var r in e)pn(n,r,{get:e[r],enumerable:!0});return t||pn(n,Symbol.toStringTag,{value:`Module`}),n};function mn(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}const E=e=>/^0x[0-9a-fA-F]*$/.test(e),hn=e=>Buffer.from(e,`utf8`),gn=e=>`0x${e.toString(`hex`)}`,_n=Symbol(`data-suffix-plugin`);function vn(e=[]){return e.find(e=>e.id===_n)}function yn(e){let t=e.startsWith(`0x`)?e:`0x${e}`;if(!E(t))throw Error(`[Privy] dataSuffix: Invalid suffix "${e}" is not valid hex`);let n=t.slice(2);return{id:_n,suffix:t,appendDataSuffix:({data:e})=>!e||e===`0x`?t:`${e}${n}`}}var bn=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(pe,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},D=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=xt.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}},xn=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 D(r).isExpired())throw Error(`JWT is expired`);return r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(se,{params:{app_id:this._privyInternal.appId}})}},Sn=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(yt,{})}},O=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}},k=class extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}},Cn=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 wn(e){return e instanceof O||e instanceof k?e.code:`unknown_error`}const Tn=e=>t=>e[wn(t)]??e.default;function En(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}const A=e=>!!e.id&&e.recovery_method===`privy-v2`,Dn=[`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 On=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 kn=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}]`:``}`}},An=class extends kn{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},jn=class extends Error{type;constructor(e,t){super(t),this.type=e}},Mn=class extends kn{type=`connector_error`;constructor(e,t,n){super(e,t,n)}},Nn=class extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}};const j={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 Pn(e){let t=e.type;return typeof t==`string`&&Dn.includes(t)}function Fn(e){return Pn(e)&&e.type===`wallet_not_on_device`}function In(e){return Pn(e)&&e.type===`mfa_timeout`}function Ln(e){return Pn(e)&&e.type===`missing_or_invalid_mfa`}function Rn(e){return Pn(e)&&e.type===`mfa_verification_max_attempts_reached`}function zn(e){return Pn(e)&&e.message.includes(`code 429`)}var Bn=class extends An{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(j).find(e=>e.eipCode===t.code);this.details=n||j.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=j.E32002_CONNECTION_ALREADY_PENDING:this.details=j.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=j.E32002_WALLET_LOCKED))}};async function M(e,t){let n;if(t instanceof Uint8Array)n=w.base64.fromBytes(t);else{let e=Zt(t);if(e===void 0)throw new k({error:`Failed to prepare the payload for signing`,code:`invalid_input`});n=w.base64.fromBytes(w.utf8.toBytes(e))}let{signature:r}=await e({message:n});return{signature:r}}const N=`privy-request-expiry`,Vn=1800*1e3;async function P(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath(gt,{params:{wallet_id:n}}),o=String(Date.now()+Vn),{signature:s}=await M(t,{version:1,url:a,method:gt.method,headers:{"privy-app-id":e.app.appId,[N]:o},body:{...i}});if(Date.now()>Number(o))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(gt,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[N]:o,...r??{}}})}function Hn(e){return C(e)?Wn(e):Un(e)}function Un(e){return{from:e.from,to:e.to??void 0,nonce:F(e.nonce),chain_id:F(e.chainId),data:Jn(e.data),value:F(e.value),type:Xn(e.type),gas_limit:F(e.gasLimit??e.gas),gas_price:F(e.gasPrice),max_fee_per_gas:F(e.maxFeePerGas),max_priority_fee_per_gas:F(e.maxPriorityFeePerGas)}}function Wn(e){return{type:qt,from:e.from,chain_id:F(e.chainId),nonce:F(e.nonce),nonce_key:F(e.nonceKey),gas_limit:F(e.gasLimit),max_fee_per_gas:F(e.maxFeePerGas),max_priority_fee_per_gas:F(e.maxPriorityFeePerGas),fee_token:e.feeToken,valid_after:F(e.validAfter),valid_before:F(e.validBefore),fee_payer_signature:Kn(e.feePayerSignature),access_list:Gn(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:F(e.value)}))}}function Gn(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 Kn(e){if(!e)return;let t=qn(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 qn(e){if(e.yParity!==void 0)return e.yParity;if(e.v!==void 0)return Number(e.v)-27}function Jn(e){if(e!==void 0)return typeof e==`string`?E(e)?e:gn(hn(e)):gn(Buffer.from(Uint8Array.from(e)))}const Yn=[0,1,2,4];function Xn(e){if(e==null)return;let t=Number(e);if(!Zn(t))throw Error(`Invalid transaction type: expected ${Yn.join(`, `)} as a number or hex string, got "${e}".`);return t}function Zn(e){return Yn.includes(e)}function F(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(E(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 Qn(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 $n({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return er({context:e,account:t,rpcRequest:n.request});case`solana`:return tr({context:e,account:t,rpcRequest:n.request})}}async function er({context:e,account:t,rpcRequest:n}){switch(n.method){case`personal_sign`:{let[r]=n.params,i=await P(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 P(e,e.signRequest,{chain_type:`ethereum`,method:`eth_signTransaction`,wallet_id:t.id,params:{transaction:Hn(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 P(e,e.signRequest,{chain_type:`ethereum`,method:n.method,wallet_id:t.id,params:{typed_data:Qn(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 P(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:E(r)?r:gn(hn(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 P(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:E(r)?r:gn(hn(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 tr({context:e,account:t,rpcRequest:n}){switch(n.method){case`signMessage`:{let{message:r}=n.params,i=await P(e,e.signRequest,{chain_type:`solana`,method:`signMessage`,wallet_id:t.id,params:{message:r,encoding:`base64`}});if(i.method!==`signMessage`)throw Error(`Unable to sign message`);return{data:i.data.signature}}case`signTransaction`:{let{transaction:r}=n.params,i=await P(e,e.signRequest,{chain_type:`solana`,method:`signTransaction`,wallet_id:t.id,params:{transaction:r,encoding:`base64`}});if(i.method!==`signTransaction`)throw Error(`Unable to sign transaction`);return{data:i.data.signed_transaction}}}}const nr=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new Mn(`Unsupported chainId ${e}`,4901);let o=ir(a,n,r.appId);if(i===Qt.id||i===$t.id){let e=i===Qt.id?Qt:$t;return Nt({transport:Bt(o),chain:e})}return Nt({transport:Bt(o),chain:a})};function rr(e){return e===Qt.id||e===$t.id}const ir=(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 Mn(`No RPC url found for ${r}`);return a};function ar({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 or=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var sr=class extends jt{_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=nr(s,a,{rpcUrls:[]},{appId:c.appId}),this._appApi=c,this._dataSuffixPlugin=l}async request(e){if(or.has(e.method))return this.handleIFrameRpc(e);switch(e.method){case`eth_accounts`:case`eth_requestAccounts`:return this._account.address?[this._account.address]:[];case`eth_chainId`:return`0x${this._chainId.toString(16)}`;case`wallet_switchEthereumChain`:return this.handleSwitchEthereumChain(e);case`eth_estimateGas`:return this.handleEstimateGas(e);case`eth_signTransaction`:{let t=this.applyDataSuffix(e.params?.[0]);return this.handleSignTransaction(t)}case`eth_sendTransaction`:{let t=this.applyDataSuffix(e.params?.[0]);return this.handleSendTransaction(t)}case`eth_populateTransactionRequest`:{let t=e.params?.[0];return this.handlePopulateTransaction(t)}default:return this.handleJsonRpc(e)}}applyDataSuffix(e){if(!this._dataSuffixPlugin||C(e))return e;let t=typeof e.data==`string`?e.data:`0x`;return{...e,data:this._dataSuffixPlugin.appendDataSuffix({data:t})}}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=nr(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit(`chainChanged`,e))}async handlePopulateTransaction(e){let t=this.ensureChainId(e);if(C(t)){let e=Yt(t),n=Jt(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:qt}}let n=Xt(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:Kt[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]=Wt(n))}return C(t)&&(t.calls=t.calls.map(e=>({...e,value:typeof e.value==`bigint`?Wt(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(C(n)){let e=Yt(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=Xt(n);return await this._client.estimateGas({account:n.from??this._account.address,...r})}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new Nn(`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 Nn(`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`);let n=this._account;if(A(n)){let{data:r}=await $n({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=Fn(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 k({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 k({code:`embedded_wallet_request_error`,error:n})}}async handleJsonRpc(e){return this._client.request(e)}requireTempoClient(){if(!rr(this._chainId))throw new Nn(`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 cr(e){return`version`in e}function lr(e,t){let n=(cr(e)?e.message:e.compileMessage()).staticAccountKeys.find(e=>e.toBase58()===t);if(!n)throw Error(`Transaction does not contain public key ${t}`);return n}function ur({transaction:e,address:t}){let{messageBytes:n,signerAddresses:r}=fr(e),i=r.indexOf(t);if(i===-1)throw Error(`Transaction does not require a signature from ${t}`);return{messageBytes:new Uint8Array(n),signerIndex:i}}function dr({transaction:e,signerIndex:t,signature:n}){if(n.length!==64)throw Error(`Solana signatures must be 64 bytes`);let{signaturesOffset:r,signerAddresses:i}=fr(e);if(!Number.isInteger(t)||t<0||t>=i.length)throw Error(`Invalid signer index ${t}`);let a=new Uint8Array(e);return a.set(n,r+t*64),a}function fr(e){if(e.length===0)throw Error(`Cannot decode an empty Solana transaction`);return e[0]===129?pr(e):mr(e)}function pr(e){let t=I(e,1),n=e.length-t*64;if(n<=41)throw Error(`Malformed V1 Solana transaction`);let r=e.subarray(0,n);if(I(r,41)<t)throw Error(`Malformed V1 Solana transaction`);return{messageBytes:r,signaturesOffset:n,signerAddresses:gr(r,42,t)}}function mr(e){let[t,n]=hr(e,0),r=n+t*64,i=I(e,r),a=r;if(i&128){let e=i&-129;if(e!==0)throw Error(`Unsupported Solana transaction version ${e}`);a+=1}let o=I(e,a);if(o!==t)throw Error(`Solana transaction signature count does not match its message header`);let[s,c]=hr(e,a+3);if(s<o)throw Error(`Malformed Solana transaction`);return{messageBytes:e.subarray(r),signaturesOffset:n,signerAddresses:gr(e,c,o)}}function I(e,t){let n=e[t];if(n===void 0)throw Error(`Malformed Solana transaction`);return n}function hr(e,t){let n=0;for(let r=0;r<3;r++){let i=I(e,t+r);if(n|=(i&127)<<7*r,!(i&128))return[n,t+r+1]}throw Error(`Malformed Solana transaction`)}function gr(e,t,n){if(t+n*32>e.length)throw Error(`Malformed Solana transaction`);return Array.from({length:n},(n,r)=>en.encode(e.subarray(t+r*32,t+(r+1)*32)))}var _r=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 k({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=Fn(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 k({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}}walletRpcContext(e){return{app:this._app,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:t})=>this._proxy.signWithUserSigner({accessToken:e,message:t})}}async signMessageRpc(e,t){let n=this._account;if(A(n)){let{data:r}=await $n({context:this.walletRpcContext(t),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 signSerializedTransaction(e,t){let n=this._account;if(A(n)){let{data:r}=await $n({context:this.walletRpcContext(t),account:n,rpcRequest:{chainType:`solana`,request:{method:`signTransaction`,params:{transaction:w.base64.fromBytes(e)}}}});return new Uint8Array(w.base64.toBytes(r))}let{messageBytes:r,signerIndex:i}=ur({transaction:e,address:n.address}),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:w.base64.fromBytes(r)}},t);return dr({transaction:e,signerIndex:i,signature:w.base64.toBytes(a)})}async signTransactionObject(e,t){if(cr(e)&&e.version===1)throw Error(`V1 transactions cannot be serialized by web3.js. Pass the serialized transaction as a Uint8Array instead.`);let n=lr(e,this._account.address),r=cr(e)?Buffer.from(e.message.serialize()):e.serializeMessage(),{signature:i}=await this.signMessageRpc({method:`signMessage`,params:{message:r.toString(`base64`)}},t);e.addSignature(n,Buffer.from(i,`base64`))}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.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 k({code:`embedded_wallet_request_error`,error:n})}}async handleSignAndSendTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.connectAndRecover(t);let{transaction:n,connection:r,options:i}=e.params,a;return n instanceof Uint8Array?a=await this.signSerializedTransaction(n,t):(await this.signTransactionObject(n,t),a=n.serialize()),{signature:await r.sendRawTransaction(a,i)}}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new k({code:`embedded_wallet_request_error`,error:n})}}async handleSignTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.connectAndRecover(t);let{transaction:n}=e.params;return n instanceof Uint8Array?{signedTransaction:await this.signSerializedTransaction(n,t)}:(await this.signTransactionObject(n,t),{signedTransaction:n})}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.wallet_index,error:n}),new k({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},vr=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(A(this._account))throw new k({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 k({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return this.handleIFrameRpc(e)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing access token. User must be authenticated.`);return(await this._proxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:this._account.chain_type})).response.data}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new k({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedBitcoinProvider { address: '${this._account.address}', request: [Function] }`}},yr=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 br(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new jn(`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 jn(`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 jn(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function xr(e){return e.error!==void 0}const Sr=(function(e){return()=>`id-${e++}`})(0),Cr=(e,t)=>typeof t==`bigint`?t.toString():t,wr=(e,t)=>`${e}${JSON.stringify(t,Cr)}`,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)}},Tr=new yr;var Er=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(br(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,Tr.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=Tr.dequeue(e.event,e.id);if(t)return xr(e)?t.reject(new jn(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=wr(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=Sr();Tr.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 Dr(e,{request:t,headers:n}){return await e.fetchPrivyRoute(dt,{body:t,headers:n})}async function Or({context:e,chainType:t,idempotencyKey:n}){return{wallet:await Dr(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}var kr=class{_privyInternal;_proxy;_chains=Array.from(St);_mfa;_mfaPromises;_appApi;_dataSuffixPlugin;constructor(e,t,n,r,i,a,o){if(this._privyInternal=e,t&&(this._proxy=new Er(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 Er(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 k({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 Or({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:e.chainType});else{if(!e.entropyId)throw new k({error:`Missing entropy details for wallet creation`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new k({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 A(e)||await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new vr({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 k({error:`User-controlled server wallets do not support custom recovery methods`,code:`embedded_wallet_creation_error`});await Or({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 k({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 k({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 k({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 k({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 Or({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 k({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 k({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 k({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new k({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 A(e)||await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new sr({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 A(e)||(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new sr({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 k({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return A(e)||(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new _r({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(A(t))throw new k({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});ar({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 sr({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(Fn(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}}},Ar=class extends jt{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const jr=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let Mr=!1;const Nr=()=>{if(Mr)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;Mr=typeof t==`string`&&t.length>0||typeof n==`string`&&jr.includes(n)}catch{Mr=!0}return Mr},R={get(e){return rn.get(e)},set(e,t,n){Nr()||rn.set(e,t,n)},remove(e){rn.remove(e)}},Pr=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!Nr(),Fr=`privy:active-user`,Ir=`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`,Lr=e=>e?`privy-${e}-token`:`privy-token`,Rr=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,zr=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}))))),Br=[`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 Vr=class extends jt{static events=Br;_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 Pr({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 D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(B(e));try{return typeof t==`string`?new D(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:`getToken_error`}),null}}async 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=D.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(Fr)];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(Lr(null)),R.remove(Rr(null)),R.remove(zr(null)),R.remove(U(null)),t&&(R.remove(Lr(t)),R.remove(Rr(t)),R.remove(zr(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=Lr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),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=Rr(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=D.parse(e)?.subject;if(typeof i!=`string`||i.length===0)return;let a=[this.storeCustomerAccessTokenForUser(i,e),this.storeRefreshTokenForUser(i,n)];typeof t==`string`&&a.push(this.storePrivyAccessTokenForUser(i,t)),typeof r==`string`&&a.push(this.storeIdentityTokenForUser(i,r));let o=(await 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=zr(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=D.parse(t)?.expiration;this.writeCookie(r,t,{sameSite:`Strict`,secure:!0,expires:i?new Date(i*1e3):void 0}),e!==t&&this.emit(`identity_token_stored`,{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(n);await this._storage.del(n),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=w.base64urlnopad.fromBytes(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(Fr);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(Fr,e)}async getSavedUserIds(){let e=await this._storage.get(Ir);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(Ir,JSON.stringify(t)):await this._storage.del(Ir),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 k({code:`invalid_input`,error:`Cannot switch active user because the user ID is not saved on this device`});await this._storage.put(Fr,e)}};const Hr=e=>{let t=new AbortController,n=e.filter(e=>!!e),r=()=>{for(let e of n)e.removeEventListener(`abort`,r);t.abort(n.find(e=>e.aborted)?.reason)};if(n.some(e=>e.aborted))r();else for(let e of n)e.addEventListener(`abort`,r);return t.signal},Ur=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function Wr(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 Gr=()=>void 0,G={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},Kr=({level:e,logger:t})=>({get level(){return e},error:G[e]>=G.ERROR?t.error:Gr,warn:G[e]>=G.WARN?t.warn:Gr,info:G[e]>=G.INFO?t.info:Gr,debug:G[e]>=G.DEBUG?t.debug:Gr}),qr=`privy:caid`;var Jr=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.78.3`;_fetch;nativeAppIdentifier;_crypto;isMultiUserModeEnabled;_cache=new Map;constructor(e){this.logger=Kr({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 Vr({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=nn(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 k({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}${bt(e.path,t)}${Wr(n)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new k({code:`invalid_input`,error:`Unauthenticated requests require sessions.mode to be set to "multi-user"`});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:n,query:r,headers:i,signal:a,onRequest:o=this._beforeRequest.bind(this)}){let s=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),c=await o(s);a&&(c.signal=Hr([a,c.signal]));let l=await this._fetch(s,c),u=await l.json();if(l.status>299)throw new O({...u,status:l.status});return u}async fetchRaw(e,{body:t,params:n,query:r,headers:i,onRequest:a=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:n,query:r}),{method:e.method,body:JSON.stringify(t),headers:i}),s=await a(o),c=await this._fetch(o,s);if(c.status>299)throw new O({...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:Ur(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:Ur(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(r,{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(qr);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(qr,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(qr)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,t){try{await this.fetch(n,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch{}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new k({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 O({code:tn.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});try{this.logger.debug(`[privy:refresh] fetching: ${Ke.path}`);let n=await this.fetch(Ke,{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 O&&e.code===tn.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}}},Yr=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(t,{})}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(qe,{});return await this._privyInternal.session.storeIdentityToken(t),this._privyInternal.callbacks?.setUser?.(e),{user:e}}async switchActiveUser(e){if(!this._isMultiUserModeEnabled)throw new k({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 k({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 Xr=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`,Zr=e=>e?e.linked_accounts.filter(Xr).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],K=e=>Zr(e).find(e=>e.wallet_index===0)??null,Qr=K,$r=e=>e?e.linked_accounts.filter(Xr).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],ei=e=>$r(e).find(e=>e.wallet_index===0)??null,ti=(e,t)=>t===`off`||Zr(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,ni=(e,t)=>t===`off`||$r(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,ri=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),q=async(e,t,n)=>{let r=ti(t.user,n?.ethereum?.createOnLogin??`off`),i=ni(t.user,n?.solana?.createOnLogin??`off`);if(r&&i){let n=await e.create({recoveryMethod:`privy`,skipCallbacks:!0}),r=await e.createSolana({ethereumAccount:K(n.user)??void 0});return ri(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:ei(t.user)??void 0});return ri(n,t)}if(i){let n=await e.createSolana({ethereumAccount:K(t.user)??void 0});return ri(n,t)}return t};var ii=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async syncWithToken(e,t,n){let r=await this._privyInternal.fetchForLogin(u,{body:{token:e,mode:n}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await q(this._embedded,r,t?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithToken(e){await this._privyInternal.fetch(d,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},ai=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Me,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(je,{body:{email:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await q(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Ne,{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(Be,{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(ze,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},oi=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(m,{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(p,{body:{channel_token:e,message:t,signature:n,fid:r,mode:i}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await q(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(h,{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}}},si=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(re,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(ne,{body:{message:e,signature:t,fid:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await q(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}},ci=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(me,{body:{guest_credential:t}});await this._privyInternal.session.updateWithTokensResponse(n);let r=await q(this._embedded,n,e?.embedded);return this._privyInternal.callbacks?.setUser?.(r.user),r}};const J=`privy:state_code`,Y=`privy:code_verifier`;async function li(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function ui(e){return crypto.getRandomValues(new Uint8Array(e))}function di(){return w.base64urlnopad.fromBytes(ui(36))}function fi(){return di()}async function pi({codeVerifier:e,method:t=`S256`,digest:n}){if(t==`S256`){let t=await li(e,n);return w.base64urlnopad.fromBytes(t)}else return e}var mi=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=di(),r=fi(),i=await pi({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put(Y,n),this._storage.put(J,r)]),this._privyInternal.fetchForLogin(Se,{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(Y),this._storage.get(J)]);if(s!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:s??``,returnedStateCode:t??``}),new k({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let c=await this._privyInternal.fetchForLogin(xe,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let l=await q(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del(Y),this._storage.del(J)]),this._privyInternal.callbacks?.setUser?.(l.user),l}async linkWithCode(e,t,n,r){let[i,a]=await Promise.all([this._storage.get(Y),this._storage.get(J)]);if(a!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:a??``,returnedStateCode:t??``}),new k({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let o=await this._privyInternal.fetch(Ce,{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(Y),this._storage.del(J)]),{user:s.user,identity_token:s.identity_token}}async unlink(e,t){await this._privyInternal.fetch(we,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},hi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(Oe,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(Ee,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(Ae,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Te,{body:{relying_party:n,challenge:t,authenticator_response:this._transformAuthenticationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await q(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async signupWithPasskey(e,t,n){let r=await this._privyInternal.fetchForLogin(ke,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await q(this._embedded,r,n?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithPasskey(e,t){await this._privyInternal.fetch(De,{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}}}},gi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(Fe,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(Pe,{body:{phoneNumber:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await q(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(Ie,{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(Re,{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(Le,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},_i=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(et,{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(Qe,{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(Xe,{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 q(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=vi({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 vi(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 yi=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlink({address:e}){await this._privyInternal.fetch(it,{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(rt,{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(tt,{body:{signature:n,message:t,walletClientType:r??null,connectorType:i??null,mode:e}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await q(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async fetchNonce({address:e}){let{nonce:t}=await this._privyInternal.fetch(nt,{body:{address:e}});return{nonce:t}}},bi=class{_privyInternal;constructor(e){this._privyInternal=e}async link(e,t,n,r){await this._privyInternal.fetch($e,{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(Ze,{body:{address:e.address}});return{nonce:t,message:xi({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 xi(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 li=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async authenticate({telegramWebAppData:e,telegramAuthResult:t,captchaToken:n,mode:r=`login-or-sign-up`},i){let a=await this._privyInternal.fetchForLogin(ot,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n,mode:r}});await this._privyInternal.session.updateWithTokensResponse(a);let o=await X(this._embedded,a,i?.embedded);return this._privyInternal.callbacks?.setUser?.(o.user),o}async link({telegramWebAppData:e,telegramAuthResult:t,captchaToken:n}){await this._privyInternal.fetch(st,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n}});let r=await this._privyInternal.refreshSession();return{user:r.user,identity_token:r.identity_token}}async unlink({telegramUserId:e}){await this._privyInternal.fetch(ct,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},ui=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 ri(this._privyInternal,t),this.email=new Kr(this._privyInternal,t),this.oauth=new ti(this._privyInternal,t,n,r),this.guest=new Yr(this._privyInternal,t),this.siwe=new ii(this._privyInternal,t),this.siws=new oi(this._privyInternal,t),this.smartWallet=new si(this._privyInternal),this.passkey=new ni(this._privyInternal,t),this.farcaster=new qr(this._privyInternal,t),this.farcasterV2=new Jr(this._privyInternal,t),this.telegram=new li(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(ye,{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}}},di=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(i,{body:e})}async getStatus(e){return await this._privyInternal.fetch(a,{query:{partnerUserId:e}})}};const fi={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},pi=new Set([_.id,m.id,g.id,b.id,h.id,Dt.id,v.id]),mi=new Set([_.id,m.id,y.id,g.id,b.id,h.id]);function hi(e,t){switch(t){case`native-currency`:return pi.has(e);case`USDC`:return mi.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function gi(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 Dt.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 _i(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var vi=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(Se,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=fi[t?`sandbox`:`prod`],i=await Yt(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new pn({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}},yi=class{moonpay;coinbase;constructor(e){this.moonpay=new vi(e),this.coinbase=new di(e)}},bi=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(be,{body:e})}},xi=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(xe,{body:e})}},Si=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new xi(e),this.passkey=new bi(e)}setProxy(e){this.proxy=e}async getAccessTokenInternal(){let e=await this.privyInternal.getAccessTokenInternal();if(!e)throw new k({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return e}async verifyMfa(){if(!this.proxy)throw new k({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 k({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 k({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 k({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 k({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 k({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.clearMfa(e)}},Ci=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(qe,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(Ue,{body:{client_type:e}})}},wi=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=Qr(),n=$r(),r=await ei({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put(Q,t),this._storage.put(Z,n)]),this._privyInternal.fetch(Ke,{body:{redirect_to:e,code_challenge:r,state_code:n}})}async authorize(e,t){let[n,r]=await Promise.all([this._storage.get(Q),this._storage.get(Z)]);if(r!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`recovery_oauth`,storedStateCode:r??``,returnedStateCode:t??``}),new k({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let i=await this._privyInternal.fetch(Ge,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del(Q),this._storage.del(Z)]),i}},Ti=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new wi(this._privyInternal,t,n),this.icloudAuth=new Ci(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(We,{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=an(r.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this.plugins=[...n],this._privyInternal=new Fr({...r,appClientId:e,crypto:i,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new Si(this._privyInternal),this.mfaPromises=new _r,this.app=new un(this._privyInternal),this.embeddedWallet=new gr(this._privyInternal,r.embeddedWalletMessagePoster,r.supportedChains,this.mfa,this.mfaPromises,this.app,cn(this.plugins)),this.user=new Ir(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new ui(this._privyInternal,this.embeddedWallet,r.storage,i,this.mfa),this.recovery=new Ti(this._privyInternal,r.storage,i),this.funding=new yi(this._privyInternal),this.delegated=new fn(this._privyInternal),this.crossApp=new dn(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}},Di=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)}},Oi=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 ki=e=>e?e.linked_accounts.filter(Lr).filter(Ai).sort((e,t)=>e.wallet_index-t.wallet_index):[],Ai=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,ji=(e,t)=>{if(!e)return null;if(t?.imported||t&&A(t))return Mi(t);let n=Y(e)??Vr(e);return n?Mi(n):null},Mi=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`)},Ni=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,Pi=(e,t)=>tn(String(e),t),Fi=e=>nn(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),Ii=(e,t)=>`+${$t(t)} ${e}`,Li=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,Ri=e=>new Zt(e),zi=Qt().map(e=>({code:e,callCode:$t(e)})),Bi=e=>{let t=en(e,Xt)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},Vi=e=>{let t=new Zt;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},Hi=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),Ui={[_.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[jt.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[y.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[kt.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[b.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[At.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[g.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[Et.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[h.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[Tt.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[m.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[wt.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},Wi={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function Gi(e,t){return e===Ui[t.id]}async function Ki(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 qi=new Set([_.id,g.id,y.id,b.id,m.id,h.id,v.id]),Ji=new Set([_.id,g.id,b.id,y.id,m.id,h.id,v.id]),Yi={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`},Zi={[_.id]:`ethereum`,[g.id]:`base`,[y.id]:`optimism`,[b.id]:`polygon`,[m.id]:`arbitrum`,[h.id]:`avacchain`,[v.id]:`monad`};function Qi(e){return e.startsWith(`.`)?`0${e}`:e}function $i({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`,Qi(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,Yi[a]),o.searchParams.set(`defaultAsset`,Xi[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const ea=(e,t)=>{switch(t){case`native-currency`:return qi.has(e);case`USDC`:return Ji.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function ta(e){return Zi[e]}function na(e,t){return t===`USDC`?`USDC`:e===b.id?`POL`:e===v.id?`MON`:`ETH`}const ra=e=>e.provider.replace(/-sandbox$/,``),ia={BINANCECONNECT:`BINANCE_CONNECT`,COINBASEPAY:`COINBASE`},aa=e=>{let t=(e.sub_provider?.trim()||ra(e)).toUpperCase();return ia[t]??t};var oa=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=an(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 sa=({address:e,nonce:t,domain:n,uri:r})=>`${n} wants you to sign in with your Solana account:
|
|
23
|
+
- https://privy.io`}var Si=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(at,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n,mode:r}});await this._privyInternal.session.updateWithTokensResponse(a);let o=await q(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(ot,{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(st,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Ci=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 ii(this._privyInternal,t),this.phone=new gi(this._privyInternal,t),this.email=new ai(this._privyInternal,t),this.oauth=new mi(this._privyInternal,t,n,r),this.guest=new ci(this._privyInternal,t),this.siwe=new _i(this._privyInternal,t),this.siws=new yi(this._privyInternal,t),this.smartWallet=new bi(this._privyInternal),this.passkey=new hi(this._privyInternal,t),this.farcaster=new oi(this._privyInternal,t),this.farcasterV2=new si(this._privyInternal,t),this.telegram=new Si(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(_e,{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}}},wi=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(i,{body:e})}async getStatus(e){return await this._privyInternal.fetch(a,{query:{partnerUserId:e}})}};const Ti={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},Ei=new Set([y.id,g.id,v.id,S.id,_.id,Et.id,b.id]),Di=new Set([y.id,g.id,x.id,v.id,S.id,_.id]);function Oi(e,t){switch(t){case`native-currency`:return Ei.has(e);case`USDC`:return Di.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function ki(e,t){switch(e){case g.id:return t===`native-currency`?`ETH_ARBITRUM`:`USDC_ARBITRUM`;case _.id:return t===`native-currency`?`AVAX_CCHAIN`:`USDC_CCHAIN`;case v.id:return t===`native-currency`?`ETH_BASE`:`USDC_BASE`;case Et.id:return`CELO_CELO`;case S.id:return t===`native-currency`?`MATIC_POLYGON`:`USDC_POLYGON`;case b.id:return`MON_MON`;case y.id:return t===`native-currency`?`ETH_ETHEREUM`:`USDC_ETHEREUM`;default:return console.warn(`Chain ${e} not supported by Moonpay, defaulting to Ethereum mainnet`),`ETH_ETHEREUM`}}function Ai(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var ji=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(be,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=Ti[t?`sandbox`:`prod`],i=await an(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new Cn({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}},Mi=class{moonpay;coinbase;constructor(e){this.moonpay=new ji(e),this.coinbase=new wi(e)}},Ni=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(ve,{body:e})}},Pi=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(ye,{body:e})}},Fi=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new Pi(e),this.passkey=new Ni(e)}setProxy(e){this.proxy=e}async getAccessTokenInternal(){let e=await this.privyInternal.getAccessTokenInternal();if(!e)throw new k({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return e}async verifyMfa(){if(!this.proxy)throw new k({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 k({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 k({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 k({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 k({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 k({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.clearMfa(e)}},Ii=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(Ge,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(Ve,{body:{client_type:e}})}},Li=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=di(),n=fi(),r=await pi({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put(Y,t),this._storage.put(J,n)]),this._privyInternal.fetch(We,{body:{redirect_to:e,code_challenge:r,state_code:n}})}async authorize(e,t){let[n,r]=await Promise.all([this._storage.get(Y),this._storage.get(J)]);if(r!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`recovery_oauth`,storedStateCode:r??``,returnedStateCode:t??``}),new k({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let i=await this._privyInternal.fetch(Ue,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del(Y),this._storage.del(J)]),i}},Ri=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new Li(this._privyInternal,t,n),this.icloudAuth=new Ii(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(He,{body:{chain_type:t},params:{address:e}})}},zi=class{plugins;auth;user;embeddedWallet;recovery;mfa;app;mfaPromises;funding;delegated;crossApp;isMultiUserModeEnabled;_privyInternal;constructor({clientId:e,sessions:t,plugins:n=[],...r}){let i=mn(r.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this.plugins=[...n],this._privyInternal=new Jr({...r,appClientId:e,crypto:i,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new Fi(this._privyInternal),this.mfaPromises=new Ar,this.app=new bn(this._privyInternal),this.embeddedWallet=new kr(this._privyInternal,r.embeddedWalletMessagePoster,r.supportedChains,this.mfa,this.mfaPromises,this.app,vn(this.plugins)),this.user=new Yr(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new Ci(this._privyInternal,this.embeddedWallet,r.storage,i,this.mfa),this.recovery=new Ri(this._privyInternal,r.storage,i),this.funding=new Mi(this._privyInternal),this.delegated=new Sn(this._privyInternal),this.crossApp=new xn(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}},Bi=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)}},Vi=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 Hi=e=>e?e.linked_accounts.filter(Xr).filter(Ui).sort((e,t)=>e.wallet_index-t.wallet_index):[],Ui=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,Wi=(e,t)=>{if(!e)return null;if(t?.imported||t&&A(t))return Gi(t);let n=K(e)??ei(e);return n?Gi(n):null},Gi=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`)},Ki=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,qi=(e,t)=>dn(String(e),t),Ji=e=>fn(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),Yi=(e,t)=>`+${ln(t)} ${e}`,Xi=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,Zi=e=>new sn(e),Qi=cn().map(e=>({code:e,callCode:ln(e)})),$i=e=>{let t=un(e,on)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},ea=e=>{let t=new sn;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},ta=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),na={[y.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[At.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[x.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[Ot.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[S.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[kt.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[v.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[Tt.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[_.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[wt.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[g.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[Ct.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},ra={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function ia(e,t){return e===na[t.id]}async function aa(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 oa=new Set([y.id,v.id,x.id,S.id,g.id,_.id,b.id]),sa=new Set([y.id,v.id,S.id,x.id,g.id,_.id,b.id]),ca={buy:`CARD`,send:`CRYPTO_ACCOUNT`},la={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`},ua={[y.id]:`ethereum`,[v.id]:`base`,[x.id]:`optimism`,[S.id]:`polygon`,[g.id]:`arbitrum`,[_.id]:`avacchain`,[b.id]:`monad`};function da(e){return e.startsWith(`.`)?`0${e}`:e}function fa({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`,da(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,ca[a]),o.searchParams.set(`defaultAsset`,la[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const pa=(e,t)=>{switch(t){case`native-currency`:return oa.has(e);case`USDC`:return sa.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function ma(e){return ua[e]}function ha(e,t){return t===`USDC`?`USDC`:e===S.id?`POL`:e===b.id?`MON`:`ETH`}const ga=e=>e.provider.replace(/-sandbox$/,``),_a={BINANCECONNECT:`BINANCE_CONNECT`,COINBASEPAY:`COINBASE`},va=e=>{let t=(e.sub_provider?.trim()||ga(e)).toUpperCase();return _a[t]??t};var ya=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=mn(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 ba=({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 ca({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 la({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function ua(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const da=`solana offchain`,fa=1232;function pa(e){let t=S.utf8.toBytes(e),n=new Uint8Array(32);return n.set(t.slice(0,32)),n}function ma({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>fa)throw Error(`Combined message length (${i}) exceeds maximum (${fa})`);let a=pa(n),o=new Uint8Array(i),s=0;o[s]=255,s+=1;let c=S.utf8.toBytes(da);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 ha(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))!==da)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 ga=[`privy`],_a=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],va=[`coinbase_wallet`],ya=`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(`.`),ba=[`unknown`],xa=[..._a,...va,...ya,...ga,...ba],Sa=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Ca(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function wa({wei:e,precision:t=3}){return parseFloat(Pt(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function Ta({amount:e,decimals:t}){return Ft(BigInt(e),t)}function Ea({lamports:e}){return Ft(e,9)}const Da=e=>[...Rr(e),...Br(e)],Oa=(e,t)=>e.imported?e:Y(t)??Vr(t),ka=e=>async({address:t,chainType:n})=>{let{user:r}=await e.user.get();if(!r)throw new k({code:`delegated_actions_before_logged_in`,error:`Must be logged in to delegate wallets`});if(n!==`solana`&&n!==`ethereum`)throw new k({code:`unsupported_chain_type`,error:`Only Solana and Ethereum embedded wallets are supported for delegation and revocation.`});let i=Da(r).find(e=>e.chain_type===n&&e.address===t);if(!i)throw new k({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});if(A(i))throw new k({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=Oa(i,r);if(!a)throw new k({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}},Aa=e=>async()=>{let{user:t}=await e.user.get();if(!t)throw new k({code:`delegated_actions_before_logged_in`,error:`Must be logged in to revoke delegated wallets`});let n=Da(t);if(n.some(A))throw new k({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 k({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 ja=w({delegateWallet:()=>ka,revokeWallets:()=>Aa});const Ma=({client:e,openAuthSession:t})=>async({providerAppId:n,redirectUrl:r,loginOptions:i})=>{let a=`privy:${n}`,{url:o}=await e.auth.oauth.generateURL(a,r),s=await t(o,r),c=s.privy_oauth_state,l=s.privy_oauth_code;if(!c||!l)throw new k({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let u=await e.auth.oauth.loginWithCode(l,c,a,void 0,void 0,i),d=u.oauth_tokens;return d&&await e.crossApp.updateOnCrossAppAuthentication(n,d),u},Na=({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 k({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 Pa(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const Fa=(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=Na({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))},La=({client:e,openAuthSession:t})=>{let n=Ia({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=Fa(r,o);if(!s)throw new k({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 k({code:`cross_app_invalid_app`,error:`Invalid connected app`});if(u.read_only)throw new k({code:`cross_app_read_only`,error:`Cannot transact against a read-only provider app`});let d=await n({providerAppId:c,redirectUrl:a});if(!d)throw new k({code:`cross_app_request_error`,error:`Wallet operations require a valid token`});let ee={content:{request:{request:i}},timestamp:Date.now(),callbackUrl:a},f=new URL(`${u.provider_app_custom_api_url}/oauth/transact`);f.searchParams.set(`communicationMode`,`redirect`),f.searchParams.set(`token`,d),f.searchParams.set(`request`,JSON.stringify(ee));let{privy_cross_app_type:te,privy_cross_app_payload:p}=await t(f.href,a);if(!te||!p)throw new k({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(te===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new k({code:`cross_app_request_error`,error:p});if(te!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new k({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:p}}};function Ra(e){if(!e)throw new k({code:`attempted_cross_app_request_before_logged_in`,error:`Must be logged in to sign messages with a cross-app wallet`})}const za=({client:e,openAuthSession:t})=>{let n=La({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{Ra(e);let a={method:Pa(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 Ba(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 Va=({client:e,openAuthSession:t})=>{let n=La({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{Ra(e);let a={method:Pa(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,Ba(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},Ha=({client:e,openAuthSession:t})=>{let n=La({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{Ra(e);let a={method:Pa(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var Ua=w({sendTransaction:()=>Ha,signMessage:()=>za,signTypedData:()=>Va}),Wa=w({linkWithCrossAppAuth:()=>Na,loginWithCrossAppAuth:()=>Ma,wallet:()=>Ua});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 Ka(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 qa(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=Ka(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(ft,{body:{chain_type:r}});return await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function Ja(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await qa({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(l,{body:{source_chain:e.sourceChain,source_currency:e.sourceCurrency,destination_chain:e.destinationChain,destination_currency:e.destinationCurrency,destination_address:e.destinationAddress,refund_address:n,...e.slippageBps==null?{}:{slippage_bps:e.slippageBps}}});return e.privy.track({name:`sdk_deposit_address_headless_quote`,properties:{sourceChain:e.sourceChain,sourceCurrency:e.sourceCurrency,destinationChain:e.destinationChain,destinationCurrency:e.destinationCurrency,depositAddressId:r.id}}),r}function Ya(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const Xa=async({operation:e,until:t,delay:n,interval:r,attempts:i,signal:a})=>{n&&await Ya(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 Ya(r)}catch(e){e instanceof Error&&(c=e),o<i&&await Ya(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},Za=2e3,Qa=1800*1e3;function $a(e,t){return Math.ceil(t/e)}function eo(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 to(e){return await e.privy.fetchPrivyRoute(fe,{params:{order_id:e.orderId}})}async function no(e){let t=e.pollIntervalMs??Za,n=e.timeoutMs??Qa,r=e.signal??new AbortController().signal;return eo(await Xa({operation:async()=>{let t=await e.privy.fetchPrivyRoute(me,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(fe,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:$a(t,n),signal:r}))}async function ro(e){let t=e.pollIntervalMs??Za,n=e.timeoutMs??Qa,r=e.signal??new AbortController().signal;return eo(await Xa({operation:()=>e.privy.fetchPrivyRoute(fe,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:$a(t,n),signal:r}))}var io=w({generateDepositAddress:()=>Ja,getConfig:()=>ao,getDeposit:()=>to,resolveRefundAddress:()=>qa,waitForCompletion:()=>ro,waitForDeposit:()=>no});async function ao(e){let t=await e.fetchPrivyRoute(pe,{});return{currencies:t.currencies,chains:t.chains}}function oo(e){let t=e.depositAddressStrategy===void 0?{}:{deposit_address_strategy:e.depositAddressStrategy};return e.type===`deposit_config`?{type:`deposit_config`,deposit_config_id:e.depositConfigId,...t}:{type:`inline_route`,source:e.source,destination:e.destination,...t}}async function so(e,t,n){let{walletId:r}=n,i=oo(n),a=e.getCompiledPath(s,{params:{wallet_id:r}}),o=String(Date.now()+I),{signature:c}=await P(t,{version:1,url:a,method:s.method,headers:{"privy-app-id":e.app.appId,[F]:o},body:i});if(Date.now()>Number(o))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});let l=await e.fetchPrivyRoute(s,{body:i,params:{wallet_id:r},headers:{"privy-authorization-signature":c,[F]:o}});return e.track({name:`sdk_deposit_address_headless_create`,properties:{version:`v3`,action:`create`,walletId:r,type:n.type,...n.type===`inline_route`?{destinationChain:n.destination.chain,destinationCurrency:n.destination.asset}:{depositConfigId:n.depositConfigId}}}),l}async function co(e,t){let n=await e.fetchPrivyRoute(c,{body:{source:t.source,destination:t.destination,...t.inputAmount==null?{}:{input_amount:t.inputAmount},...t.slippageBps==null?{}:{slippage_bps:t.slippageBps}}});return e.track({name:`sdk_deposit_address_headless_quote`,properties:{version:`v3`,action:`quote`,sourceChain:t.source.chain,sourceCurrency:t.source.asset,destinationChain:t.destination.chain,destinationCurrency:t.destination.asset}}),n}function lo(e){let t=Number(e.input_amount),n=Number(e.estimated_output_amount);if(!(!Number.isFinite(t)||!Number.isFinite(n)||t===0))return String(n/t)}async function uo(e,t){return e.fetchPrivyRoute(de,{params:{wallet_id:t.walletId,order_id:t.orderId}})}async function fo(e,t){return e.fetchPrivyRoute(ue,{params:{wallet_id:t.walletId},query:{after:t.after}})}const po={ethereum:`eip155:1`,arbitrum:`eip155:42161`,avalanche:`eip155:43114`,arc:`eip155:5042`,base:`eip155:8453`,tempo:`eip155:4217`,linea:`eip155:59144`,optimism:`eip155:10`,polygon:`eip155:137`,bsc:`eip155:56`,zksync_era:`eip155:324`,solana:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,tron:`tron:mainnet`,robinhood:`eip155:4663`,unichain:`eip155:130`,worldchain:`eip155:480`,ink:`eip155:57073`,soneium:`eip155:1868`,megaeth:`eip155:4326`,hyperevm:`eip155:999`,hypercore:`eip155:1337`,"tempo_zone:00001":`eip155:421700001`,"tempo_zone:00002":`eip155:421700002`,tempo_testnet:`eip155:42431`,"tempo_testnet_zone:00003":`eip155:1424310003`,hoodi:`eip155:560048`,sepolia:`eip155:11155111`,arbitrum_sepolia:`eip155:421614`,avalanche_fuji:`eip155:43113`,base_sepolia:`eip155:84532`,linea_testnet:`eip155:59140`,optimism_sepolia:`eip155:11155420`,polygon_amoy:`eip155:80002`,bsc_testnet:`eip155:97`,solana_devnet:`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,solana_testnet:`solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`,tron_nile:`tron:nile`,robinhood_testnet:`eip155:46630`,ink_sepolia:`eip155:763373`},mo=[{id:`eth`,symbol:`ETH`},{id:`sol`,symbol:`SOL`},{id:`pol`,symbol:`POL`},{id:`trx`,symbol:`TRX`},{id:`usdc`,symbol:`USDC`},{id:`usdc_e`,symbol:`USDC.e`},{id:`usdt`,symbol:`USDT`},{id:`usdt0`,symbol:`USDT0`},{id:`usdb`,symbol:`USDB`},{id:`eurc`,symbol:`EURC`},{id:`ousd`,symbol:`OUSD`},{id:`usdg`,symbol:`USDG`},{id:`pathusd`,symbol:`PathUSD`}],ho=new Set([`native`,`native-token`,`0x0000000000000000000000000000000000000000`,`11111111111111111111111111111111`]);function go(e){return ho.has(e.toLowerCase())}function _o(e){return e.includes(`:`)}function $(e){return _o(e)?e:po[e.toLowerCase()]||(/^\d+$/.test(e)?`eip155:${e}`:e)}function vo(e){return go(e)}function yo(e){let t=e.toLowerCase();return mo.find(e=>e.id===t||e.symbol.toLowerCase()===t)}function bo({symbol:e,address:t}){return yo(e)?.id??t}function xo({asset:e,symbol:t,addresses:n}){let r=e.toLowerCase();return t.toLowerCase()===r?!0:vo(e)?n.some(go):n.some(e=>e.toLowerCase()===r)}function So({config:e,chain:t,asset:n}){let r=t?$(t):void 0;for(let t of e.currencies){let e=r?t.chains.filter(e=>$(e.caip2)===r):t.chains;if(e.length!==0&&xo({asset:n,symbol:t.symbol,addresses:e.map(e=>e.address)}))return t.symbol}return n.toUpperCase()}function Co(e,t,n){return wo(e,n)===wo(t,n)}function wo(e,t){let n=$(e);if(n!==e||e.includes(`:`))return n;let r=e.toLowerCase();for(let n of Object.values(t.chains))if(n.caip2===e||n.display_name.toLowerCase()===r||String(n.chain_id)===e)return n.caip2;return n}function To(e,t){return xo({asset:t.asset,symbol:e.symbol,addresses:e.chains.map(e=>e.address)})}function Eo({caip2:e,asset:t,config:n}){return!t.chain||Co(t.chain,e,n)}function Do({currency:e,source:t,config:n}){switch(t.mode){case`all`:return e.chains;case`include`:{let r=t.values.filter(t=>To(e,t));return r.length===0?[]:e.chains.filter(e=>r.some(t=>Eo({caip2:e.caip2,asset:t,config:n})))}case`exclude`:{let r=t.values.filter(t=>To(e,t));return r.length===0?e.chains:e.chains.filter(e=>!r.some(t=>Eo({caip2:e.caip2,asset:t,config:n})))}default:return e.chains}}function Oo(e,t){return{currencies:e.currencies.map(n=>({...n,chains:Do({currency:n,source:t,config:e})})).filter(e=>e.chains.length>0),chains:e.chains}}function ko(e){return e.startsWith(`0x`)}function Ao(e,t){let n=ko(e);switch(t){case`evm`:case`hypevm`:return n;case`svm`:case`bvm`:case`tron`:case`tvm`:return!n;default:return n}}function jo(e,t){let n=$(t);switch(e.source.mode){case`all`:return!0;case`include`:return e.source.values.some(e=>!e.chain||$(e.chain)===n);case`exclude`:return!e.source.values.some(e=>!e.chain||$(e.chain)===n);default:return e.source,!1}}function Mo({accounts:e,selectedChain:t}){if(e.length===0)return;let n=e.filter(e=>jo(e,t.caip2)),r=n.length>0?n:e,i=r.find(e=>Ao(e.deposit_address,t.vmType));return i?i.deposit_address:r[0]?.deposit_address}var No=w({createCryptoDepositAccount:()=>so,filterDepositConfig:()=>Oo,findCatalogSymbol:()=>So,getCryptoDepositAccountNextOrder:()=>fo,getCryptoDepositAccountOrder:()=>uo,getCryptoDepositAccountQuote:()=>co,indicativeRateFromQuote:()=>lo,isNativeAssetAlias:()=>vo,pickDepositAddressForChain:()=>Mo,quoteSourceAsset:()=>bo,resolveChainAlias:()=>$});async function Po(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(gt,{params:{wallet_id:n}}),a=String(Date.now()+I),{signature:o}=await P(t,{version:1,url:i,method:gt.method,headers:{"privy-app-id":e.app.appId,[F]:a},body:{...r}});if(Date.now()>Number(a))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(gt,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[F]:a}})}async function Fo(e,{wallet_id:t}){return await e.fetchPrivyRoute(pt,{params:{wallet_id:t}})}async function Io(e,{wallet_id:t},n,r){let{signature:i}=await P(n,{version:1,url:e.getCompiledPath(yt,{params:{wallet_id:t}}),method:yt.method,headers:{"privy-app-id":e.app.appId},body:r});return await e.fetchPrivyRoute(yt,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":i}})}async function Lo(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(vt,{params:{wallet_id:n}}),a=String(Date.now()+I),{signature:o}=await P(t,{version:1,url:i,method:vt.method,headers:{"privy-app-id":e.app.appId,[F]:a},body:{...r}});if(Date.now()>Number(a))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(vt,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[F]:a}})}async function Ro(e,{wallet_id:t,action_id:n}){return await e.fetchPrivyRoute(mt,{params:{wallet_id:t,action_id:n}})}async function zo(e,{wallet_id:t,...n}){return await e.fetchPrivyRoute(ht,{params:{wallet_id:t},query:{...n.cursor?{cursor:n.cursor}:{},...n.limit===void 0||n.limit===null?{}:{limit:n.limit},...n.type?{type:n.type}:{}}})}async function Bo({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(A(t)){if(n.length===0)throw Error(`Must specify at least one signer to add.`);let r={wallet_id:t.id},i=await Fo(e,r);await Io(e,r,Uo(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return Ho(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=Oa(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 Ho(e)}async function Vo({client:e,wallet:t}){return A(t)?await Io(e,{wallet_id:t.id},Uo(e),{additional_signers:[]}):await e.delegated.revoke(),Ho(e)}async function Ho(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function Uo(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var Wo=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 Go=async(t,{environment:n,acceptElectronicDisclosure:r,acceptBankTerms:i})=>{let{data:a}=await t.fetchPrivyRoute(e,{body:{environment:n,accept_electronic_disclosure:r,accept_bank_terms:i}});return a},Ko=async(e,{environment:t,walletId:n,chainId:r,asset:i})=>e.fetchPrivyRoute(o,{body:{environment:t,wallet_id:n,chain_id:r,asset:i}}),qo=async(e,{cardId:t,environment:n,statementPeriod:r})=>(await e.fetchPrivyRouteRaw(ee,{params:{card_id:t,statement_period:r},query:{environment:n}})).blob(),Jo=async(e,{environment:t,limit:n,cursor:r})=>e.fetchPrivyRoute(ve,{query:{environment:t,...n===void 0?{}:{limit:n},...r?{cursor:r}:{}}}),Yo=20,Xo=async(e,{cardId:t,environment:n})=>{let{data:r}=await Jo(e,{environment:n,limit:20});return r.find(e=>e.id===t)??null},Zo=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(oe,{query:{environment:t}});return n},Qo=async(e,{cardId:t,environment:n,nonce:r})=>{let{data:i}=await e.fetchPrivyRoute(se,{params:{card_id:t},body:{environment:n,nonce:r}});return i.ephemeral_key_secret},$o=async(e,{appId:t,environment:n})=>{let{data:r}=await e.fetchPrivyRoute(ce,{params:{app_id:t},query:{environment:n}});return{publishableKey:r.publishable_key,cardLogoUrl:r.card_logo_url??null,stripeAccount:r.stripe_account}},es=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(dt,{body:{environment:t}});return n},ts=async(e,{cardId:t,environment:n,limit:r,cursor:i})=>e.fetchPrivyRoute(_e,{params:{card_id:t},query:{environment:n,...r===void 0?{}:{limit:r},...i?{cursor:i}:{}}}),ns=async(e,{cardId:t,environment:n,reason:r})=>e.fetchPrivyRoute(Xe,{params:{card_id:t},body:{environment:n,replacement_reason:r}}),rs=async(e,{cardId:t,environment:n,encryptedNumber:r})=>e.fetchPrivyRoute(ut,{params:{card_id:t},body:{environment:n,pin:{encrypted_number:r}}}),is=async(e,{cardId:t,environment:n,status:r})=>e.fetchPrivyRoute(lt,{params:{card_id:t},body:{environment:n,status:r}}),as=`biconomy`,os=`coinbase_smart_wallet`,ss=`kernel`,cs=`light_account`,ls=`safe`,us=`thirdweb`,ds=`nexus`;var fs=Ei;export{xa as ALL_WALLET_CLIENT_TYPES,as as BICONOMY,os as COINBASE_SMART_WALLET,Wo as ConnectedStandardSolanaWallet,sn as DATA_SUFFIX_PLUGIN_ID,j as EmbeddedProviderError,Oi as InMemoryCache,ss as KERNEL,cs as LIGHT_ACCOUNT,Yo as LIST_CARDS_MAX_LIMIT,Di as LocalStorage,pn as MoonpayApiError,ds as NEXUS,O as PrivyApiError,k as PrivyClientError,Sn as PrivyConnectorError,vn as PrivyEmbeddedWalletErrorCode,On as PrivyProviderRpcError,M as ProviderErrors,ls as SAFE,Sa as SUPPORTED_CONNECTOR_TYPES,oa as SolanaClient,Wi as SolanaUsdcAddressMap,us as THIRDWEB,Ui as UsdcAddressMap,Go as acceptCardConsents,Bo as addSessionSigners,ma as buildSolanaOffchainMessage,gi as chainToMoonpayCurrency,V as cookies,zi as countryCodesAndNumbers,mr as create,Ko as createCard,ln as createDataSuffixPlugin,hn as createErrorFormatter,sa as createSiwsMessage,Wa as crossApp,No as cryptoDepositAccount,fs as default,ja as delegatedActions,io as depositAddress,pa as deriveSolanaApplicationDomain,qo as downloadCardStatement,En as errorIndicatesMaxMfaRetries,gn as errorIndicatesMfaCanceled,Dn as errorIndicatesMfaRateLimit,wn as errorIndicatesMfaTimeout,Tn as errorIndicatesMfaVerificationFailed,Cn as errorIndicatesRecoveryIsNeeded,Ea as formatLamportsAmount,Ii as formatPhoneNumber,Ta as formatTokenAmount,Ca as formatWalletAddress,wa as formatWeiAmount,_i as fundingMethodToMoonpayPaymentMethod,P as generateAuthorizationSignature,Ki as generateWalletIdempotencyKey,ki as getAllUserEmbeddedBitcoinWallets,Rr as getAllUserEmbeddedEthereumWallets,Br as getAllUserEmbeddedSolanaWallets,Xo as getCardById,Zo as getCardCustomer,Qo as getCardEphemeralKey,$o as getCardsConfig,$i as getCoinbaseOnRampUrl,$t as getCountryCallingCode,cn as getDataSuffixPlugin,Mi as getEntropyDetailsFromAccount,ji as getEntropyDetailsFromUser,aa as getFiatOnrampProviderBrand,ra as getFiatOnrampProviderId,Gi as getIsTokenUsdc,Gn as getJsonRpcEndpointFromChain,es as getOrCreateCardCustomer,Vi as getPhoneCountryCodeAndNumber,Bi as getPlaceholderPhoneNumber,ua as getSolanaClusterDisplayName,ca as getSolanaRpcEndpointForCluster,la as getSolanaUsdcMintAddressForCluster,Y as getUserEmbeddedEthereumWallet,Vr as getUserEmbeddedSolanaWallet,zr as getUserEmbeddedWallet,Ni as getUserSmartWallet,Fo as getWallet,Ro as getWalletAction,Lr as isEmbeddedWalletAccount,br as isExtensionContext,ea as isSupportedChainIdForCoinbaseOnramp,hi as isSupportedChainIdForMoonpay,A as isUnifiedWallet,Li as lastFourDigits,ts as listCardTransactions,Jo as listCards,zo as listWalletActions,ha as parseSolanaOffchainMessage,Ri as phoneNumberTypingFormatter,Xa as poll,Po as rawSign,Vo as removeSessionSigners,ns as replaceCard,L as rpc,xr as shouldWriteSessionCookies,Kn as throwIfInvalidRecoveryUpgradePath,na as toCoinbaseAssetId,ta as toCoinbaseBlockchainFromChainId,Fi as toE164,Hi as toObjectKeys,kn as toWalletApiUnsignedEthTransaction,Lo as transfer,rs as updateCardPin,is as updateCardStatus,Io as updateWallet,Pi as validatePhoneNumber};
|
|
34
|
+
- https://privy.io`;function xa({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 Sa({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function Ca(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const wa=`solana offchain`,Ta=1232;function Ea(e){let t=w.utf8.toBytes(e),n=new Uint8Array(32);return n.set(t.slice(0,32)),n}function Da({message:e,signerPublicKey:t,domain:n}){let r=w.utf8.toBytes(e);if(t.length!==32)throw Error(`Signer public key must be 32 bytes`);let i=85+r.length;if(i>Ta)throw Error(`Combined message length (${i}) exceeds maximum (${Ta})`);let a=Ea(n),o=new Uint8Array(i),s=0;o[s]=255,s+=1;let c=w.utf8.toBytes(wa);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 Oa(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))!==wa)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 ka=[`privy`],Aa=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],ja=[`coinbase_wallet`],Ma=`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(`.`),Na=[`unknown`],Pa=[...Aa,...ja,...Ma,...ka,...Na],Fa=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Ia(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function La({wei:e,precision:t=3}){return parseFloat(Rt(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function Ra({amount:e,decimals:t}){return zt(BigInt(e),t)}function za({lamports:e}){return zt(e,9)}const Ba=e=>[...Zr(e),...$r(e)],Va=(e,t)=>e.imported?e:K(t)??ei(t),Ha=e=>async({address:t,chainType:n})=>{let{user:r}=await e.user.get();if(!r)throw new k({code:`delegated_actions_before_logged_in`,error:`Must be logged in to delegate wallets`});if(n!==`solana`&&n!==`ethereum`)throw new k({code:`unsupported_chain_type`,error:`Only Solana and Ethereum embedded wallets are supported for delegation and revocation.`});let i=Ba(r).find(e=>e.chain_type===n&&e.address===t);if(!i)throw new k({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});if(A(i))throw new k({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=Va(i,r);if(!a)throw new k({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}},Ua=e=>async()=>{let{user:t}=await e.user.get();if(!t)throw new k({code:`delegated_actions_before_logged_in`,error:`Must be logged in to revoke delegated wallets`});let n=Ba(t);if(n.some(A))throw new k({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 k({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 Wa=T({delegateWallet:()=>Ha,revokeWallets:()=>Ua});const Ga=({client:e,openAuthSession:t})=>async({providerAppId:n,redirectUrl:r,loginOptions:i})=>{let a=`privy:${n}`,{url:o}=await e.auth.oauth.generateURL(a,r),s=await t(o,r),c=s.privy_oauth_state,l=s.privy_oauth_code;if(!c||!l)throw new k({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let u=await e.auth.oauth.loginWithCode(l,c,a,void 0,void 0,i),d=u.oauth_tokens;return d&&await e.crossApp.updateOnCrossAppAuthentication(n,d),u},Ka=({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 k({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 qa(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const Ja=(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)),Ya=({client:e,openAuthSession:t})=>{let n=Ka({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))},Xa=({client:e,openAuthSession:t})=>{let n=Ya({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=Ja(r,o);if(!s)throw new k({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 k({code:`cross_app_invalid_app`,error:`Invalid connected app`});if(u.read_only)throw new k({code:`cross_app_read_only`,error:`Cannot transact against a read-only provider app`});let d=await n({providerAppId:c,redirectUrl:a});if(!d)throw new k({code:`cross_app_request_error`,error:`Wallet operations require a valid token`});let f={content:{request:{request:i}},timestamp:Date.now(),callbackUrl:a},p=new URL(`${u.provider_app_custom_api_url}/oauth/transact`);p.searchParams.set(`communicationMode`,`redirect`),p.searchParams.set(`token`,d),p.searchParams.set(`request`,JSON.stringify(f));let{privy_cross_app_type:m,privy_cross_app_payload:h}=await t(p.href,a);if(!m||!h)throw new k({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(m===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new k({code:`cross_app_request_error`,error:h});if(m!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new k({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:h}}};function Za(e){if(!e)throw new k({code:`attempted_cross_app_request_before_logged_in`,error:`Must be logged in to sign messages with a cross-app wallet`})}const Qa=({client:e,openAuthSession:t})=>{let n=Xa({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{Za(e);let a={method:qa(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 $a(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 eo=({client:e,openAuthSession:t})=>{let n=Xa({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{Za(e);let a={method:qa(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,$a(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},to=({client:e,openAuthSession:t})=>{let n=Xa({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{Za(e);let a={method:qa(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var no=T({sendTransaction:()=>to,signMessage:()=>Qa,signTypedData:()=>eo}),ro=T({linkWithCrossAppAuth:()=>Ka,loginWithCrossAppAuth:()=>Ga,wallet:()=>no});function io(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 ao(e,t){let n=io(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 oo(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=ao(e.caip2,t);if(n)return{ok:!0,address:n};let r=io(e.caip2);if(!r)return{ok:!1,error:`UNSUPPORTED_CHAIN`};try{let t=await e.privy.fetchPrivyRoute(dt,{body:{chain_type:r}});return await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function so(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await oo({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(l,{body:{source_chain:e.sourceChain,source_currency:e.sourceCurrency,destination_chain:e.destinationChain,destination_currency:e.destinationCurrency,destination_address:e.destinationAddress,refund_address:n,...e.slippageBps==null?{}:{slippage_bps:e.slippageBps}}});return e.privy.track({name:`sdk_deposit_address_headless_quote`,properties:{sourceChain:e.sourceChain,sourceCurrency:e.sourceCurrency,destinationChain:e.destinationChain,destinationCurrency:e.destinationCurrency,depositAddressId:r.id}}),r}function co(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const X=async({operation:e,until:t,delay:n,interval:r,attempts:i,signal:a})=>{n&&await co(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 co(r)}catch(e){e instanceof Error&&(c=e),o<i&&await co(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},lo=2e3,uo=1800*1e3;function fo(e,t){return Math.ceil(t/e)}function po(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 mo(e){return await e.privy.fetchPrivyRoute(ue,{params:{order_id:e.orderId}})}async function ho(e){let t=e.pollIntervalMs??lo,n=e.timeoutMs??uo,r=e.signal??new AbortController().signal;return po(await X({operation:async()=>{let t=await e.privy.fetchPrivyRoute(fe,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(ue,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:fo(t,n),signal:r}))}async function go(e){let t=e.pollIntervalMs??lo,n=e.timeoutMs??uo,r=e.signal??new AbortController().signal;return po(await X({operation:()=>e.privy.fetchPrivyRoute(ue,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:fo(t,n),signal:r}))}var _o=T({generateDepositAddress:()=>so,getConfig:()=>vo,getDeposit:()=>mo,resolveRefundAddress:()=>oo,waitForCompletion:()=>go,waitForDeposit:()=>ho});async function vo(e){let t=await e.fetchPrivyRoute(de,{});return{currencies:t.currencies,chains:t.chains}}function yo(e){let t=e.depositAddressStrategy===void 0?{}:{deposit_address_strategy:e.depositAddressStrategy};return e.type===`deposit_config`?{type:`deposit_config`,deposit_config_id:e.depositConfigId,...t}:{type:`inline_route`,source:e.source,destination:e.destination,...t}}async function bo(e,t,n){let{walletId:r}=n,i=yo(n),a=e.getCompiledPath(s,{params:{wallet_id:r}}),o=String(Date.now()+Vn),{signature:c}=await M(t,{version:1,url:a,method:s.method,headers:{"privy-app-id":e.app.appId,[N]:o},body:i});if(Date.now()>Number(o))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});let l=await e.fetchPrivyRoute(s,{body:i,params:{wallet_id:r},headers:{"privy-authorization-signature":c,[N]:o}});return e.track({name:`sdk_deposit_address_headless_create`,properties:{version:`v3`,action:`create`,walletId:r,type:n.type,...n.type===`inline_route`?{destinationChain:n.destination.chain,destinationCurrency:n.destination.asset}:{depositConfigId:n.depositConfigId}}}),l}async function xo(e,t){let n=await e.fetchPrivyRoute(c,{body:{source:t.source,destination:t.destination,...t.inputAmount==null?{}:{input_amount:t.inputAmount},...t.slippageBps==null?{}:{slippage_bps:t.slippageBps}}});return e.track({name:`sdk_deposit_address_headless_quote`,properties:{version:`v3`,action:`quote`,sourceChain:t.source.chain,sourceCurrency:t.source.asset,destinationChain:t.destination.chain,destinationCurrency:t.destination.asset}}),n}function So(e){let t=Number(e.input_amount),n=Number(e.estimated_output_amount);if(!(!Number.isFinite(t)||!Number.isFinite(n)||t===0))return String(n/t)}async function Co(e,t){return e.fetchPrivyRoute(Ye,{query:{q:t}})}async function wo(e,t){return e.fetchPrivyRoute(le,{params:{wallet_id:t.walletId,order_id:t.orderId}})}async function To(e,t){return e.fetchPrivyRoute(ce,{params:{wallet_id:t.walletId},query:{after:t.after}})}const Eo={ethereum:`eip155:1`,arbitrum:`eip155:42161`,avalanche:`eip155:43114`,arc:`eip155:5042`,monad:`eip155:143`,base:`eip155:8453`,tempo:`eip155:4217`,linea:`eip155:59144`,optimism:`eip155:10`,polygon:`eip155:137`,bsc:`eip155:56`,zksync_era:`eip155:324`,solana:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,tron:`tron:mainnet`,robinhood:`eip155:4663`,unichain:`eip155:130`,worldchain:`eip155:480`,ink:`eip155:57073`,soneium:`eip155:1868`,megaeth:`eip155:4326`,hyperevm:`eip155:999`,hypercore:`eip155:1337`,"tempo_zone:00001":`eip155:421700001`,"tempo_zone:00002":`eip155:421700002`,tempo_testnet:`eip155:42431`,"tempo_testnet_zone:00003":`eip155:1424310003`,hoodi:`eip155:560048`,sepolia:`eip155:11155111`,arbitrum_sepolia:`eip155:421614`,avalanche_fuji:`eip155:43113`,base_sepolia:`eip155:84532`,linea_testnet:`eip155:59140`,optimism_sepolia:`eip155:11155420`,polygon_amoy:`eip155:80002`,bsc_testnet:`eip155:97`,solana_devnet:`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,solana_testnet:`solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`,tron_nile:`tron:nile`,robinhood_testnet:`eip155:46630`,ink_sepolia:`eip155:763373`},Do=[{id:`eth`,symbol:`ETH`},{id:`sol`,symbol:`SOL`},{id:`pol`,symbol:`POL`},{id:`trx`,symbol:`TRX`},{id:`usdc`,symbol:`USDC`},{id:`usdc_e`,symbol:`USDC.e`},{id:`usdt`,symbol:`USDT`},{id:`usdt0`,symbol:`USDT0`},{id:`usdb`,symbol:`USDB`},{id:`eurc`,symbol:`EURC`},{id:`ousd`,symbol:`OUSD`},{id:`usdg`,symbol:`USDG`},{id:`pathusd`,symbol:`PathUSD`}],Oo=new Set([`native`,`native-token`,`0x0000000000000000000000000000000000000000`,`11111111111111111111111111111111`]);function ko(e){return Oo.has(e.toLowerCase())}function Ao(e){return e.includes(`:`)}function Z(e){return Ao(e)?e:Eo[e.toLowerCase()]||(/^\d+$/.test(e)?`eip155:${e}`:e)}function jo(e){return ko(e)}function Mo(e){let t=e.toLowerCase();return Do.find(e=>e.id===t||e.symbol.toLowerCase()===t)}function No({symbol:e,address:t}){return Mo(e)?.id??t}function Po({asset:e,symbol:t,addresses:n}){let r=e.toLowerCase();return t.toLowerCase()===r?!0:jo(e)?n.some(ko):n.some(e=>e.toLowerCase()===r)}function Fo({config:e,chain:t,asset:n}){let r=t?Z(t):void 0;for(let t of e.currencies){let e=r?t.chains.filter(e=>Z(e.caip2)===r):t.chains;if(e.length!==0&&Po({asset:n,symbol:t.symbol,addresses:e.map(e=>e.address)}))return t.symbol}return n.toUpperCase()}function Io(e,t,n){return Lo(e,n)===Lo(t,n)}function Lo(e,t){let n=Z(e);if(n!==e||e.includes(`:`))return n;let r=e.toLowerCase();for(let n of Object.values(t.chains))if(n.caip2===e||n.display_name.toLowerCase()===r||String(n.chain_id)===e)return n.caip2;return n}function Ro(e,t){return Po({asset:t.asset,symbol:e.symbol,addresses:e.chains.map(e=>e.address)})}function zo({caip2:e,asset:t,config:n}){return!t.chain||Io(t.chain,e,n)}function Bo({currency:e,source:t,config:n}){switch(t.mode){case`all`:return e.chains;case`include`:{let r=t.values.filter(t=>Ro(e,t));return r.length===0?[]:e.chains.filter(e=>r.some(t=>zo({caip2:e.caip2,asset:t,config:n})))}case`exclude`:{let r=t.values.filter(t=>Ro(e,t));return r.length===0?e.chains:e.chains.filter(e=>!r.some(t=>zo({caip2:e.caip2,asset:t,config:n})))}default:return e.chains}}function Vo(e,t){return{currencies:e.currencies.map(n=>({...n,chains:Bo({currency:n,source:t,config:e})})).filter(e=>e.chains.length>0),chains:e.chains}}function Ho(e){return e.startsWith(`0x`)}function Uo(e,t){let n=Ho(e);switch(t){case`evm`:case`hypevm`:return n;case`svm`:case`bvm`:case`tron`:case`tvm`:return!n;default:return n}}function Wo(e,t){let n=Z(t);switch(e.source.mode){case`all`:return!0;case`include`:return e.source.values.some(e=>!e.chain||Z(e.chain)===n);case`exclude`:return!e.source.values.some(e=>!e.chain||Z(e.chain)===n);default:return e.source,!1}}function Go({accounts:e,selectedChain:t}){if(e.length===0)return;let n=e.filter(e=>Wo(e,t.caip2)),r=n.length>0?n:e,i=r.find(e=>Uo(e.deposit_address,t.vmType));return i?i.deposit_address:r[0]?.deposit_address}var Ko=T({createCryptoDepositAccount:()=>bo,filterDepositConfig:()=>Vo,findCatalogSymbol:()=>Fo,getCryptoDepositAccountNextOrder:()=>To,getCryptoDepositAccountOrder:()=>wo,getCryptoDepositAccountQuote:()=>xo,indicativeRateFromQuote:()=>So,isNativeAssetAlias:()=>jo,pickDepositAddressForChain:()=>Go,quoteSourceAsset:()=>No,resolveChainAlias:()=>Z,searchCryptoDepositAccountConfig:()=>Co});async function qo(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(ht,{params:{wallet_id:n}}),a=String(Date.now()+Vn),{signature:o}=await M(t,{version:1,url:i,method:ht.method,headers:{"privy-app-id":e.app.appId,[N]:a},body:{...r}});if(Date.now()>Number(a))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(ht,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[N]:a}})}async function Jo(e,{wallet_id:t}){return await e.fetchPrivyRoute(ft,{params:{wallet_id:t}})}async function Yo(e,{wallet_id:t},n,r){let{signature:i}=await M(n,{version:1,url:e.getCompiledPath(vt,{params:{wallet_id:t}}),method:vt.method,headers:{"privy-app-id":e.app.appId},body:r});return await e.fetchPrivyRoute(vt,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":i}})}async function Xo(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(_t,{params:{wallet_id:n}}),a=String(Date.now()+Vn),{signature:o}=await M(t,{version:1,url:i,method:_t.method,headers:{"privy-app-id":e.app.appId,[N]:a},body:{...r}});if(Date.now()>Number(a))throw new k({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(_t,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[N]:a}})}async function Zo(e,{wallet_id:t,action_id:n}){return await e.fetchPrivyRoute(pt,{params:{wallet_id:t,action_id:n}})}async function Qo(e,{wallet_id:t,...n}){return await e.fetchPrivyRoute(mt,{params:{wallet_id:t},query:{...n.cursor?{cursor:n.cursor}:{},...n.limit===void 0||n.limit===null?{}:{limit:n.limit},...n.type?{type:n.type}:{}}})}async function $o({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(A(t)){if(n.length===0)throw Error(`Must specify at least one signer to add.`);let r={wallet_id:t.id},i=await Jo(e,r);await Yo(e,r,ns(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return ts(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=Va(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 ts(e)}async function es({client:e,wallet:t}){return A(t)?await Yo(e,{wallet_id:t.id},ns(e),{additional_signers:[]}):await e.delegated.revoke(),ts(e)}async function ts(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function ns(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var rs=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 is=async(t,{environment:n,acceptElectronicDisclosure:r,acceptBankTerms:i})=>{let{data:a}=await t.fetchPrivyRoute(e,{body:{environment:n,accept_electronic_disclosure:r,accept_bank_terms:i}});return a},as=async({sendTransaction:e,evmChainId:t,stablecoinAddress:n,spenderAddress:r})=>{let i={to:n,chainId:t,data:It({abi:Lt,functionName:`approve`,args:[r,Ht]})};try{return await e(i,{sponsor:!0})}catch(t){return console.warn(`[privy] Sponsored card approval failed; retrying pre-funded.`,t instanceof Error?t.message:String(t)),e(i,{sponsor:!1})}},os=[{type:`function`,name:`publicCall`,stateMutability:`nonpayable`,inputs:[{name:`data`,type:`bytes`}],outputs:[]},{type:`function`,name:`publicGetCall`,stateMutability:`view`,inputs:[{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bytes`}]}],ss=async({sendTransaction:e,evmChainId:t,spenderAddress:n,vaultAddress:r})=>{let i={to:n,chainId:t,data:It({abi:os,functionName:`publicCall`,args:[Mt([Ut(`TEUP`),r])]})};try{return await e(i,{sponsor:!0})}catch(t){return console.warn(`[privy] Sponsored card vault choice failed; retrying pre-funded.`,t instanceof Error?t.message:String(t)),e(i,{sponsor:!1})}},cs=async(e,{environment:t,walletId:n,chainId:r,asset:i})=>e.fetchPrivyRoute(o,{body:{environment:t,wallet_id:n,chain_id:r,asset:i}}),Q=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(ie,{query:{environment:t}});return n},ls=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(ut,{body:{environment:t}});return n},us=async(e,{environment:t,limit:n,cursor:r})=>e.fetchPrivyRoute(ge,{query:{environment:t,...n===void 0?{}:{limit:n},...r?{cursor:r}:{}}}),ds=20,fs=async({provider:e,evmChainId:t,owner:n,stablecoinAddress:r,spenderAddress:i})=>{await e.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${t.toString(16)}`}]});let a=await e.request({method:`eth_call`,params:[{to:r,data:It({abi:Lt,functionName:`allowance`,args:[n,i]})},`latest`]});if(!Vt(a)||a===`0x`)throw Error(`Could not read the spend approval`);return Ft({abi:Lt,functionName:`allowance`,data:a})},ps=async({provider:e,evmChainId:t,owner:n,spenderAddress:r})=>{await e.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${t.toString(16)}`}]});let i=await e.request({method:`eth_call`,params:[{to:r,data:It({abi:os,functionName:`publicGetCall`,args:[Mt([Ut(`TEGP`),n])]})},`latest`]});if(!Vt(i)||i===`0x`)throw Error(`Could not read the card vault choice`);let[a]=Pt([{type:`address`}],Ft({abi:os,functionName:`publicGetCall`,data:i}));return a},ms=2e3,hs=1e3,gs=new Map([[`morpho`,`Morpho`],[`aave`,`Aave`]]),_s=e=>{switch(e.status){case`kyc_required`:return{kind:`kyc`,url:e.kyc_url};case`provider_terms_required`:return{kind:`provider`,url:e.tos_url};default:return null}},vs=e=>{try{return new URL(e).protocol===`https:`?e:null}catch{return null}},$=e=>e instanceof Error&&e.message?e.message:void 0,ys=({client:e,environment:t,walletId:n,chainId:r,asset:i,platform:a})=>{let o=null,s=e=>{o=e,a.setStep(e)},c=null,l=null,u=null,d=i=>{let o=u;if(!o)return a.resolveSpendApproval();if(!r.startsWith(`eip155:`))return{kind:`unsupported`};let{spenderAddress:s,shareTokenAddress:c}=o,d=a.resolveEvmWallet(),f=Number(r.slice(7)),p=async()=>fs({provider:await d.getProvider(),evmChainId:f,owner:d.address,stablecoinAddress:c,spenderAddress:s}),m=async()=>ps({provider:await d.getProvider(),evmChainId:f,owner:d.address,spenderAddress:s});return{kind:`supported`,isApproved:async()=>await p()>0n&&(o.kind!==`opt_in`||await m()!==Gt),approve:async()=>{if(await as({sendTransaction:d.sendTransaction,evmChainId:f,stablecoinAddress:c,spenderAddress:s}),o.kind!==`opt_in`)return;let a=await X({operation:p,until:e=>e>0n,delay:0,interval:hs,attempts:60,signal:i});if(a.status===`aborted`)return;if(a.status===`max_attempts`)throw Error(`The share approval did not land in time`,{cause:a.error});let u=await m();if(i.aborted||u!==Gt)return;await ss({sendTransaction:d.sendTransaction,evmChainId:f,spenderAddress:s,vaultAddress:o.vaultAddress});let h=await X({operation:m,until:e=>e.toLowerCase()===o.vaultAddress.toLowerCase(),delay:0,interval:hs,attempts:60,signal:i});if(h.status===`max_attempts`)throw Error(`The vault choice did not land in time`,{cause:h.error});h.status===`success`&&l&&e.track({name:`sdk_card_sign_up_tempo_earn_opt_in`,properties:{cardId:l,walletId:n,chainId:r,environment:t,vaultAddress:o.vaultAddress}})}}},f=async(e,t)=>{if(t.aborted)return;l=e;let n={status:`approve-prompt`,vaultProvider:u?.providerName??null},r;try{r=d(t)}catch{s(n);return}if(r.kind===`unsupported`){s(r.reason?{status:`error`,message:r.reason,cardId:e}:{status:`error`,cardId:e});return}try{let i=await r.isApproved();if(t.aborted)return;s(i?{status:`ready`,cardId:e}:n)}catch{t.aborted||s(n)}},p=async a=>{if(!a.aborted)try{let o=await us(e,{environment:t,limit:20});if(a.aborted)return;let c=o.data.find(e=>e.wallet_id===n&&e.chain_id===r&&e.asset===i&&e.status!==`replaced`);if(c||=(s({status:`creating-card`}),await cs(e,{environment:t,walletId:n,chainId:r,asset:i})),a.aborted)return;let l=c.funding_sources,d=l?.find(e=>e.selected),p;if(d?.type===`erc4626_vault`?p=gs.get(d.provider):d?.type===`tempo_earn_vault`&&(p=`Tempo`),l&&!d||d&&d.type!==`wallet`&&!p){console.warn(`[privy] Card funding source is not supported by this SDK version`,{type:d?.type,provider:d?.type===`erc4626_vault`?d.provider:void 0}),s({status:`error`,cardId:c.id});return}if(u=null,d&&d.type!==`wallet`&&p)u={kind:`selected`,spenderAddress:d.spender_address,shareTokenAddress:d.share_token_address,providerName:p};else{let e=c.funding_sources?.find(e=>e.type===`tempo_earn_vault`);e&&(u={kind:`opt_in`,spenderAddress:e.spender_address,shareTokenAddress:e.share_token_address,providerName:`Tempo`,vaultAddress:e.vault_address})}await f(c.id,a)}catch(e){if(a.aborted)return;s({status:`error`,message:$(e)})}},m=async n=>{let r=0;for(;!n.aborted;){if(++r>10){s({status:`error`});return}let i;try{i=await Q(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}if(n.aborted)return;switch(i.status){case`not_created`:try{await ls(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}continue;case`electronic_disclosure_required`:s({status:`disclosure-prompt`,disclosureUrl:i.disclosure_url});return;case`bank_terms_required`:s({status:`bank-terms-prompt`,bankInfo:i.bank_info});return;case`provider_terms_required`:c={kind:`provider`,url:i.tos_url},s({status:`provider-terms-prompt`});return;case`kyc_required`:c={kind:`kyc`,url:i.kyc_url},s({status:`kyc-prompt`});return;case`pending`:if(s({status:`pending`}),(await X({operation:()=>Q(e,{environment:t}),until:e=>e.status!==`pending`,delay:0,interval:ms,attempts:60,signal:n})).status!==`success`)return;continue;case`under_review`:s({status:`under-review`});return;case`ready`:await p(n);return;case`rejected`:s({status:`rejected`,reason:i.rejection_reasons?.[0]?.reason});return;case`error`:s({status:`error`});return;default:return}}},h=async({page:n,url:r,until:i,signal:o})=>{let s=vs(r);if(!s)return n?.dismiss(),`blocked`;let c=n??a.openHostedPage(s);if(!c)return`blocked`;n&&n.navigate(s);let l=await X({operation:()=>Q(e,{environment:t}),until:e=>i(e)||c.isClosed(),delay:0,interval:ms,attempts:60,signal:o});if(l.status===`aborted`)return c.dismiss(),`aborted`;if(l.status===`max_attempts`)return`stalled`;if(i(l.result))return c.dismiss(),`advanced`;let u=await X({operation:()=>Q(e,{environment:t}),until:i,delay:0,interval:1e3,attempts:5,signal:o});return u.status===`aborted`?(c.dismiss(),`aborted`):u.status===`success`?`advanced`:`closed`},ee=async(n,r)=>{c=null,s({status:n===`provider`?`provider-terms-prompt`:`kyc-prompt`,pending:!0});try{let n=await Q(e,{environment:t});if(r.aborted)return;let i=_s(n);if(i){c=i,s({status:i.kind===`provider`?`provider-terms-prompt`:`kyc-prompt`});return}}catch(e){r.aborted||s({status:`error`,message:$(e)});return}await m(r)},te=async n=>{s({status:`loading`});let r;try{r=await Q(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}if(!n.aborted)switch(r.status){case`not_created`:case`electronic_disclosure_required`:case`bank_terms_required`:case`provider_terms_required`:case`kyc_required`:case`pending`:case`ready`:s({status:`get-started`});return;case`under_review`:s({status:`under-review`});return;case`rejected`:s({status:`rejected`,reason:r.rejection_reasons?.[0]?.reason});return;case`error`:s({status:`error`});return;default:}};return{load:te,start(e){s({status:`get-started`,pending:!0}),m(e)},acceptDisclosure(n){(async()=>{s({status:`accepting-disclosure`});try{await is(e,{environment:t,acceptElectronicDisclosure:!0})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}n.aborted||await m(n)})()},acceptBankTerms(n){let r=a.openHostedPage();(async()=>{s({status:`accepting-bank-terms`});let i;try{i=await is(e,{environment:t,acceptBankTerms:!0})}catch(e){r?.dismiss(),n.aborted||s({status:`error`,message:$(e)});return}if(n.aborted){r?.dismiss();return}if(i.status===`provider_terms_required`){s({status:`accepting-provider-terms`});let e=await h({page:r,url:i.tos_url,until:e=>e.status!==`provider_terms_required`,signal:n});if(e===`aborted`)return;if(e===`blocked`){s({status:`error`});return}if(e===`closed`||e===`stalled`){await ee(`provider`,n);return}await m(n);return}r?.dismiss(),await m(n)})()},proceed(e){let t=c;t&&(async()=>{s({status:t.kind===`provider`?`accepting-provider-terms`:`verifying-identity`});let n=t.kind===`provider`?e=>e.status!==`provider_terms_required`:e=>e.status===`ready`||e.status===`rejected`||e.status===`pending`||e.status===`under_review`,r=await h({url:t.url,until:n,signal:e});if(r!==`aborted`){if(r===`blocked`){s({status:`error`});return}if(r===`closed`||r===`stalled`){await ee(t.kind,e);return}await m(e)}})()},approve(e){let t=l;if(!t)return;let n=o?.status===`approve-error`;(async()=>{s({status:`approve-prompt`,pending:!0,vaultProvider:u?.providerName??null});let r;try{r=d(e)}catch(e){s({status:`error`,message:$(e),cardId:t});return}if(r.kind===`unsupported`){s(r.reason?{status:`error`,message:r.reason,cardId:t}:{status:`error`,cardId:t});return}if(n){try{if(await r.isApproved()){e.aborted||s({status:`ready`,cardId:t});return}}catch{}if(e.aborted)return}try{if(await r.approve(),e.aborted)return;s({status:`ready`,cardId:t})}catch(n){if(e.aborted)return;console.error(`[privy] Card spending approval failed after card creation`,n),s({status:`approve-error`,cardId:t})}})()},retry(e){te(e)}}},bs=async(e,{cardId:t,environment:n,statementPeriod:r})=>(await e.fetchPrivyRouteRaw(f,{params:{card_id:t,statement_period:r},query:{environment:n}})).blob(),xs=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),Ss=e=>Number.isFinite(e)?xs.format(Math.abs(e)/100):``,Cs=({amount:e,status:t})=>e===0?`none`:t===`posted`&&e>0?`credit`:`debit`,ws=({amount:e,status:t})=>{if(!Number.isFinite(e))return{text:``,isCredit:!1};let n=Ss(e);switch(Cs({amount:e,status:t})){case`credit`:return{text:`+ ${n}`,isCredit:!0};case`debit`:return{text:`- ${n}`,isCredit:!1};case`none`:return{text:n,isCredit:!1}}},Ts={month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`},Es=new Intl.DateTimeFormat(void 0,Ts),Ds=new Intl.DateTimeFormat(void 0,{...Ts,year:`numeric`}),Os=({unixSeconds:e})=>{let t=new Date(e*1e3);return Number.isNaN(t.getTime())?``:(t.getFullYear()===new Date().getFullYear()?Es:Ds).format(t)},ks={usdc:`USDC`,pathusd:`PathUSD`,path_usd:`PathUSD`,ousd:`OUSD`},As=e=>e?ks[e.toLowerCase()]??e:``,js=async(e,{cardId:t,environment:n})=>{let{data:r}=await us(e,{environment:n,limit:20});return r.find(e=>e.id===t)??null},Ms=e=>`The Prepaid Debit Visa Card (the “Card”) is issued by Lead Bank pursuant to licensing by Visa U.S.A. Inc. and may be used everywhere Visa is accepted. Must be 18 or older to apply. Fees may apply. See Cardholder Agreement and ${e} website for more details.\n\nBridge Ventures LLC (“Bridge”) is not a bank. Bridge is a financial technology company and is the Program Manager responsible for managing and operating the Card on behalf of Lead Bank. ${e} is not a bank. ${e} is a financial technology company and is the Platform Provider responsible for the application, access, and management of/for the card.`,Ns=async(e,{cardId:t,environment:n,nonce:r})=>{let{data:i}=await e.fetchPrivyRoute(ae,{params:{card_id:t},body:{environment:n,nonce:r}});return i.ephemeral_key_secret},Ps=async(e,{appId:t,environment:n})=>{let{data:r}=await e.fetchPrivyRoute(oe,{params:{app_id:t},query:{environment:n}});return{publishableKey:r.publishable_key,cardLogoUrl:r.card_logo_url??null,stripeAccount:r.stripe_account}},Fs=`eip155:42431`,Is=[`eip155:11155111`,`eip155:11155420`,`eip155:80002`,`eip155:84532`,`eip155:421614`,`eip155:43113`],Ls=[`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,`solana:devnet`],Rs={...Object.fromEntries(Is.flatMap(e=>{let t=na[Number.parseInt(e.replace(`eip155:`,``))];return t?[[e,{stablecoinAddress:t,spenderAddress:`0x8cc0d9e8a157b73d1172a22f5066048bda46c0e3`}]]:[]})),[Fs]:{stablecoinAddress:`0x20C0000000000000000000000000000000000000`,spenderAddress:`0x1955a82a01E8c0A31371792b3045341eB8b938e2`},...Object.fromEntries(Ls.map(e=>[e,{stablecoinAddress:ra.devnet,programId:`cardWArqhdV5jeRXXjUti7cHAa4mj41Nj3Apc6RPZH2`,merchantId:1n}]))},zs=(e,t)=>{let n=Rs[e];if(n)return t===`ousd`&&e===Fs&&`spenderAddress`in n?{...n,stablecoinAddress:`0x20c0000000000000000000006a37DA5C996874BE`}:n},Bs={"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":`solana:mainnet`,"solana:mainnet":`solana:mainnet`,"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":`solana:devnet`,"solana:devnet":`solana:devnet`},Vs=(e,t,n)=>{let r=t??zs(e,n);if(!r)return null;let i=Bs[e];return i?`programId`in r?{...r,kind:`svm`,chain:i,merchantId:BigInt(r.merchantId)}:Hs(e,t):e.startsWith(`eip155:`)&&`spenderAddress`in r?{kind:`evm`,...r}:Hs(e,t)},Hs=(e,t)=>(t&&console.warn(`[privy] Ignoring the spendApproval option for "${e}": its shape does not match the chain (an eip155:* chain needs an EvmDevSpendApprovalTarget, a solana:* chain an SvmDevSpendApprovalTarget), or the chain is not a recognized spend-approval target.`),null),Us=e=>e.status===`pending`?`pending`:e.status===`declined`?`declined`:e.status===`expired`?`expired`:e.status===`reversed`?`reversed`:Cs(e)===`credit`?`credit`:null,Ws=({step:e,onSuccess:t,onFailure:n})=>{switch(e.status){case`ready`:case`approve-error`:t({id:e.cardId});return;case`under-review`:n(Error(`Card application is under review`));return;case`rejected`:n(Error(e.reason??`Card application was rejected`));return;case`error`:if(e.cardId){t({id:e.cardId});return}n(Error(e.message??`Card sign-up failed`));return;default:n(Error(`User cancelled card sign-up`))}},Gs=({exp_month:e,exp_year:t})=>{if(e===null||t===null)return!1;let n=new Date,r=n.getFullYear(),i=n.getMonth()+1;return t<r||t===r&&e<i},Ks=async(e,{cardId:t,environment:n,limit:r,cursor:i})=>e.fetchPrivyRoute(he,{params:{card_id:t},query:{environment:n,...r===void 0?{}:{limit:r},...i?{cursor:i}:{}}}),qs=async(e,{cardId:t,environment:n,reason:r})=>e.fetchPrivyRoute(Je,{params:{card_id:t},body:{environment:n,replacement_reason:r}}),Js=({transaction:e,unknownMerchantName:t})=>({id:e.id,amount:e.amount,merchant:{name:e.merchant.name??t},status:e.status,created:e.created,currency:e.currency,dispute:e.dispute}),Ys=async(e,{cardId:t,environment:n,encryptedNumber:r})=>e.fetchPrivyRoute(lt,{params:{card_id:t},body:{environment:n,pin:{encrypted_number:r}}}),Xs=async(e,{cardId:t,environment:n,status:r})=>e.fetchPrivyRoute(ct,{params:{card_id:t},body:{environment:n,status:r}}),Zs=`biconomy`,Qs=`coinbase_smart_wallet`,$s=`kernel`,ec=`light_account`,tc=`safe`,nc=`thirdweb`,rc=`nexus`;var ic=zi;export{Pa as ALL_WALLET_CLIENT_TYPES,Zs as BICONOMY,Qs as COINBASE_SMART_WALLET,rs as ConnectedStandardSolanaWallet,_n as DATA_SUFFIX_PLUGIN_ID,Nn as EmbeddedProviderError,Vi as InMemoryCache,$s as KERNEL,ec as LIGHT_ACCOUNT,ds as LIST_CARDS_MAX_LIMIT,Bi as LocalStorage,Cn as MoonpayApiError,rc as NEXUS,O as PrivyApiError,k as PrivyClientError,Mn as PrivyConnectorError,On as PrivyEmbeddedWalletErrorCode,Bn as PrivyProviderRpcError,j as ProviderErrors,tc as SAFE,Fa as SUPPORTED_CONNECTOR_TYPES,ya as SolanaClient,ra as SolanaUsdcAddressMap,nc as THIRDWEB,na as UsdcAddressMap,is as acceptCardConsents,$o as addSessionSigners,as as approveSpend,Da as buildSolanaOffchainMessage,ki as chainToMoonpayCurrency,ss as chooseTempoEarnVault,R as cookies,Qi as countryCodesAndNumbers,Dr as create,cs as createCard,ys as createCardSignUp,yn as createDataSuffixPlugin,Tn as createErrorFormatter,ba as createSiwsMessage,ro as crossApp,Ko as cryptoDepositAccount,ic as default,Wa as delegatedActions,_o as depositAddress,Ea as deriveSolanaApplicationDomain,bs as downloadCardStatement,Rn as errorIndicatesMaxMfaRetries,En as errorIndicatesMfaCanceled,zn as errorIndicatesMfaRateLimit,In as errorIndicatesMfaTimeout,Ln as errorIndicatesMfaVerificationFailed,Fn as errorIndicatesRecoveryIsNeeded,za as formatLamportsAmount,Yi as formatPhoneNumber,ws as formatSignedTransactionAmount,Ra as formatTokenAmount,Os as formatTransactionDate,Ss as formatUsdAmount,Ia as formatWalletAddress,La as formatWeiAmount,Ai as fundingMethodToMoonpayPaymentMethod,M as generateAuthorizationSignature,aa as generateWalletIdempotencyKey,Hi as getAllUserEmbeddedBitcoinWallets,Zr as getAllUserEmbeddedEthereumWallets,$r as getAllUserEmbeddedSolanaWallets,As as getCardAssetDisplayName,js as getCardById,Q as getCardCustomer,Ms as getCardDisclosure,Ns as getCardEphemeralKey,Ps as getCardsConfig,fa as getCoinbaseOnRampUrl,ln as getCountryCallingCode,vn as getDataSuffixPlugin,Gi as getEntropyDetailsFromAccount,Wi as getEntropyDetailsFromUser,va as getFiatOnrampProviderBrand,ga as getFiatOnrampProviderId,ia as getIsTokenUsdc,ir as getJsonRpcEndpointFromChain,ls as getOrCreateCardCustomer,ea as getPhoneCountryCodeAndNumber,$i as getPlaceholderPhoneNumber,Ca as getSolanaClusterDisplayName,xa as getSolanaRpcEndpointForCluster,Sa as getSolanaUsdcMintAddressForCluster,Vs as getSpendApproval,Us as getTransactionBadge,K as getUserEmbeddedEthereumWallet,ei as getUserEmbeddedSolanaWallet,Qr as getUserEmbeddedWallet,Ki as getUserSmartWallet,Jo as getWallet,Zo as getWalletAction,Ws as handleSignUpClose,Gs as isCardExpired,Xr as isEmbeddedWalletAccount,Nr as isExtensionContext,pa as isSupportedChainIdForCoinbaseOnramp,Oi as isSupportedChainIdForMoonpay,A as isUnifiedWallet,Xi as lastFourDigits,Ks as listCardTransactions,us as listCards,Qo as listWalletActions,Oa as parseSolanaOffchainMessage,Zi as phoneNumberTypingFormatter,X as poll,qo as rawSign,fs as readSpendAllowance,ps as readTempoEarnVault,es as removeSessionSigners,qs as replaceCard,P as rpc,Pr as shouldWriteSessionCookies,ar as throwIfInvalidRecoveryUpgradePath,ha as toCoinbaseAssetId,ma as toCoinbaseBlockchainFromChainId,Ji as toE164,ta as toObjectKeys,Js as toTransactionRow,Hn as toWalletApiUnsignedEthTransaction,Xo as transfer,Ys as updateCardPin,Xs as updateCardStatus,Yo as updateWallet,qi as validatePhoneNumber};
|
|
35
35
|
//# sourceMappingURL=index.mjs.map
|