@privy-io/js-sdk-core 0.79.0 → 0.79.2
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/cjs/tempoChains-C7o70PSk.js +1 -0
- package/dist/dts/index.d.mts +65 -17
- package/dist/dts/index.d.ts +65 -17
- package/dist/esm/index.mjs +4 -4
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/tempoChains-CJGgHPcv.mjs +1 -0
- package/package.json +7 -7
package/dist/cjs/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require("@privy-io/routes"),u=require("jose");u=c(u);let d=require("@privy-io/chains"),f=require("eventemitter3");f=c(f);let p=require("viem"),m=require("@privy-io/ethereum"),h=require("canonicalize");h=c(h);let g=require("@privy-io/encoding"),_=require("viem/chains"),ee=require("@scure/base"),te=require("@privy-io/api-base"),ne=require("@privy-io/std/retry-fetch"),v=require("js-cookie");v=c(v);let re=require("fetch-retry");re=c(re);let ie=require("libphonenumber-js/examples.mobile.json");ie=c(ie);let y=require("libphonenumber-js/min");function ae(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}const b=e=>/^0x[0-9a-fA-F]*$/.test(e),oe=e=>Buffer.from(e,`utf8`),x=e=>`0x${e.toString(`hex`)}`,se=Symbol(`data-suffix-plugin`);function ce(e=[]){return e.find(e=>e.id===se)}function le(e){let t=e.startsWith(`0x`)?e:`0x${e}`;if(!b(t))throw Error(`[Privy] dataSuffix: Invalid suffix "${e}" is not valid hex`);let n=t.slice(2);return{id:se,suffix:t,appendDataSuffix:({data:e})=>!e||e===`0x`?t:`${e}${n}`}}var ue=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(l.GetSmartWalletConfig,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},S=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=u.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}},de=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 S(r).isExpired())throw Error(`JWT is expired`);return r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(l.GetCrossAppConnections,{params:{app_id:this._privyInternal.appId}})}},fe=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(l.WalletsRevoke,{})}},C=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}},w=class extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}},pe=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 me(e){return e instanceof C||e instanceof w?e.code:`unknown_error`}const he=e=>t=>e[me(t)]??e.default;function ge(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}const T=e=>!!e.id&&e.recovery_method===`privy-v2`,_e=[`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 ve=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 ye=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}]`:``}`}},be=class extends ye{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},xe=class extends Error{type;constructor(e,t){super(t),this.type=e}},Se=class extends ye{type=`connector_error`;constructor(e,t,n){super(e,t,n)}},Ce=class extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}};const E={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 D(e){let t=e.type;return typeof t==`string`&&_e.includes(t)}function we(e){return D(e)&&e.type===`wallet_not_on_device`}function Te(e){return D(e)&&e.type===`mfa_timeout`}function Ee(e){return D(e)&&e.type===`missing_or_invalid_mfa`}function De(e){return D(e)&&e.type===`mfa_verification_max_attempts_reached`}function Oe(e){return D(e)&&e.message.includes(`code 429`)}var ke=class extends be{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(E).find(e=>e.eipCode===t.code);this.details=n||E.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=E.E32002_CONNECTION_ALREADY_PENDING:this.details=E.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=E.E32002_WALLET_LOCKED))}};async function O(e,t){let n;if(t instanceof Uint8Array)n=g.encoding.base64.fromBytes(t);else{let e=(0,h.default)(t);if(e===void 0)throw new w({error:`Failed to prepare the payload for signing`,code:`invalid_input`});n=g.encoding.base64.fromBytes(g.encoding.utf8.toBytes(e))}let{signature:r}=await e({message:n});return{signature:r}}const k=`privy-request-expiry`,A=1800*1e3;async function j(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath(l.WalletRpc,{params:{wallet_id:n}}),o=String(Date.now()+A),{signature:s}=await O(t,{version:1,url:a,method:l.WalletRpc.method,headers:{"privy-app-id":e.app.appId,[k]:o},body:{...i}});if(Date.now()>Number(o))throw new w({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(l.WalletRpc,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[k]:o,...r??{}}})}function Ae(e){return(0,m.isTempoTransactionRequest)(e)?Me(e):je(e)}function je(e){return{from:e.from,to:e.to??void 0,nonce:M(e.nonce),chain_id:M(e.chainId),data:Ie(e.data),value:M(e.value),type:Re(e.type),gas_limit:M(e.gasLimit??e.gas),gas_price:M(e.gasPrice),max_fee_per_gas:M(e.maxFeePerGas),max_priority_fee_per_gas:M(e.maxPriorityFeePerGas)}}function Me(e){return{type:m.TEMPO_TXN_TYPE_NUMBER,from:e.from,chain_id:M(e.chainId),nonce:M(e.nonce),nonce_key:M(e.nonceKey),gas_limit:M(e.gasLimit),max_fee_per_gas:M(e.maxFeePerGas),max_priority_fee_per_gas:M(e.maxPriorityFeePerGas),fee_token:e.feeToken,valid_after:M(e.validAfter),valid_before:M(e.validBefore),fee_payer_signature:Pe(e.feePayerSignature),access_list:Ne(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:M(e.value)}))}}function Ne(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 Pe(e){if(!e)return;let t=Fe(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 Fe(e){if(e.yParity!==void 0)return e.yParity;if(e.v!==void 0)return Number(e.v)-27}function Ie(e){if(e!==void 0)return typeof e==`string`?b(e)?e:x(oe(e)):x(Buffer.from(Uint8Array.from(e)))}const Le=[0,1,2,4];function Re(e){if(e==null)return;let t=Number(e);if(!ze(t))throw Error(`Invalid transaction type: expected ${Le.join(`, `)} as a number or hex string, got "${e}".`);return t}function ze(e){return Le.includes(e)}function M(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(b(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 Be(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 Ve({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return He({context:e,account:t,rpcRequest:n.request});case`solana`:return Ue({context:e,account:t,rpcRequest:n.request})}}async function He({context:e,account:t,rpcRequest:n}){switch(n.method){case`personal_sign`:{let[r]=n.params,i=await j(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 j(e,e.signRequest,{chain_type:`ethereum`,method:`eth_signTransaction`,wallet_id:t.id,params:{transaction:Ae(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 j(e,e.signRequest,{chain_type:`ethereum`,method:n.method,wallet_id:t.id,params:{typed_data:Be(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 j(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:b(r)?r:x(oe(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 j(e,e.signRequest,{chain_type:`ethereum`,method:`secp256k1_sign`,wallet_id:t.id,params:{hash:b(r)?r:x(oe(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 Ue({context:e,account:t,rpcRequest:n}){switch(n.method){case`signMessage`:{let{message:r}=n.params,i=await j(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 j(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 We=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new Se(`Unsupported chainId ${e}`,4901);let o=Ke(a,n,r.appId);if(i===_.tempo.id||i===_.tempoModerato.id){let e=i===_.tempo.id?_.tempo:_.tempoModerato;return(0,p.createPublicClient)({transport:(0,p.http)(o),chain:e})}return(0,p.createPublicClient)({transport:(0,p.http)(o),chain:a})};function Ge(e){return e===_.tempo.id||e===_.tempoModerato.id}const Ke=(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 Se(`No RPC url found for ${r}`);return a};function qe({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 Je=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var Ye=class extends f.default{_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=We(s,a,{rpcUrls:[]},{appId:c.appId}),this._appApi=c,this._dataSuffixPlugin=l}async request(e){if(Je.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||(0,m.isTempoTransactionRequest)(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=We(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit(`chainChanged`,e))}async handlePopulateTransaction(e){let t=this.ensureChainId(e);if((0,m.isTempoTransactionRequest)(t)){let e=(0,m.toViemTempoTransactionSerializable)(t),n=(0,m.normalizeViemPreparedTempoTransaction)(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:m.TEMPO_TXN_TYPE_NUMBER}}let n=(0,m.toViemTransactionSerializable)(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:m.STRING_TO_NUMBER_TXN_TYPE[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]=(0,p.toHex)(n))}return(0,m.isTempoTransactionRequest)(t)&&(t.calls=t.calls.map(e=>({...e,value:typeof e.value==`bigint`?(0,p.toHex)(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((0,m.isTempoTransactionRequest)(n)){let e=(0,m.toViemTempoTransactionSerializable)(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=(0,m.toViemTransactionSerializable)(n);return await this._client.estimateGas({account:n.from??this._account.address,...r})}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new Ce(`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 Ce(`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(T(n)){let{data:r}=await Ve({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=we(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 w({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 w({code:`embedded_wallet_request_error`,error:n})}}async handleJsonRpc(e){return this._client.request(e)}requireTempoClient(){if(!Ge(this._chainId))throw new Ce(`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 Xe(e){return`version`in e}function Ze(e,t){let n=(Xe(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 Qe({transaction:e,address:t}){let{messageBytes:n,signerAddresses:r}=et(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 $e({transaction:e,signerIndex:t,signature:n}){if(n.length!==64)throw Error(`Solana signatures must be 64 bytes`);let{signaturesOffset:r,signerAddresses:i}=et(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 et(e){if(e.length===0)throw Error(`Cannot decode an empty Solana transaction`);return e[0]===129?tt(e):nt(e)}function tt(e){let t=N(e,1),n=e.length-t*64;if(n<=41)throw Error(`Malformed V1 Solana transaction`);let r=e.subarray(0,n);if(N(r,41)<t)throw Error(`Malformed V1 Solana transaction`);return{messageBytes:r,signaturesOffset:n,signerAddresses:it(r,42,t)}}function nt(e){let[t,n]=rt(e,0),r=n+t*64,i=N(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=N(e,a);if(o!==t)throw Error(`Solana transaction signature count does not match its message header`);let[s,c]=rt(e,a+3);if(s<o)throw Error(`Malformed Solana transaction`);return{messageBytes:e.subarray(r),signaturesOffset:n,signerAddresses:it(e,c,o)}}function N(e,t){let n=e[t];if(n===void 0)throw Error(`Malformed Solana transaction`);return n}function rt(e,t){let n=0;for(let r=0;r<3;r++){let i=N(e,t+r);if(n|=(i&127)<<7*r,!(i&128))return[n,t+r+1]}throw Error(`Malformed Solana transaction`)}function it(e,t,n){if(t+n*32>e.length)throw Error(`Malformed Solana transaction`);return Array.from({length:n},(n,r)=>ee.base58.encode(e.subarray(t+r*32,t+(r+1)*32)))}var at=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 w({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=we(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 w({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(T(n)){let{data:r}=await Ve({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(T(n)){let{data:r}=await Ve({context:this.walletRpcContext(t),account:n,rpcRequest:{chainType:`solana`,request:{method:`signTransaction`,params:{transaction:g.encoding.base64.fromBytes(e)}}}});return new Uint8Array(g.encoding.base64.toBytes(r))}let{messageBytes:r,signerIndex:i}=Qe({transaction:e,address:n.address}),{signature:a}=await this.signMessageRpc({method:`signMessage`,params:{message:g.encoding.base64.fromBytes(r)}},t);return $e({transaction:e,signerIndex:i,signature:g.encoding.base64.toBytes(a)})}async signTransactionObject(e,t){if(Xe(e)&&e.version===1)throw Error(`V1 transactions cannot be serialized by web3.js. Pass the serialized transaction as a Uint8Array instead.`);let n=Ze(e,this._account.address),r=Xe(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 w({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 w({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 w({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},ot=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(T(this._account))throw new w({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 w({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 w({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedBitcoinProvider { address: '${this._account.address}', request: [Function] }`}},st=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 ct(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new xe(`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 xe(`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 xe(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function lt(e){return e.error!==void 0}const ut=(function(e){return()=>`id-${e++}`})(0),dt=(e,t)=>typeof t==`bigint`?t.toString():t,ft=(e,t)=>`${e}${JSON.stringify(t,dt)}`,P=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)}},pt=new st;var mt=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 P(ct(n=>P(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,pt.flush(Error(`Embedded wallet WebView was reloaded`)),this.cache.clear(),this._embeddedWalletMessagePoster.reload()}onBackground(){this.ready=!1}ping(e=15e3){return P(this.invoke(`privy:iframe:ready`,{}),{msg:`Ping reached timeout`,ms:e})}create(e){return P(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 P(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`}):P(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 P(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 P(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 P(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=pt.dequeue(e.event,e.id);if(t)return lt(e)?t.reject(new xe(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=ft(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=ut();pt.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 ht(e,{request:t,headers:n}){return await e.fetchPrivyRoute(l.WalletCreate,{body:t,headers:n})}async function gt({context:e,chainType:t,idempotencyKey:n}){return{wallet:await ht(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}var _t=class{_privyInternal;_proxy;_chains=Array.from(d.DEFAULT_SUPPORTED_CHAINS);_mfa;_mfaPromises;_appApi;_dataSuffixPlugin;constructor(e,t,n,r,i,a,o){if(this._privyInternal=e,t&&(this._proxy=new mt(t,i),r.setProxy(this._proxy)),n){let e=(0,d.dedupeSupportedChains)(n);this._chains=e}this._mfa=r,this._mfaPromises=i,this._appApi=a,this._dataSuffixPlugin=o}setMessagePoster(e){this._proxy=new mt(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 w({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 gt({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 w({error:`Missing entropy details for wallet creation`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new w({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 T(e)||await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new ot({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 w({error:`User-controlled server wallets do not support custom recovery methods`,code:`embedded_wallet_creation_error`});await gt({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 w({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 w({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 w({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 w({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 gt({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 w({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 w({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 w({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new w({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 T(e)||await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new Ye({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 T(e)||(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new Ye({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 w({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return T(e)||(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new at({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(T(t))throw new w({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});qe({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 Ye({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(we(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}}},vt=class extends f.default{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const yt=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let F=!1;const bt=()=>{if(F)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;F=typeof t==`string`&&t.length>0||typeof n==`string`&&yt.includes(n)}catch{F=!0}return F},I={get(e){return v.default.get(e)},set(e,t,n){bt()||v.default.set(e,t,n)},remove(e){v.default.remove(e)}},xt=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!bt(),L=`privy:active-user`,St=`privy:saved-users`,R=e=>e?`privy:${e}:token`:`privy:token`,z=e=>e?`privy:${e}:pat`:`privy:pat`,B=e=>e?`privy:${e}:refresh_token`:`privy:refresh_token`,V=e=>e?`privy:${e}:id-token`:`privy:id-token`,Ct=e=>e?`privy-${e}-token`:`privy-token`,wt=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,Tt=e=>e?`privy-${e}-id-token`:`privy-id-token`,H=e=>e?`privy-${e}-session`:`privy-session`,U=Promise.allSettled.bind(Promise)??(e=>Promise.all(e.map(e=>e.then(e=>({status:`fulfilled`,value:e})).catch(e=>({status:`rejected`,reason:e}))))),Et=[`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 Dt=class extends f.default{static events=Et;_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 xt({useServerCookies:this._isUsingServerCookies,cookieWriteBehavior:this._cookieWriteBehavior})}writeCookie(e,t,n){this.shouldWriteCookies()&&I.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(R(e));try{return typeof t==`string`?new S(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(z(e));try{return typeof t==`string`?new S(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(B(e));return typeof t==`string`?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(V(e));return typeof t==`string`?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=I.get(H(e));if(t!==void 0&&t.length>0)return!0;let n=I.get(H(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=S.parse(e);return t!==null&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),n=[this._storage.del(R(null)),this._storage.del(z(null)),this._storage.del(B(null)),this._storage.del(V(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(L)];t&&n.push(this._storage.del(R(t)),this._storage.del(z(t)),this._storage.del(B(t)),this._storage.del(V(t)),this.removeSavedUserId(t)),await U(n),I.remove(Ct(null)),I.remove(wt(null)),I.remove(Tt(null)),I.remove(H(null)),t&&(I.remove(Ct(t)),I.remove(wt(t)),I.remove(Tt(t)),I.remove(H(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=R(e),r=Ct(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=S.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),I.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=z(e);typeof t==`string`?await this._storage.put(n,t):await this._storage.del(n)}async storeRefreshTokenForUser(e,t){let n=B(e),r=wt(e),i=H(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),I.remove(r),I.remove(i),this.emit(`refresh_token_cleared`,{reason:`set_with_non_string_value`}))}async updateWithTokensResponse(e){let t=e.user.id,n=(await U([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 U([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 U([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(R(null)),this._storage.get(z(null)),this._storage.get(B(null)),this._storage.get(V(null))]);if(typeof e!=`string`||typeof n!=`string`)return;let i=S.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 U(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=V(e),r=Tt(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=S.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),I.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=g.encoding.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(L);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(L,e)}async getSavedUserIds(){let e=await this._storage.get(St);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(St,JSON.stringify(t)):await this._storage.del(St),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 w({code:`invalid_input`,error:`Cannot switch active user because the user ID is not saved on this device`});await this._storage.put(L,e)}};const Ot=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},kt=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function At(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 W=()=>void 0,G={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},jt=({level:e,logger:t})=>({get level(){return e},error:G[e]>=G.ERROR?t.error:W,warn:G[e]>=G.WARN?t.warn:W,info:G[e]>=G.INFO?t.info:W,debug:G[e]>=G.DEBUG?t.debug:W}),Mt=`privy:caid`;var Nt=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.79.0`;_fetch;nativeAppIdentifier;_crypto;isMultiUserModeEnabled;_cache=new Map;constructor(e){this.logger=jt({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 Dt({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=(0,ne.retryFetch)(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 w({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}${(0,l.getPathWithParams)(e.path,t)}${At(n)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new w({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=Ot([a,c.signal]));let l=await this._fetch(s,c),u=await l.json();if(l.status>299)throw new C({...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 C({...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:kt(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:kt(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(l.AppConfig,{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(Mt);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(Mt,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(Mt)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,t){try{await this.fetch(l.AnalyticsEvent,{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 w({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 C({code:te.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});try{this.logger.debug(`[privy:refresh] fetching: ${l.RefreshSession.path}`);let n=await this.fetch(l.RefreshSession,{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 C&&e.code===te.PrivyErrorCode.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}}},Pt=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(l.AcceptTermsOnUser,{})}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(l.RefreshUser,{});return await this._privyInternal.session.storeIdentityToken(t),this._privyInternal.callbacks?.setUser?.(e),{user:e}}async switchActiveUser(e){if(!this._isMultiUserModeEnabled)throw new w({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 w({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 Ft=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`,It=e=>e?e.linked_accounts.filter(Ft).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],K=e=>It(e).find(e=>e.wallet_index===0)??null,Lt=K,Rt=e=>e?e.linked_accounts.filter(Ft).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],zt=e=>Rt(e).find(e=>e.wallet_index===0)??null,Bt=(e,t)=>t===`off`||It(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,Vt=(e,t)=>t===`off`||Rt(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,Ht=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),q=async(e,t,n)=>{let r=Bt(t.user,n?.ethereum?.createOnLogin??`off`),i=Vt(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 Ht(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:zt(t.user)??void 0});return Ht(n,t)}if(i){let n=await e.createSolana({ethereumAccount:K(t.user)??void 0});return Ht(n,t)}return t};var Ut=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async syncWithToken(e,t,n){let r=await this._privyInternal.fetchForLogin(l.CustomJWTAuthenticate,{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(l.CustomJWTLink,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Wt=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(l.PasswordlessInit,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(l.PasswordlessAuthenticate,{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(l.PasswordlessLink,{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(l.PasswordlessUpdate,{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(l.PasswordlessUnlink,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Gt=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth({relyingParty:e,redirectUrl:t,token:n}){return await this._privyInternal.fetch(l.FarcasterInit,{body:{relying_party:e,redirect_url:t,token:n}})}async getFarcasterStatus({channel_token:e}){return await this._privyInternal.fetch(l.FarcasterStatus,{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(l.FarcasterAuthenticate,{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(l.FarcasterLink,{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(l.FarcasterUnlink,{body:{fid:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Kt=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(l.FarcasterV2Init,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(l.FarcasterV2Authenticate,{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}},qt=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(l.GuestAuthenticate,{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 Jt(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function Yt(e){return crypto.getRandomValues(new Uint8Array(e))}function Xt(){return g.encoding.base64urlnopad.fromBytes(Yt(36))}function Zt(){return Xt()}async function Qt({codeVerifier:e,method:t=`S256`,digest:n}){if(t==`S256`){let t=await Jt(e,n);return g.encoding.base64urlnopad.fromBytes(t)}else return e}var $t=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=Xt(),r=Zt(),i=await Qt({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put(Y,n),this._storage.put(J,r)]),this._privyInternal.fetchForLogin(l.OAuthInit,{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 w({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let c=await this._privyInternal.fetchForLogin(l.OAuthAuthenticate,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let u=await q(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del(Y),this._storage.del(J)]),this._privyInternal.callbacks?.setUser?.(u.user),u}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 w({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let o=await this._privyInternal.fetch(l.OAuthLink,{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(l.OAuthUnlink,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},en=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(l.PasskeyLinkInit,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(l.PasskeyAuthenticateInit,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(l.PasskeyRegisterInit,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(l.PasskeyAuthenticate,{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(l.PasskeyRegister,{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(l.PasskeyLink,{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}}}},tn=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(l.PasswordlessSmsInit,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(l.PasswordlessSmsAuthenticate,{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(l.PasswordlessSmsLink,{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(l.PasswordlessSmsUpdate,{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(l.PasswordlessSmsUnlink,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},nn=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(l.SiweUnlink,{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(l.SiweLink,{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(l.SiweAuthenticate,{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(l.SiweInit,{body:{address:e.address}}),i=rn({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 rn(e){return`${e.domain} wants you to sign in with your Ethereum account:
|
|
1
|
+
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require("@privy-io/encoding"),u=require("@privy-io/routes"),d=require("jose");d=c(d);let f=require("@privy-io/chains"),p=require("@scure/base"),m=require("eventemitter3");m=c(m);let h=require("viem"),g=require("@privy-io/ethereum"),_=require("canonicalize");_=c(_);let v=require("@privy-io/api-base"),ee=require("@privy-io/std/retry-fetch"),y=require("js-cookie");y=c(y);let te=require("fetch-retry");te=c(te);let ne=require("libphonenumber-js/examples.mobile.json");ne=c(ne);let b=require("libphonenumber-js/min");function re(e){return{digest:e?.digest??((e,t)=>globalThis.crypto.subtle.digest(e,t)),randomUUID:e?.randomUUID??(()=>globalThis.crypto.randomUUID())}}const ie=e=>/^0x[0-9a-fA-F]*$/.test(e),ae=e=>`0x${l.encoding.hex.fromBytes(e)}`,oe=e=>ie(e)?e:ae(l.encoding.utf8.toBytes(e)),se=Symbol(`data-suffix-plugin`);function ce(e=[]){return e.find(e=>e.id===se)}function le(e){let t=e.startsWith(`0x`)?e:`0x${e}`;if(!ie(t))throw Error(`[Privy] dataSuffix: Invalid suffix "${e}" is not valid hex`);let n=t.slice(2);return{id:se,suffix:t,appendDataSuffix:({data:e})=>!e||e===`0x`?t:`${e}${n}`}}var ue=class{_privyInternal;_smartWalletConfig;constructor(e){this._privyInternal=e}getConfig(){return this._privyInternal.config}async getSmartWalletConfig(){return this._smartWalletConfig||=await this._privyInternal.fetch(u.GetSmartWalletConfig,{params:{app_id:this.appId}}),this._smartWalletConfig}get appId(){return this._privyInternal.appId}},x=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}},S=class extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}},de=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 fe(e){return e instanceof x||e instanceof S?e.code:`unknown_error`}const pe=e=>t=>e[fe(t)]??e.default;function me(e){return e&&typeof e==`object`&&`code`in e&&e.code===`mfa_canceled`}var C=class e{static parse(t){try{return new e(t)}catch{return null}}value;_decoded;constructor(e){this.value=e,this._decoded=d.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}},he=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=C.parse(r);if(!i||i.issuer!==`privy:${t}`)throw new S({code:`cross_app_invalid_app`,error:`Cross-app token issuer does not match the provider app.`});let a=e.providerAccessTokenStorageKey(t);await this._storage.put(a,r)}async getProviderAccessToken(t){let n=e.providerAccessTokenStorageKey(t),r=await this._storage.get(n);if(typeof r!=`string`)return null;try{let e=new C(r);return e.isExpired()||e.issuer!==`privy:${t}`?(await this._storage.del(n),null):r}catch{return await this._storage.del(n),null}}async getCrossAppConnections(){return await this._privyInternal.fetch(u.GetCrossAppConnections,{params:{app_id:this._privyInternal.appId}})}},ge=class{_privyInternal;constructor(e){this._privyInternal=e}async revoke(){await this._privyInternal.fetch(u.WalletsRevoke,{})}};const w=e=>!!e.id&&e.recovery_method===`privy-v2`;var _e=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(w(this._account))throw new S({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 S({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 S({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedBitcoinProvider { address: '${this._account.address}', request: [Function] }`}},ve=class{callbacks={};enqueue(e,t){this.callbacks[e]=t}flush(e){let t=Object.values(this.callbacks);this.callbacks={};for(let{reject:n}of t)n(e)}dequeue(e,t){let n=this.callbacks[t];if(!n)return console.warn(`[Privy] No callback found for "${e}" (id: ${t})`),null;switch(delete this.callbacks[t],e){case`privy:iframe:ready`:return n;case`privy:wallets:create`:return n;case`privy:user-signer:sign`:return n;case`privy:wallets:add`:return n;case`privy:wallets:set-recovery`:return n;case`privy:wallets:connect`:return n;case`privy:wallets:recover`:return n;case`privy:wallets:rpc`:return n;case`privy:wallets:import`:return n;case`privy:wallet:create`:return n;case`privy:wallet:connect`:return n;case`privy:wallet:recover`:return n;case`privy:wallet:rpc`:return n;case`privy:solana-wallet:create`:return n;case`privy:solana-wallet:create-additional`:return n;case`privy:solana-wallet:connect`:return n;case`privy:solana-wallet:recover`:return n;case`privy:solana-wallet:rpc`:return n;case`privy:delegated-actions:consent`:return n;case`privy:mfa:verify`:return n;case`privy:mfa:init-enrollment`:return n;case`privy:mfa:submit-enrollment`:return n;case`privy:mfa:unenroll`:return n;case`privy:mfa:clear`:return n;case`privy:auth:unlink-passkey`:return n;default:throw Error(`invalid wallet event type ${e}`)}}};const ye=[`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 be=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 xe=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}]`:``}`}},Se=class extends xe{type=`provider_error`;code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}},T=class extends Error{type;constructor(e,t){super(t),this.type=e}},Ce=class extends xe{type=`connector_error`;constructor(e,t,n){super(e,t,n)}},we=class extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n}};const E={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 D(e){let t=e.type;return typeof t==`string`&&ye.includes(t)}function Te(e){return D(e)&&e.type===`wallet_not_on_device`}function Ee(e){return D(e)&&e.type===`mfa_timeout`}function De(e){return D(e)&&e.type===`missing_or_invalid_mfa`}function Oe(e){return D(e)&&e.type===`mfa_verification_max_attempts_reached`}function ke(e){return D(e)&&e.message.includes(`code 429`)}var Ae=class extends Se{details;constructor(e){let t=e;super(t.message,t.code,t.data);let n=Object.values(E).find(e=>e.eipCode===t.code);this.details=n||E.UNKNOWN_ERROR,t.code===-32002&&(t.message?.includes(`already pending for origin`)?t.message?.includes(`wallet_requestPermissions`)?this.details=E.E32002_CONNECTION_ALREADY_PENDING:this.details=E.E32002_REQUEST_ALREADY_PENDING:t.message?.includes(`Already processing`)&&t.message.includes(`eth_requestAccounts`)&&(this.details=E.E32002_WALLET_LOCKED))}};async function je(e,t,n,r,i=!1,a,o){let s=i,c=async a=>s?(a===+!i?r():n.current?.reject(new T(`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 T(`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 T(`mfa_verification_max_attempts_reached`,`Max MFA verification attempts reached`);throw n.current?.reject(e),e}return l}function Me(e){return e.error!==void 0}const Ne=(function(e){return()=>`id-${e++}`})(0),Pe=(e,t)=>typeof t==`bigint`?t.toString():t,Fe=(e,t)=>`${e}${JSON.stringify(t,Pe)}`,O=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)}},Ie=new ve;var Le=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 O(je(n=>O(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,Ie.flush(Error(`Embedded wallet WebView was reloaded`)),this.cache.clear(),this._embeddedWalletMessagePoster.reload()}retarget(e){e!==this._embeddedWalletMessagePoster&&(this._embeddedWalletMessagePoster=e,this.ready=!1)}onBackground(){this.ready=!1}ping(e=15e3){return O(this.invoke(`privy:iframe:ready`,{}),{msg:`Ping reached timeout`,ms:e})}create(e){return O(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 O(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`}):O(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 O(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 O(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 O(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=Ie.dequeue(e.event,e.id);if(t)return Me(e)?t.reject(new T(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=Fe(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=Ne();Ie.enqueue(i,{resolve:n,reject:r}),this._embeddedWalletMessagePoster.postMessage(JSON.stringify({id:i,event:e,data:t}),`*`)}).finally(()=>{this.cache.delete(n)});return this.cache.set(n,r),r}};function Re({transaction:e,address:t}){let{messageBytes:n,signerAddresses:r}=Be(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 ze({transaction:e,signerIndex:t,signature:n}){if(n.length!==64)throw Error(`Solana signatures must be 64 bytes`);let{signaturesOffset:r,signerAddresses:i}=Be(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 Be(e){if(e.length===0)throw Error(`Cannot decode an empty Solana transaction`);return e[0]===129?Ve(e):He(e)}function Ve(e){let t=k(e,1),n=e.length-t*64;if(n<=41)throw Error(`Malformed V1 Solana transaction`);let r=e.subarray(0,n);if(k(r,41)<t)throw Error(`Malformed V1 Solana transaction`);return{messageBytes:r,signaturesOffset:n,signerAddresses:We(r,42,t)}}function He(e){let[t,n]=Ue(e,0),r=n+t*64,i=k(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=k(e,a);if(o!==t)throw Error(`Solana transaction signature count does not match its message header`);let[s,c]=Ue(e,a+3);if(s<o)throw Error(`Malformed Solana transaction`);return{messageBytes:e.subarray(r),signaturesOffset:n,signerAddresses:We(e,c,o)}}function k(e,t){let n=e[t];if(n===void 0)throw Error(`Malformed Solana transaction`);return n}function Ue(e,t){let n=0;for(let r=0;r<3;r++){let i=k(e,t+r);if(n|=(i&127)<<7*r,!(i&128))return[n,t+r+1]}throw Error(`Malformed Solana transaction`)}function We(e,t,n){if(t+n*32>e.length)throw Error(`Malformed Solana transaction`);return Array.from({length:n},(n,r)=>p.base58.encode(e.subarray(t+r*32,t+(r+1)*32)))}function Ge(e){return`version`in e}function Ke(e,t){let n=(Ge(e)?e.message:e.compileMessage()).staticAccountKeys.find(e=>e.toBase58()===t);if(!n)throw Error(`Transaction does not contain public key ${t}`);return n}var qe=class{_privyInternal;_account;constructor({privyInternal:e,account:t}){this._privyInternal=e,this._account=t}async request(e){if(!await this._privyInternal.getAccessTokenInternal())throw new S({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});switch(e.method){case`signAndSendTransaction`:return await this.handleSignAndSendTransaction(e);case`signTransaction`:return await this.handleSignTransaction(e);default:return await this.handleIFrameRpc(e)}}get _publicKey(){return this._account.address}async signTransactionObject(e,t){if(Ge(e)&&e.version===1)throw Error(`V1 transactions cannot be serialized by web3.js. Pass the serialized transaction as a Uint8Array instead.`);let n=Ke(e,this._account.address),r=Ge(e)?e.message.serialize():e.serializeMessage(),{signature:i}=await this.signMessageRpc({method:`signMessage`,params:{message:l.encoding.base64.fromBytes(r)}},t);e.addSignature(n,l.encoding.base64.toBytes(i))}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.prepare(t),await this.signMessageRpc(e,t)}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new S({code:`embedded_wallet_request_error`,error:n})}}async handleSignAndSendTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.prepare(t);let{transaction:n,connection:r,options:i}=e.params,a;return n instanceof Uint8Array?a=await this.signSerializedTransaction(n,t):(await this.signTransactionObject(n,t),a=n.serialize()),{signature:await r.sendRawTransaction(a,i)}}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new S({code:`embedded_wallet_request_error`,error:n})}}async handleSignTransaction(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);await this.prepare(t);let{transaction:n}=e.params;return n instanceof Uint8Array?{signedTransaction:await this.signSerializedTransaction(n,t)}:(await this.signTransactionObject(n,t),{signedTransaction:n})}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new S({code:`embedded_wallet_request_error`,error:n})}}toJSON(){return`PrivyEmbeddedSolanaProvider { address: '${this._account.address}', request: [Function] }`}},Je=class extends qe{_proxy;_entropyId;_entropyIdVerifier;_onNeedsRecovery;constructor({proxy:e,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:r,...i}){super(i),this._proxy=e,this._entropyId=t,this._entropyIdVerifier=n,this._onNeedsRecovery=r}async prepare(e){try{await this._proxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:e})}catch(t){let n=Te(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 S({code:`embedded_wallet_recovery_error`,error:`User-owned recovery timed out`})),12e4),await this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>t(!0)})}).finally(()=>clearTimeout(e))}else throw t}}async signMessageRpc(e,t){return(await this._proxy.rpcWallet({accessToken:t,request:e,chainType:`solana`,hdWalletIndex:this._account.wallet_index,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier})).response.data}async signSerializedTransaction(e,t){let{messageBytes:n,signerIndex:r}=Re({transaction:e,address:this._account.address}),{signature:i}=await this.signMessageRpc({method:`signMessage`,params:{message:l.encoding.base64.fromBytes(n)}},t);return ze({transaction:e,signerIndex:r,signature:l.encoding.base64.toBytes(i)})}};let A;async function Ye(){if(!A){let{tempo:e,tempoModerato:t}=await Promise.resolve().then(()=>require("./tempoChains-C7o70PSk.js"));A={tempo:e,tempoModerato:t}}return A}function Xe(){return A!==void 0}const Ze=(e,t,n,r)=>{let i=Number(e),a=t.find(e=>e.id===i);if(!a)throw new Ce(`Unsupported chainId ${e}`,4901);let o=$e(a,n,r.appId);if(Qe(i)){if(!A)throw new Ce(`Tempo chains are not loaded for chainId ${e}; await loadTempoChains() first`,4901);let t=i===f.tempo.id?A.tempo:A.tempoModerato;return(0,h.createPublicClient)({transport:(0,h.http)(o),chain:t})}return(0,h.createPublicClient)({transport:(0,h.http)(o),chain:a})};function Qe(e){return e===f.tempo.id||e===f.tempoTestnet.id}const $e=(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 Ce(`No RPC url found for ${r}`);return a};function et({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 tt=new Set([`eth_sign`,`personal_sign`,`eth_signTypedData_v4`,`csw_signUserOperation`,`secp256k1_sign`]);var nt=class extends m.default{_privyInternal;_account;_chainId;_chains;_client;_clientReady;_appApi;_dataSuffixPlugin;constructor({privyInternal:e,account:t,chains:n,chainId:r=n[0].id,appApi:i,dataSuffixPlugin:a}){super(),this._privyInternal=e,this._account=t,this._chainId=r,this._chains=n,this.updateClient(i.appId),this._appApi=i,this._dataSuffixPlugin=a}async request(e){if(await this.awaitClientReady(),tt.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||(0,g.isTempoTransactionRequest)(e))return e;let t=typeof e.data==`string`?e.data:`0x`;return{...e,data:this._dataSuffixPlugin.appendDataSuffix({data:t})}}async ensureChainId(e){let t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),await this.awaitClientReady(),t}async awaitClientReady(){for(;this._clientReady;){let e=this._clientReady;await e,this._clientReady===e&&(this._clientReady=void 0)}}internalSwitchEthereumChain(e){!e||Number(e)===this._chainId||(this._chainId=Number(e),this.updateClient(this._privyInternal.appId),this.emit(`chainChanged`,e))}updateClient(e){let t=this._chainId,n=()=>Ze(t,this._chains,{rpcUrls:[]},{appId:e});if(!Qe(t)||Xe()){this._client=n(),this._clientReady=void 0;return}let r=Ye().then(()=>{this._chainId===t&&(this._client=n())});this._clientReady=r,r.catch(()=>{})}async handlePopulateTransaction(e){let t=await this.ensureChainId(e);if((0,g.isTempoTransactionRequest)(t)){let e=(0,g.toViemTempoTransactionSerializable)(t),n=(0,g.normalizeViemPreparedTempoTransaction)(await this.requireTempoClient().prepareTransactionRequest({account:t.from??this._account.address,...e}),t.gasLimit);return{...t,...n,type:g.TEMPO_TXN_TYPE_NUMBER}}let n=(0,g.toViemTransactionSerializable)(t),{gas:r,...i}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...n});return{...i,gasLimit:r,type:g.STRING_TO_NUMBER_TXN_TYPE[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]=(0,h.toHex)(n))}return(0,g.isTempoTransactionRequest)(t)&&(t.calls=t.calls.map(e=>({...e,value:typeof e.value==`bigint`?(0,h.toHex)(e.value):e.value}))),await this.handleIFrameRpc({method:`eth_signTransaction`,params:[t]})}async handleSendTransaction(e){let t=await this.handlePopulateTransaction(e),n=await this.handleSignTransaction(t);return await this.handleJsonRpc({method:`eth_sendRawTransaction`,params:[n]})}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error(`Invalid params for eth_estimateGas`);let t=e.params?.[0],n=await this.ensureChainId(t);if((0,g.isTempoTransactionRequest)(n)){let e=(0,g.toViemTempoTransactionSerializable)(n);return await this.requireTempoClient().estimateGas({account:n.from??this._account.address,...e})}let r=(0,g.toViemTransactionSerializable)(n);return await this._client.estimateGas({account:n.from??this._account.address,...r})}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new we(`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 we(`Invalid params for ${e.method}`,4200);this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw Error(`Missing privy token. User must be logged in`);return await this.signWithWallet(e,t)}catch(t){console.error(t);let n=t instanceof Error?t.message:`Unable to make wallet request`;throw this._privyInternal.createAnalyticsEvent(`embedded_wallet_sdk_rpc_failed`,{method:e.method,address:this._account.address,error:n}),new S({code:`embedded_wallet_request_error`,error:n})}}async handleJsonRpc(e){return this._client.request(e)}requireTempoClient(){if(!Qe(this._chainId))throw new we(`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] }`}},rt=class extends nt{_walletProxy;_entropyId;_entropyIdVerifier;_onNeedsRecovery;constructor({walletProxy:e,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:r,...i}){super(i),this._walletProxy=e,this._entropyId=t,this._entropyIdVerifier=n,this._onNeedsRecovery=r}async signWithWallet(e,t){try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t})}catch(e){let n=Te(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 S({code:`embedded_wallet_recovery_error`,error:`User-owned recovery timed out`})),12e4),await this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>t(!0)})}).finally(()=>clearTimeout(e))}else throw e}return(await this._walletProxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:`ethereum`})).response.data}};async function j(e,t){let n;if(t instanceof Uint8Array)n=l.encoding.base64.fromBytes(t);else{let e=(0,_.default)(t);if(e===void 0)throw new S({error:`Failed to prepare the payload for signing`,code:`invalid_input`});n=l.encoding.base64.fromBytes(l.encoding.utf8.toBytes(e))}let{signature:r}=await e({message:n});return{signature:r}}const M=`privy-request-expiry`,N=1800*1e3;async function P(e,t,{wallet_id:n,headers:r,...i}){let a=e.getCompiledPath(u.WalletRpc,{params:{wallet_id:n}}),o=String(Date.now()+N),{signature:s}=await j(t,{version:1,url:a,method:u.WalletRpc.method,headers:{"privy-app-id":e.app.appId,[M]:o},body:{...i}});if(Date.now()>Number(o))throw new S({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(u.WalletRpc,{body:i,params:{wallet_id:n},headers:{"privy-authorization-signature":s,[M]:o,...r??{}}})}function it(e){return(0,g.isTempoTransactionRequest)(e)?ot(e):at(e)}function at(e){return{from:e.from,to:e.to??void 0,nonce:F(e.nonce),chain_id:F(e.chainId),data:ut(e.data),value:F(e.value),type:ft(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),authorization_list:e.authorizationList?.map(e=>{let t=e.yParity??(e.v===void 0?0:Number(e.v)-27);if(t!==0&&t!==1)throw Error(`EIP-7702 authorizations require a valid yParity value`);return{contract:e.address,chain_id:mt(e.chainId,`chainId`),nonce:mt(e.nonce,`nonce`),r:e.r,s:e.s,y_parity:t}})}}function ot(e){return{type:g.TEMPO_TXN_TYPE_NUMBER,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:ct(e.feePayerSignature),access_list:st(e.accessList),calls:e.calls.map(e=>({to:e.to,data:e.data,value:F(e.value)}))}}function st(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 ct(e){if(!e)return;let t=lt(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 lt(e){if(e.yParity!==void 0)return e.yParity;if(e.v!==void 0)return Number(e.v)-27}function ut(e){if(e!==void 0)return typeof e==`string`?oe(e):ae(Uint8Array.from(e))}const dt=[0,2,4];function ft(e){if(e==null)return;let t=Number(e);if(!pt(t))throw Error(`Invalid transaction type: expected ${dt.join(`, `)} as a number or hex string, got "${e}".`);return t}function pt(e){return dt.includes(e)}function F(e){if(typeof e==`number`||typeof e==`bigint`)return`0x${BigInt(e).toString(16)}`;if(typeof e==`string`){if(ie(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 mt(e,t){let n=F(e);if(n===void 0)throw Error(`EIP-7702 authorization ${t} is required`);return n}function ht(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 gt({context:e,account:t,rpcRequest:n}){switch(n.chainType){case`ethereum`:return _t({context:e,account:t,rpcRequest:n.request});case`solana`:return vt({context:e,account:t,rpcRequest:n.request})}}async function _t({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:it(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:ht(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:oe(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:oe(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 vt({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}}}}var yt=class extends qe{_app;_signRequest;constructor({app:e,signRequest:t,...n}){super(n),this._app=e,this._signRequest=t}async prepare(){}async signMessageRpc(e){let{data:t}=await gt({context:this.walletRpcContext(),account:this._account,rpcRequest:{chainType:`solana`,request:e}});return{signature:t}}async signSerializedTransaction(e){let{data:t}=await gt({context:this.walletRpcContext(),account:this._account,rpcRequest:{chainType:`solana`,request:{method:`signTransaction`,params:{transaction:l.encoding.base64.fromBytes(e)}}}});return new Uint8Array(l.encoding.base64.toBytes(t))}walletRpcContext(){return{app:this._app,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:this._signRequest}}},bt=class extends nt{_signRequest;constructor({signRequest:e,...t}){super(t),this._signRequest=e}async signWithWallet(e){let{data:t}=await gt({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:this._signRequest},account:this._account,rpcRequest:{chainType:`ethereum`,request:e}});return t}};async function xt(e,{request:t,headers:n}){return await e.fetchPrivyRoute(u.WalletCreate,{body:t,headers:n})}async function St({context:e,chainType:t,idempotencyKey:n}){return{wallet:await xt(e,{request:{chain_type:t,owner_id:void 0},headers:n?{"privy-idempotency-key":n}:void 0})}}var Ct=class{_privyInternal;_proxy;_chains=Array.from(f.DEFAULT_SUPPORTED_CHAINS);_mfa;_mfaPromises;_appApi;_dataSuffixPlugin;_signRequest=e=>this.signWithUserSigner(e);constructor(e,t,n,r,i,a,o){if(this._privyInternal=e,t&&(this._proxy=new Le(t,i),r.setProxy(this._proxy)),n){let e=(0,f.dedupeSupportedChains)(n);this._chains=e}this._mfa=r,this._mfaPromises=i,this._appApi=a,this._dataSuffixPlugin=o}setMessagePoster(e){if(this._proxy){this._proxy.retarget(e);return}this._proxy=new Le(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 S({error:`User must be logged in to sign a message with the user signer`,code:`user_signer_sign_error`});let{signature:n}=await this._proxy.signWithUserSigner({accessToken:t,message:e.message});return{signature:n}}async add(e){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await St({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:e.chainType});else{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(!e.entropyId)throw new S({error:`Missing entropy details for wallet creation`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new S({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 w(e)||await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new _e({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n})}async create({password:e,recoveryMethod:t,recoveryToken:n,recoveryKey:r,recoverySecretOverride:i,iCloudRecordNameOverride:a,solanaAccount:o,skipCallbacks:s,idempotencyKey:c}){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`){if(t&&!t.startsWith(`privy`))throw new S({error:`User-controlled server wallets do not support custom recovery methods`,code:`embedded_wallet_creation_error`});await St({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`ethereum`,idempotencyKey:c})}else{if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let s;if(s=t||(e?`user-passcode`:`privy`),e&&typeof e!=`string`)throw Error(`Invalid recovery password, must be a string`);if(s===`privy`&&this._privyInternal.config?.embedded_wallet_config.require_user_password_on_create)throw Error(`Password not provided yet is required by App configuration`);let c=await this._privyInternal.getAccessTokenInternal();if(!c)throw Error(`User must be logged in to create an embedded wallet`);let{address:l}=await this._proxy.create({accessToken:c,recoveryMethod:s,recoveryKey:r,recoveryPassword:e,recoveryAccessToken:n,recoverySecretOverride:i,iCloudRecordNameOverride:a,solanaAddress:o?.address});if(!l)throw Error(`Failed to create wallet`)}return await this._privyInternal.refreshSession(s)}async importWallet({privateKey:e,chainType:t,additionalSigners:n}){if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);let r=this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`?`tee`:`on-device`;if(n&&r===`on-device`)throw new S({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 S({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 S({error:`Failed to import wallet`,code:`embedded_wallet_creation_error`});let{session_update_action:o,...s}=await this._privyInternal.refreshSession();return{address:a,user:s}}async createSolana(e){if(this._privyInternal.config?.embedded_wallet_config.mode===`user-controlled-server-wallets-only`)await St({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e)},chainType:`solana`,idempotencyKey:e?.idempotencyKey});else{if(!this._proxy)throw new S({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let t=await this._privyInternal.getAccessTokenInternal();if(!t)throw new S({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 S({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 S({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_creation_error`});let n=await this._privyInternal.getAccessTokenInternal();if(!n)throw new S({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(w(e))return new bt({account:e,privyInternal:this._privyInternal,chains:this._chains,signRequest:this._signRequest,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin});if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return await this._load({wallet:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,recoveryPassword:t,recoveryKey:i,recoveryAccessToken:n,recoverySecretOverride:r}),new rt({account:e,entropyId:e.address,entropyIdVerifier:`ethereum-address-verifier`,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin})}async getEthereumProvider({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o,onNeedsRecovery:s}){if(!await this._privyInternal.getAccessTokenInternal())throw Error(`User must be logged in to create an embedded wallet`);if(w(e))return new bt({account:e,privyInternal:this._privyInternal,chains:this._chains,signRequest:this._signRequest,appApi:this._appApi,dataSuffixPlugin:this._dataSuffixPlugin});if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);return(!s||r||i||a||o)&&await this._load({entropyId:t,entropyIdVerifier:n,wallet:e,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a,recoveryKey:o}),new rt({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(w(e))return new yt({account:e,privyInternal:this._privyInternal,signRequest:this._signRequest,app:this._appApi});if(!this._proxy)throw new S({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return(!o||r||i||a)&&await this._load({wallet:e,entropyId:t,entropyIdVerifier:n,recoveryPassword:r,recoveryAccessToken:i,recoverySecretOverride:a}),new Je({account:e,privyInternal:this._privyInternal,proxy:this._proxy,entropyId:t,entropyIdVerifier:n,onNeedsRecovery:o})}async setRecovery(e){let{wallet:t,...n}=e;if(!this._proxy)throw Error(`Embedded wallet proxy not initialized`);if(w(t))throw new S({error:`This wallet does not support setting recovery methods`,code:`unsupported_recovery_method`});et({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 rt({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(Te(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}}},wt=class extends m.default{rootPromise;submitPromise;constructor(){super(),this.rootPromise={current:null},this.submitPromise={current:null}}};const Tt=[`chrome-extension:`,`moz-extension:`,`safari-web-extension:`];let I=!1;const Et=()=>{if(I)return!0;try{let e=globalThis,t=e.chrome?.runtime?.id??e.browser?.runtime?.id,n=e.location?.protocol;I=typeof t==`string`&&t.length>0||typeof n==`string`&&Tt.includes(n)}catch{I=!0}return I},L={get(e){return y.default.get(e)},set(e,t,n){Et()||y.default.set(e,t,n)},remove(e){y.default.remove(e)}},Dt=({useServerCookies:e,cookieWriteBehavior:t})=>e||t===`never`?!1:!Et(),R=`privy:active-user`,Ot=`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`,kt=e=>e?`privy-${e}-token`:`privy-token`,At=e=>e?`privy-${e}-refresh-token`:`privy-refresh-token`,jt=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}))))),Mt=[`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 Nt=class extends m.default{static events=Mt;_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 Dt({useServerCookies:this._isUsingServerCookies,cookieWriteBehavior:this._cookieWriteBehavior})}writeCookie(e,t,n){this.shouldWriteCookies()&&L.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 C(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 C(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=L.get(U(e));if(t!==void 0&&t.length>0)return!0;let n=L.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=C.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(R)];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),L.remove(kt(null)),L.remove(At(null)),L.remove(jt(null)),L.remove(U(null)),t&&(L.remove(kt(t)),L.remove(At(t)),L.remove(jt(t)),L.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=kt(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=C.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),L.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=At(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),L.remove(r),L.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=C.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=jt(e);if(typeof t==`string`){let e=await this._storage.get(n);await this._storage.put(n,t);let i=C.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),L.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=l.encoding.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(R);return typeof e==`string`?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(R,e)}async getSavedUserIds(){let e=await this._storage.get(Ot);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(Ot,JSON.stringify(t)):await this._storage.del(Ot),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 S({code:`invalid_input`,error:`Cannot switch active user because the user ID is not saved on this device`});await this._storage.put(R,e)}};const Pt=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},Ft=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};function It(e){let t=new URLSearchParams;for(let n in e)e[n]!=null&&t.append(n,String(e[n]));return Array.from(t).length?`?`+t.toString():``}const G=()=>void 0,K={NONE:-1/0,ERROR:1,WARN:2,INFO:3,DEBUG:1/0},Lt=({level:e,logger:t})=>({get level(){return e},error:K[e]>=K.ERROR?t.error:G,warn:K[e]>=K.WARN?t.warn:G,info:K[e]>=K.INFO?t.info:G,debug:K[e]>=K.DEBUG?t.debug:G}),Rt=`privy:caid`;var zt=class{baseUrl;callbacks;appId;appClientId;logger;session;_config;_analyticsId;_storage;_sdkVersion=`js-sdk-core:0.79.2`;_fetch;nativeAppIdentifier;_crypto;isMultiUserModeEnabled;_cache=new Map;constructor(e){this.logger=Lt({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 Nt({storage:this._storage,isUsingServerCookies:!1,cookieWriteBehavior:e.cookieWriteBehavior,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=(0,ee.retryFetch)(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 S({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}${(0,u.getPathWithParams)(e.path,t)}${It(n)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new S({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=Pt([a,c.signal]));let l=await this._fetch(s,c),u=await l.json();if(l.status>299)throw new x({...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 x({...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:Ft(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:Ft(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(u.AppConfig,{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(Rt);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(Rt,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(Rt)}catch(e){this.logger.error(`Unable to delete clientId`,e)}}async createAnalyticsEvent(e,t){try{await this.fetch(u.AnalyticsEvent,{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 S({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 x({code:v.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:`No tokens found in storage`,status:401});try{this.logger.debug(`[privy:refresh] fetching: ${u.RefreshSession.path}`);let n=await this.fetch(u.RefreshSession,{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 x&&e.code===v.PrivyErrorCode.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}}},Bt=class{_privyInternal;_embedded;_isMultiUserModeEnabled;constructor(e,t,n){this._privyInternal=e,this._embedded=t,this._isMultiUserModeEnabled=n}async get(){let{user:e}=await this._privyInternal.refreshSession();return{user:e}}async acceptTerms(){let e=await this._privyInternal.fetch(u.AcceptTermsOnUser,{});return this._privyInternal.callbacks?.setUser?.(e),{user:e}}async refreshUser(){let{user:e,identity_token:t}=await this._privyInternal.fetch(u.RefreshUser,{});return await this._privyInternal.session.storeIdentityToken(t),this._privyInternal.callbacks?.setUser?.(e),{user:e}}async switchActiveUser(e){if(!this._isMultiUserModeEnabled)throw new S({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 S({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 Vt=e=>e.type===`wallet`&&e.wallet_client_type===`privy`&&e.connector_type===`embedded`,Ht=e=>e?e.linked_accounts.filter(Vt).filter(e=>e.chain_type===`ethereum`).sort((e,t)=>e.wallet_index-t.wallet_index):[],q=e=>Ht(e).find(e=>e.wallet_index===0)??null,Ut=q,Wt=e=>e?e.linked_accounts.filter(Vt).filter(e=>e.chain_type===`solana`).sort((e,t)=>e.wallet_index-t.wallet_index):[],Gt=e=>Wt(e).find(e=>e.wallet_index===0)??null,Kt=(e,t)=>t===`off`||Ht(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`ethereum`).length>0?t===`all-users`:!0,qt=(e,t)=>t===`off`||Wt(e).length>0?!1:e.linked_accounts.filter(e=>e.type===`wallet`&&e.chain_type===`solana`).length>0?t===`all-users`:!0,Jt=(e,t)=>({...e,is_new_user:t.is_new_user,oauth_tokens:t.oauth_tokens}),J=async(e,t,n)=>{let r=Kt(t.user,n?.ethereum?.createOnLogin??`off`),i=qt(t.user,n?.solana?.createOnLogin??`off`);if(r&&i){let n=await e.create({recoveryMethod:`privy`,skipCallbacks:!0}),r=await e.createSolana({ethereumAccount:q(n.user)??void 0});return Jt(r,t)}if(r){let n=await e.create({recoveryMethod:`privy`,solanaAccount:Gt(t.user)??void 0});return Jt(n,t)}if(i){let n=await e.createSolana({ethereumAccount:q(t.user)??void 0});return Jt(n,t)}return t};var Yt=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async syncWithToken(e,t,n){let r=await this._privyInternal.fetchForLogin(u.CustomJWTAuthenticate,{body:{token:e,mode:n}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await J(this._embedded,r,t?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithToken(e){await this._privyInternal.fetch(u.CustomJWTLink,{body:{token:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Xt=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(u.PasswordlessInit,{body:{email:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(u.PasswordlessAuthenticate,{body:{email:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(u.PasswordlessLink,{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(u.PasswordlessUpdate,{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(u.PasswordlessUnlink,{body:{address:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Zt=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(u.FarcasterInit,{body:{relying_party:e,redirect_url:t,token:n}})}async getFarcasterStatus({channel_token:e}){return await this._privyInternal.fetch(u.FarcasterStatus,{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(u.FarcasterAuthenticate,{body:{channel_token:e,message:t,signature:n,fid:r,mode:i}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await J(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async link({channel_token:e,message:t,signature:n,fid:r}){await this._privyInternal.fetch(u.FarcasterLink,{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(u.FarcasterUnlink,{body:{fid:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},Qt=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async initializeAuth(){return await this._privyInternal.fetch(u.FarcasterV2Init,{body:{}})}async authenticate({message:e,signature:t,fid:n},r){let i=await this._privyInternal.fetchForLogin(u.FarcasterV2Authenticate,{body:{message:e,signature:t,fid:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}},$t=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(u.GuestAuthenticate,{body:{guest_credential:t}});await this._privyInternal.session.updateWithTokensResponse(n);let r=await J(this._embedded,n,e?.embedded);return this._privyInternal.callbacks?.setUser?.(r.user),r}};const Y=`privy:state_code`,X=`privy:code_verifier`;async function en(e,t){let n=await t(`SHA-256`,new TextEncoder().encode(e));return new Uint8Array(n)}function tn(e){return crypto.getRandomValues(new Uint8Array(e))}function nn(){return l.encoding.base64urlnopad.fromBytes(tn(36))}function rn(){return nn()}async function an({codeVerifier:e,method:t=`S256`,digest:n}){if(t==`S256`){let t=await en(e,n);return l.encoding.base64urlnopad.fromBytes(t)}else return e}var on=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=nn(),r=rn(),i=await an({codeVerifier:n,digest:this._crypto.digest});return await Promise.all([this._storage.put(X,n),this._storage.put(Y,r)]),this._privyInternal.fetchForLogin(u.OAuthInit,{body:{redirect_to:t,provider:e,code_challenge:i,state_code:r}})}async loginWithCode(e,t,n,r,i,a){let[o,s]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(s!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:s??``,returnedStateCode:t??``}),new S({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let c=await this._privyInternal.fetchForLogin(u.OAuthAuthenticate,{body:{authorization_code:e,code_type:r,state_code:s,code_verifier:o,mode:i}});await this._privyInternal.session.updateWithTokensResponse(c);let l=await J(this._embedded,c,a?.embedded);return await Promise.all([this._storage.del(X),this._storage.del(Y)]),this._privyInternal.callbacks?.setUser?.(l.user),l}async linkWithCode(e,t,n,r){let[i,a]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(a!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`oauth`,provider:n,storedStateCode:a??``,returnedStateCode:t??``}),new S({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let o=await this._privyInternal.fetch(u.OAuthLink,{body:{authorization_code:e,code_type:r,state_code:a,code_verifier:i}});await this._privyInternal.session.processOAuthTokens(o.oauth_tokens);let s=await this._privyInternal.refreshSession();return await Promise.all([this._storage.del(X),this._storage.del(Y)]),{user:s.user,identity_token:s.identity_token,oauth_tokens:o.oauth_tokens}}async unlink(e,t){await this._privyInternal.fetch(u.OAuthUnlink,{body:{provider:e,subject:t}});let n=await this._privyInternal.refreshSession();return{user:n.user,identity_token:n.identity_token}}},sn=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async generateRegistrationOptions(e){return await this._privyInternal.fetch(u.PasskeyLinkInit,{body:{relying_party:e}})}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(u.PasskeyAuthenticateInit,{body:{relying_party:e}})}async generateSignupOptions(e){return await this._privyInternal.fetch(u.PasskeyRegisterInit,{body:{relying_party:e}})}async loginWithPasskey(e,t,n,r){let i=await this._privyInternal.fetchForLogin(u.PasskeyAuthenticate,{body:{relying_party:n,challenge:t,authenticator_response:this._transformAuthenticationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async signupWithPasskey(e,t,n){let r=await this._privyInternal.fetchForLogin(u.PasskeyRegister,{body:{relying_party:t,authenticator_response:this._transformRegistrationResponseToSnakeCase(e)}});await this._privyInternal.session.updateWithTokensResponse(r);let i=await J(this._embedded,r,n?.embedded);return this._privyInternal.callbacks?.setUser?.(i.user),i}async linkWithPasskey(e,t){await this._privyInternal.fetch(u.PasskeyLink,{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}}}},cn=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async sendCode(e,t){return this._privyInternal.fetch(u.PasswordlessSmsInit,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t,n,r){let i=await this._privyInternal.fetchForLogin(u.PasswordlessSmsAuthenticate,{body:{phoneNumber:e,code:t,mode:n}});await this._privyInternal.session.updateWithTokensResponse(i);let a=await J(this._embedded,i,r?.embedded);return this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithCode(e,t){await this._privyInternal.fetch(u.PasswordlessSmsLink,{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(u.PasswordlessSmsUpdate,{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(u.PasswordlessSmsUnlink,{body:{phoneNumber:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},ln=class{_privyInternal;_embedded;_wallet=void 0;_preparedMessage;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlinkWallet(e){await this._privyInternal.fetch(u.SiweUnlink,{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(u.SiweLink,{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(u.SiweAuthenticate,{body:{signature:e,message:o,chainId:a.chainId,walletClientType:a.walletClientType??null,connectorType:a.connectorType??null,mode:r}});await this._privyInternal.session.updateWithTokensResponse(s);let c=await J(this._embedded,s,i?.embedded);return this._privyInternal.callbacks?.setUser?.(c.user),c}async init(e,t,n){this._wallet=e;let{nonce:r}=await this._privyInternal.fetch(u.SiweInit,{body:{address:e.address}}),i=un({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 un(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 dn=class{_privyInternal;_embedded;constructor(e,t){this._privyInternal=e,this._embedded=t}async unlink({address:e}){await this._privyInternal.fetch(u.SiwsUnlink,{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(u.SiwsLink,{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(u.SiwsAuthenticate,{body:{signature:n,message:t,walletClientType:r??null,connectorType:i??null,mode:e}});await this._privyInternal.session.updateWithTokensResponse(o);let s=await J(this._embedded,o,a?.embedded);return this._privyInternal.callbacks?.setUser?.(s.user),s}async fetchNonce({address:e}){let{nonce:t}=await this._privyInternal.fetch(u.SiwsInit,{body:{address:e}});return{nonce:t}}},fn=class{_privyInternal;constructor(e){this._privyInternal=e}async link(e,t,n,r){await this._privyInternal.fetch(u.SiweLinkSmartWallet,{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(u.SiweInit,{body:{address:e.address}});return{nonce:t,message:pn({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 pn(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 cn=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(l.TelegramAuthenticate,{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(l.TelegramLink,{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(l.TelegramUnlink,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},ln=class{_privyInternal;_embedded;_mfa;customProvider;phone;email;oauth;siwe;siws;smartWallet;passkey;farcaster;farcasterV2;guest;telegram;constructor(e,t,n,r,i){this._privyInternal=e,this._embedded=t,this._mfa=i,this.customProvider=new Ut(this._privyInternal,t),this.phone=new tn(this._privyInternal,t),this.email=new Wt(this._privyInternal,t),this.oauth=new $t(this._privyInternal,t,n,r),this.guest=new qt(this._privyInternal,t),this.siwe=new nn(this._privyInternal,t),this.siws=new an(this._privyInternal,t),this.smartWallet=new on(this._privyInternal),this.passkey=new en(this._privyInternal,t),this.farcaster=new Gt(this._privyInternal,t),this.farcasterV2=new Kt(this._privyInternal,t),this.telegram=new cn(this._privyInternal,t)}async logout(e){try{this._embedded.reload()}catch{this._privyInternal.logger.warn(`Error reloading embedded wallet`)}let t=await this._prepareSessionRevocation();await Promise.all([this._privyInternal.session.destroyLocalState({reason:`logout`}),this._privyInternal.destroyClientAnalyticsId(),e?.userId&&this._mfa.clearMfa({userId:e.userId})]),this._privyInternal.callbacks?.setUser?.(null),t&&this._privyInternal.fetch(l.Logout,{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}}},un=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(l.CoinbaseOnRampInit,{body:e})}async getStatus(e){return await this._privyInternal.fetch(l.CoinbaseOnRampStatus,{query:{partnerUserId:e}})}};const dn={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},fn=new Set([d.mainnet.id,d.arbitrum.id,d.base.id,d.polygon.id,d.avalanche.id,d.celo.id,d.monadMainnet.id]),pn=new Set([d.mainnet.id,d.arbitrum.id,d.optimism.id,d.base.id,d.polygon.id,d.avalanche.id]);function mn(e,t){switch(t){case`native-currency`:return fn.has(e);case`USDC`:return pn.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function hn(e,t){switch(e){case d.arbitrum.id:return t===`native-currency`?`ETH_ARBITRUM`:`USDC_ARBITRUM`;case d.avalanche.id:return t===`native-currency`?`AVAX_CCHAIN`:`USDC_CCHAIN`;case d.base.id:return t===`native-currency`?`ETH_BASE`:`USDC_BASE`;case d.celo.id:return`CELO_CELO`;case d.polygon.id:return t===`native-currency`?`MATIC_POLYGON`:`USDC_POLYGON`;case d.monadMainnet.id:return`MON_MON`;case d.mainnet.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 gn(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var _n=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(l.MoonpayOnRampSign,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=dn[t?`sandbox`:`prod`],i=await(0,re.default)(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new pe({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}},vn=class{moonpay;coinbase;constructor(e){this.moonpay=new _n(e),this.coinbase=new un(e)}},yn=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(l.MfaPasskeyInit,{body:e})}},bn=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(l.MfaPasswordlessSmsInit,{body:e})}},xn=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new bn(e),this.passkey=new yn(e)}setProxy(e){this.proxy=e}async getAccessTokenInternal(){let e=await this.privyInternal.getAccessTokenInternal();if(!e)throw new w({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return e}async verifyMfa(){if(!this.proxy)throw new w({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 w({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 w({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 w({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 w({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 w({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.clearMfa(e)}},Sn=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(l.RecoveryOAuthInitICloud,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(l.RecoveryConfigurationICloud,{body:{client_type:e}})}},Cn=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=Xt(),n=Zt(),r=await Qt({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put(Y,t),this._storage.put(J,n)]),this._privyInternal.fetch(l.RecoveryOAuthInit,{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 w({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let i=await this._privyInternal.fetch(l.RecoveryOAuthAuthenticate,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del(Y),this._storage.del(J)]),i}},wn=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new Cn(this._privyInternal,t,n),this.icloudAuth=new Sn(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(l.RecoveryKeyMaterial,{body:{chain_type:t},params:{address:e}})}},Tn=class{plugins;auth;user;embeddedWallet;recovery;mfa;app;mfaPromises;funding;delegated;crossApp;isMultiUserModeEnabled;_privyInternal;constructor({clientId:e,sessions:t,plugins:n=[],...r}){let i=ae(r.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this.plugins=[...n],this._privyInternal=new Nt({...r,appClientId:e,crypto:i,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new xn(this._privyInternal),this.mfaPromises=new vt,this.app=new ue(this._privyInternal),this.embeddedWallet=new _t(this._privyInternal,r.embeddedWalletMessagePoster,r.supportedChains,this.mfa,this.mfaPromises,this.app,ce(this.plugins)),this.user=new Pt(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new ln(this._privyInternal,this.embeddedWallet,r.storage,i,this.mfa),this.recovery=new wn(this._privyInternal,r.storage,i),this.funding=new vn(this._privyInternal),this.delegated=new fe(this._privyInternal),this.crossApp=new de(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}},En=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)}},Dn=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 On=e=>e?e.linked_accounts.filter(Ft).filter(kn).sort((e,t)=>e.wallet_index-t.wallet_index):[],kn=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,An=(e,t)=>{if(!e)return null;if(t?.imported||t&&T(t))return jn(t);let n=K(e)??zt(e);return n?jn(n):null},jn=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`)},Mn=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,Nn=(e,t)=>(0,y.isPossiblePhoneNumber)(String(e),t),Pn=e=>(0,y.parsePhoneNumberFromString)(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),Fn=(e,t)=>`+${(0,y.getCountryCallingCode)(t)} ${e}`,In=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,Ln=e=>new y.AsYouType(e),Rn=(0,y.getCountries)().map(e=>({code:e,callCode:(0,y.getCountryCallingCode)(e)})),zn=e=>{let t=(0,y.getExampleNumber)(e,ie.default)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},Bn=e=>{let t=new y.AsYouType;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},Vn=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),Hn={[d.mainnet.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[d.sepolia.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[d.optimism.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[d.optimismSepolia.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[d.polygon.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[d.polygonAmoy.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[d.base.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[d.baseSepolia.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[d.avalanche.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[d.avalancheFuji.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[d.arbitrum.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[d.arbitrumSepolia.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},Un={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function Wn(e,t){return e===Hn[t.id]}async function Gn(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 Kn=new Set([d.mainnet.id,d.base.id,d.optimism.id,d.polygon.id,d.arbitrum.id,d.avalanche.id,d.monadMainnet.id]),qn=new Set([d.mainnet.id,d.base.id,d.polygon.id,d.optimism.id,d.arbitrum.id,d.avalanche.id,d.monadMainnet.id]),Jn={buy:`CARD`,send:`CRYPTO_ACCOUNT`},Yn={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`},Xn={[d.mainnet.id]:`ethereum`,[d.base.id]:`base`,[d.optimism.id]:`optimism`,[d.polygon.id]:`polygon`,[d.arbitrum.id]:`arbitrum`,[d.avalanche.id]:`avacchain`,[d.monadMainnet.id]:`monad`};function Zn(e){return e.startsWith(`.`)?`0${e}`:e}function Qn({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`,Zn(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,Jn[a]),o.searchParams.set(`defaultAsset`,Yn[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const $n=(e,t)=>{switch(t){case`native-currency`:return Kn.has(e);case`USDC`:return qn.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function er(e){return Xn[e]}function tr(e,t){return t===`USDC`?`USDC`:e===d.polygon.id?`POL`:e===d.monadMainnet.id?`MON`:`ETH`}const nr=e=>e.provider.replace(/-sandbox$/,``),rr={BINANCECONNECT:`BINANCE_CONNECT`,COINBASEPAY:`COINBASE`},ir=e=>{let t=(e.sub_provider?.trim()||nr(e)).toUpperCase();return rr[t]??t};var ar=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=ae(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 or=({address:e,nonce:t,domain:n,uri:r})=>`${n} wants you to sign in with your Solana account:
|
|
23
|
+
- https://privy.io`}var mn=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(u.TelegramAuthenticate,{body:{telegram_web_app_data:e,telegram_auth_result:t,captcha_token:n,mode:r}});await this._privyInternal.session.updateWithTokensResponse(a);let o=await J(this._embedded,a,i?.embedded);return this._privyInternal.callbacks?.setUser?.(o.user),o}async link({telegramWebAppData:e,telegramAuthResult:t,captchaToken:n}){await this._privyInternal.fetch(u.TelegramLink,{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(u.TelegramUnlink,{body:{telegram_user_id:e}});let t=await this._privyInternal.refreshSession();return{user:t.user,identity_token:t.identity_token}}},hn=class{_privyInternal;_embedded;_mfa;customProvider;phone;email;oauth;siwe;siws;smartWallet;passkey;farcaster;farcasterV2;guest;telegram;constructor(e,t,n,r,i){this._privyInternal=e,this._embedded=t,this._mfa=i,this.customProvider=new Yt(this._privyInternal,t),this.phone=new cn(this._privyInternal,t),this.email=new Xt(this._privyInternal,t),this.oauth=new on(this._privyInternal,t,n,r),this.guest=new $t(this._privyInternal,t),this.siwe=new ln(this._privyInternal,t),this.siws=new dn(this._privyInternal,t),this.smartWallet=new fn(this._privyInternal),this.passkey=new sn(this._privyInternal,t),this.farcaster=new Zt(this._privyInternal,t),this.farcasterV2=new Qt(this._privyInternal,t),this.telegram=new mn(this._privyInternal,t)}async logout(e){try{this._embedded.reload()}catch{this._privyInternal.logger.warn(`Error reloading embedded wallet`)}let t=await this._prepareSessionRevocation();await Promise.all([this._privyInternal.session.destroyLocalState({reason:`logout`}),this._privyInternal.destroyClientAnalyticsId(),e?.userId&&this._mfa.clearMfa({userId:e.userId}).catch(e=>{this._privyInternal.logger.warn(`Error clearing MFA state`,e)})]),this._privyInternal.callbacks?.setUser?.(null),t&&this._privyInternal.fetch(u.Logout,{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}}},gn=class{_privyInternal;constructor(e){this._privyInternal=e}async initOnRampSession(e){return await this._privyInternal.fetch(u.CoinbaseOnRampInit,{body:e})}async getStatus(e){return await this._privyInternal.fetch(u.CoinbaseOnRampStatus,{query:{partnerUserId:e}})}};const _n={prod:{url:`https://api.moonpay.com/v1`,key:`pk_live_hirbpu0cVcLHrjktC9l7fbc9ctjv0SL`},sandbox:{url:`https://api.moonpay.com/v1`,key:`pk_test_fqWjXZMSFwloh7orvJsRfjiUHXJqFzI`}},vn=new Set([f.mainnet.id,f.arbitrum.id,f.base.id,f.polygon.id,f.avalanche.id,f.celo.id,f.monadMainnet.id]),yn=new Set([f.mainnet.id,f.arbitrum.id,f.optimism.id,f.base.id,f.polygon.id,f.avalanche.id]);function bn(e,t){switch(t){case`native-currency`:return vn.has(e);case`USDC`:return yn.has(e);default:return console.warn(`Unknown asset passed to MoonPay Onramp`),!1}}function xn(e,t){switch(e){case f.arbitrum.id:return t===`native-currency`?`ETH_ARBITRUM`:`USDC_ARBITRUM`;case f.avalanche.id:return t===`native-currency`?`AVAX_CCHAIN`:`USDC_CCHAIN`;case f.base.id:return t===`native-currency`?`ETH_BASE`:`USDC_BASE`;case f.celo.id:return`CELO_CELO`;case f.polygon.id:return t===`native-currency`?`MATIC_POLYGON`:`USDC_POLYGON`;case f.monadMainnet.id:return`MON_MON`;case f.mainnet.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 Sn(e){switch(e){case`card`:case`payment-request`:return`credit_debit_card`;default:throw Error(`Unsupported Moonpay funding method ${e}`)}}var Cn=class{_privyInternal;constructor(e){this._privyInternal=e}async sign(e){return await this._privyInternal.fetch(u.MoonpayOnRampSign,{body:e})}async getTransactionStatus({transactionId:e,useSandbox:t}){let{url:n,key:r}=_n[t?`sandbox`:`prod`],i=await(0,te.default)(fetch,{retries:3,retryDelay:500})(`${n}/transactions/ext/${e}?apiKey=${r}`);if(!i.ok)throw new de({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}},wn=class{moonpay;coinbase;constructor(e){this.moonpay=new Cn(e),this.coinbase=new gn(e)}},Tn=class{_privyInternal;constructor(e){this._privyInternal=e}async generateAuthenticationOptions(e){return await this._privyInternal.fetch(u.MfaPasskeyInit,{body:e})}},En=class{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(e){return await this._privyInternal.fetch(u.MfaPasswordlessSmsInit,{body:e})}},Dn=class{privyInternal;proxy;sms;passkey;constructor(e,t){this.proxy=t,this.privyInternal=e,this.sms=new En(e),this.passkey=new Tn(e)}setProxy(e){this.proxy=e}async getAccessTokenInternal(){let e=await this.privyInternal.getAccessTokenInternal();if(!e)throw new S({error:`Missing access token`,code:`attempted_rpc_call_before_logged_in`});return e}async verifyMfa(){if(!this.proxy)throw new S({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 S({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 S({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 S({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 S({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 S({error:`Embedded wallet proxy not initialized`,code:`embedded_wallet_webview_not_loaded`});return await this.proxy.clearMfa(e)}},On=class{_privyInternal;constructor(e){this._privyInternal=e}async init(e){return this._privyInternal.fetch(u.RecoveryOAuthInitICloud,{body:{client_type:e}})}async getICloudConfiguration(e){return this._privyInternal.fetch(u.RecoveryConfigurationICloud,{body:{client_type:e}})}},kn=class{_privyInternal;_storage;_crypto;constructor(e,t,n){this._privyInternal=e,this._storage=t,this._crypto=n}async generateURL(e){let t=nn(),n=rn(),r=await an({codeVerifier:t,digest:this._crypto.digest});return await Promise.all([this._storage.put(X,t),this._storage.put(Y,n)]),this._privyInternal.fetch(u.RecoveryOAuthInit,{body:{redirect_to:e,code_challenge:r,state_code:n}})}async authorize(e,t){let[n,r]=await Promise.all([this._storage.get(X),this._storage.get(Y)]);if(r!==t)throw this._privyInternal.createAnalyticsEvent(`possible_phishing_attempt`,{flow:`recovery_oauth`,storedStateCode:r??``,returnedStateCode:t??``}),new S({code:`pkce_state_code_mismatch`,error:`Unexpected auth flow. This may be a phishing attempt.`});let i=await this._privyInternal.fetch(u.RecoveryOAuthAuthenticate,{body:{authorization_code:e,state_code:r,code_verifier:n}});return await Promise.all([this._storage.del(X),this._storage.del(Y)]),i}},An=class{_privyInternal;auth;icloudAuth;constructor(e,t,n){this._privyInternal=e,this.auth=new kn(this._privyInternal,t,n),this.icloudAuth=new On(this._privyInternal)}async getRecoveryKeyMaterial(e,t){return this._privyInternal.fetch(u.RecoveryKeyMaterial,{body:{chain_type:t},params:{address:e}})}},jn=class{plugins;auth;user;embeddedWallet;recovery;mfa;app;mfaPromises;funding;delegated;crossApp;isMultiUserModeEnabled;_privyInternal;constructor({clientId:e,sessions:t,plugins:n=[],...r}){let i=re(r.crypto);this.isMultiUserModeEnabled=t?.mode===`multi-user`,this.plugins=[...n],this._privyInternal=new zt({...r,appClientId:e,crypto:i,isMultiUserModeEnabled:this.isMultiUserModeEnabled,cookieWriteBehavior:t?.cookieWriteBehavior}),this.mfa=new Dn(this._privyInternal),this.mfaPromises=new wt,this.app=new ue(this._privyInternal),this.embeddedWallet=new Ct(this._privyInternal,r.embeddedWalletMessagePoster,r.supportedChains,this.mfa,this.mfaPromises,this.app,ce(this.plugins)),this.user=new Bt(this._privyInternal,this.embeddedWallet,t?.mode===`multi-user`),this.auth=new hn(this._privyInternal,this.embeddedWallet,r.storage,i,this.mfa),this.recovery=new An(this._privyInternal,r.storage,i),this.funding=new wn(this._privyInternal),this.delegated=new ge(this._privyInternal),this.crossApp=new he(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}},Mn=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)}},Nn=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 Pn=e=>e?e.linked_accounts.filter(Vt).filter(Fn).sort((e,t)=>e.wallet_index-t.wallet_index):[],Fn=e=>e.chain_type===`bitcoin-segwit`||e.chain_type===`bitcoin-taproot`,In=(e,t)=>{if(!e)return null;if(t?.imported||t&&w(t))return Ln(t);let n=q(e)??Gt(e);return n?Ln(n):null},Ln=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`)},Rn=e=>e?.linked_accounts.find(e=>e.type===`smart_wallet`)??null,zn=(e,t)=>(0,b.isPossiblePhoneNumber)(String(e),t),Bn=e=>(0,b.parsePhoneNumberFromString)(e,`US`)?.format(`E.164`)??e.replace(/[\s()-]/g,``),Vn=(e,t)=>`+${(0,b.getCountryCallingCode)(t)} ${e}`,Hn=e=>`*${e.replaceAll(`-`,``).slice(-4)}`,Un=e=>new b.AsYouType(e),Wn=(0,b.getCountries)().map(e=>({code:e,callCode:(0,b.getCountryCallingCode)(e)})),Gn=e=>{let t=(0,b.getExampleNumber)(e,ne.default)?.formatInternational();return t?.substring(t.indexOf(` `)+1)},Kn=e=>{let t=new b.AsYouType;t.input(e);let n=t.getCountry()||`US`,r=t.getCallingCode()||`1`;return{countryCode:n,phone:e.replace(`+`+r,``)}},qn=(e,t=!0)=>e.reduce((e,n)=>({...e,[n]:t}),{}),Jn={[f.mainnet.id]:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`,[f.sepolia.id]:`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`,[f.optimism.id]:`0x0b2c639c533813f4aa9d7837caf62653d097ff85`,[f.optimismSepolia.id]:`0x5fd84259d66Cd46123540766Be93DFE6D43130D7`,[f.polygon.id]:`0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`,[f.polygonAmoy.id]:`0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582`,[f.base.id]:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,[f.baseSepolia.id]:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,[f.avalanche.id]:`0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E`,[f.avalancheFuji.id]:`0x5425890298aed601595a70ab815c96711a31bc65`,[f.arbitrum.id]:`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`,[f.arbitrumSepolia.id]:`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`},Yn={"mainnet-beta":`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,devnet:`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`,testnet:``};function Xn(e,t){return e===Jn[t.id]}async function Zn(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 Qn=new Set([f.mainnet.id,f.base.id,f.optimism.id,f.polygon.id,f.arbitrum.id,f.avalanche.id,f.monadMainnet.id]),$n=new Set([f.mainnet.id,f.base.id,f.polygon.id,f.optimism.id,f.arbitrum.id,f.avalanche.id,f.monadMainnet.id]),er={buy:`CARD`,send:`CRYPTO_ACCOUNT`},tr={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`},nr={[f.mainnet.id]:`ethereum`,[f.base.id]:`base`,[f.optimism.id]:`optimism`,[f.polygon.id]:`polygon`,[f.arbitrum.id]:`arbitrum`,[f.avalanche.id]:`avacchain`,[f.monadMainnet.id]:`monad`};function rr(e){return e.startsWith(`.`)?`0${e}`:e}function ir({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`,rr(n)),o.searchParams.set(`defaultNetwork`,r),o.searchParams.set(`defaultPaymentMethod`,er[a]),o.searchParams.set(`defaultAsset`,tr[i]),o.searchParams.set(`partnerUserId`,t.partner_user_id),{url:o}}const ar=(e,t)=>{switch(t){case`native-currency`:return Qn.has(e);case`USDC`:return $n.has(e);default:return console.warn(`Unknown asset passed to Coinbase Onramp`),!1}};function or(e){return nr[e]}function sr(e,t){return t===`USDC`?`USDC`:e===f.polygon.id?`POL`:e===f.monadMainnet.id?`MON`:`ETH`}const cr=e=>e.provider.replace(/-sandbox$/,``),lr={BINANCECONNECT:`BINANCE_CONNECT`,COINBASEPAY:`COINBASE`},ur=e=>{let t=(e.sub_provider?.trim()||cr(e)).toUpperCase();return lr[t]??t};var dr=class{cluster;_crypto;constructor(e,t){this.cluster=e,this._crypto=re(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 fr=({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 sr({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 cr({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function lr(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const ur=`solana offchain`,dr=1232;function fr(e){let t=g.encoding.utf8.toBytes(e),n=new Uint8Array(32);return n.set(t.slice(0,32)),n}function pr({message:e,signerPublicKey:t,domain:n}){let r=g.encoding.utf8.toBytes(e);if(t.length!==32)throw Error(`Signer public key must be 32 bytes`);let i=85+r.length;if(i>dr)throw Error(`Combined message length (${i}) exceeds maximum (${dr})`);let a=fr(n),o=new Uint8Array(i),s=0;o[s]=255,s+=1;let c=g.encoding.utf8.toBytes(ur);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 mr(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))!==ur)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 hr=[`privy`],gr=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],_r=[`coinbase_wallet`],vr=`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(`.`),yr=[`unknown`],br=[...gr,..._r,...vr,...hr,...yr],xr=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Sr(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function Cr({wei:e,precision:t=3}){return parseFloat((0,p.formatEther)(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function wr({amount:e,decimals:t}){return(0,p.formatUnits)(BigInt(e),t)}function Tr({lamports:e}){return(0,p.formatUnits)(e,9)}const Er=e=>[...It(e),...Rt(e)],Dr=(e,t)=>e.imported?e:K(t)??zt(t),Or=e=>async({address:t,chainType:n})=>{let{user:r}=await e.user.get();if(!r)throw new w({code:`delegated_actions_before_logged_in`,error:`Must be logged in to delegate wallets`});if(n!==`solana`&&n!==`ethereum`)throw new w({code:`unsupported_chain_type`,error:`Only Solana and Ethereum embedded wallets are supported for delegation and revocation.`});let i=Er(r).find(e=>e.chain_type===n&&e.address===t);if(!i)throw new w({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});if(T(i))throw new w({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=Dr(i,r);if(!a)throw new w({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}},kr=e=>async()=>{let{user:t}=await e.user.get();if(!t)throw new w({code:`delegated_actions_before_logged_in`,error:`Must be logged in to revoke delegated wallets`});let n=Er(t);if(n.some(T))throw new w({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 w({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 Ar=o({delegateWallet:()=>Or,revokeWallets:()=>kr});const jr=({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 w({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},Mr=({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 w({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 Nr(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const Pr=(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)),Fr=({client:e,openAuthSession:t})=>{let n=Mr({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))},Ir=({client:e,openAuthSession:t})=>{let n=Fr({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=Pr(r,o);if(!s)throw new w({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 w({code:`cross_app_invalid_app`,error:`Invalid connected app`});if(u.read_only)throw new w({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 w({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 w({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(m===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new w({code:`cross_app_request_error`,error:h});if(m!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new w({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:h}}};function Lr(e){if(!e)throw new w({code:`attempted_cross_app_request_before_logged_in`,error:`Must be logged in to sign messages with a cross-app wallet`})}const Rr=({client:e,openAuthSession:t})=>{let n=Ir({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{Lr(e);let a={method:Nr(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 zr(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 Br=({client:e,openAuthSession:t})=>{let n=Ir({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{Lr(e);let a={method:Nr(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,zr(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},Vr=({client:e,openAuthSession:t})=>{let n=Ir({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{Lr(e);let a={method:Nr(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var Hr=o({sendTransaction:()=>Vr,signMessage:()=>Rr,signTypedData:()=>Br}),Ur=o({linkWithCrossAppAuth:()=>Mr,loginWithCrossAppAuth:()=>jr,wallet:()=>Hr});function Wr(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 Gr(e,t){let n=Wr(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 Kr(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=Gr(e.caip2,t);if(n)return{ok:!0,address:n};let r=Wr(e.caip2);if(!r)return{ok:!1,error:`UNSUPPORTED_CHAIN`};try{let t=await e.privy.fetchPrivyRoute(l.WalletCreate,{body:{chain_type:r}});return await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function qr(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await Kr({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.CreateDepositAddressQuote,{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 Jr(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 Jr(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 Jr(r)}catch(e){e instanceof Error&&(c=e),o<i&&await Jr(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},Yr=2e3,Xr=1800*1e3;function Zr(e,t){return Math.ceil(t/e)}function Qr(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 $r(e){return await e.privy.fetchPrivyRoute(l.GetDepositAddressOrder,{params:{order_id:e.orderId}})}async function ei(e){let t=e.pollIntervalMs??Yr,n=e.timeoutMs??Xr,r=e.signal??new AbortController().signal;return Qr(await X({operation:async()=>{let t=await e.privy.fetchPrivyRoute(l.GetNextDepositAddressOrder,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(l.GetDepositAddressOrder,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:Zr(t,n),signal:r}))}async function ti(e){let t=e.pollIntervalMs??Yr,n=e.timeoutMs??Xr,r=e.signal??new AbortController().signal;return Qr(await X({operation:()=>e.privy.fetchPrivyRoute(l.GetDepositAddressOrder,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:Zr(t,n),signal:r}))}var ni=o({generateDepositAddress:()=>qr,getConfig:()=>ri,getDeposit:()=>$r,resolveRefundAddress:()=>Kr,waitForCompletion:()=>ti,waitForDeposit:()=>ei});async function ri(e){let t=await e.fetchPrivyRoute(l.GetDepositConfig,{});return{currencies:t.currencies,chains:t.chains}}function ii(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 ai(e,t,n){let{walletId:r}=n,i=ii(n),a=e.getCompiledPath(l.CreateCryptoDepositAccount,{params:{wallet_id:r}}),o=String(Date.now()+A),{signature:s}=await O(t,{version:1,url:a,method:l.CreateCryptoDepositAccount.method,headers:{"privy-app-id":e.app.appId,[k]:o},body:i});if(Date.now()>Number(o))throw new w({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});let c=await e.fetchPrivyRoute(l.CreateCryptoDepositAccount,{body:i,params:{wallet_id:r},headers:{"privy-authorization-signature":s,[k]: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}}}),c}async function oi(e,t){let n=await e.fetchPrivyRoute(l.CreateCryptoDepositAccountQuote,{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 si(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 ci(e,t){return e.fetchPrivyRoute(l.SearchCryptoDepositAccountConfig,{query:{q:t}})}async function li(e,t){return e.fetchPrivyRoute(l.GetCryptoDepositAccountOrder,{params:{wallet_id:t.walletId,order_id:t.orderId}})}async function ui(e,t){return e.fetchPrivyRoute(l.GetCryptoDepositAccountNextOrder,{params:{wallet_id:t.walletId},query:{after:t.after}})}const di={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`},fi=[{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`}],pi=new Set([`native`,`native-token`,`0x0000000000000000000000000000000000000000`,`11111111111111111111111111111111`]);function mi(e){return pi.has(e.toLowerCase())}function hi(e){return e.includes(`:`)}function Z(e){return hi(e)?e:di[e.toLowerCase()]||(/^\d+$/.test(e)?`eip155:${e}`:e)}function gi(e){return mi(e)}function _i(e){let t=e.toLowerCase();return fi.find(e=>e.id===t||e.symbol.toLowerCase()===t)}function vi({symbol:e,address:t}){return _i(e)?.id??t}function yi({asset:e,symbol:t,addresses:n}){let r=e.toLowerCase();return t.toLowerCase()===r?!0:gi(e)?n.some(mi):n.some(e=>e.toLowerCase()===r)}function bi({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&&yi({asset:n,symbol:t.symbol,addresses:e.map(e=>e.address)}))return t.symbol}return n.toUpperCase()}function xi(e,t,n){return Si(e,n)===Si(t,n)}function Si(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 Ci(e,t){return yi({asset:t.asset,symbol:e.symbol,addresses:e.chains.map(e=>e.address)})}function wi({caip2:e,asset:t,config:n}){return!t.chain||xi(t.chain,e,n)}function Ti({currency:e,source:t,config:n}){switch(t.mode){case`all`:return e.chains;case`include`:{let r=t.values.filter(t=>Ci(e,t));return r.length===0?[]:e.chains.filter(e=>r.some(t=>wi({caip2:e.caip2,asset:t,config:n})))}case`exclude`:{let r=t.values.filter(t=>Ci(e,t));return r.length===0?e.chains:e.chains.filter(e=>!r.some(t=>wi({caip2:e.caip2,asset:t,config:n})))}default:return e.chains}}function Ei(e,t){return{currencies:e.currencies.map(n=>({...n,chains:Ti({currency:n,source:t,config:e})})).filter(e=>e.chains.length>0),chains:e.chains}}function Di(e){return e.startsWith(`0x`)}function Oi(e,t){let n=Di(e);switch(t){case`evm`:case`hypevm`:return n;case`svm`:case`bvm`:case`tron`:case`tvm`:return!n;default:return n}}function ki(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 Ai({accounts:e,selectedChain:t}){if(e.length===0)return;let n=e.filter(e=>ki(e,t.caip2)),r=n.length>0?n:e,i=r.find(e=>Oi(e.deposit_address,t.vmType));return i?i.deposit_address:r[0]?.deposit_address}var ji=o({createCryptoDepositAccount:()=>ai,filterDepositConfig:()=>Ei,findCatalogSymbol:()=>bi,getCryptoDepositAccountNextOrder:()=>ui,getCryptoDepositAccountOrder:()=>li,getCryptoDepositAccountQuote:()=>oi,indicativeRateFromQuote:()=>si,isNativeAssetAlias:()=>gi,pickDepositAddressForChain:()=>Ai,quoteSourceAsset:()=>vi,resolveChainAlias:()=>Z,searchCryptoDepositAccountConfig:()=>ci});async function Mi(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(l.WalletRawSign,{params:{wallet_id:n}}),a=String(Date.now()+A),{signature:o}=await O(t,{version:1,url:i,method:l.WalletRawSign.method,headers:{"privy-app-id":e.app.appId,[k]:a},body:{...r}});if(Date.now()>Number(a))throw new w({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(l.WalletRawSign,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[k]:a}})}async function Ni(e,{wallet_id:t}){return await e.fetchPrivyRoute(l.WalletGet,{params:{wallet_id:t}})}async function Pi(e,{wallet_id:t},n,r){let i=e.getCompiledPath(l.WalletUpdate,{params:{wallet_id:t}}),a=String(Date.now()+A),{signature:o}=await O(n,{version:1,url:i,method:l.WalletUpdate.method,headers:{"privy-app-id":e.app.appId,[k]:a},body:r});if(Date.now()>Number(a))throw new w({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(l.WalletUpdate,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":o,[k]:a}})}async function Fi(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(l.WalletTransfer,{params:{wallet_id:n}}),a=String(Date.now()+A),{signature:o}=await O(t,{version:1,url:i,method:l.WalletTransfer.method,headers:{"privy-app-id":e.app.appId,[k]:a},body:{...r}});if(Date.now()>Number(a))throw new w({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(l.WalletTransfer,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[k]:a}})}async function Ii(e,{wallet_id:t,action_id:n}){return await e.fetchPrivyRoute(l.WalletGetAction,{params:{wallet_id:t,action_id:n}})}async function Li(e,{wallet_id:t,...n}){return await e.fetchPrivyRoute(l.WalletListActions,{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 Ri({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(T(t)){if(n.length===0)throw Error(`Must specify at least one signer to add.`);let r={wallet_id:t.id},i=await Ni(e,r);await Pi(e,r,Vi(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return Bi(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=Dr(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 Bi(e)}async function zi({client:e,wallet:t}){return T(t)?await Pi(e,{wallet_id:t.id},Vi(e),{additional_signers:[]}):await e.delegated.revoke(),Bi(e)}async function Bi(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function Vi(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var Hi=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 Ui=async(e,{environment:t,acceptElectronicDisclosure:n,acceptBankTerms:r})=>{let{data:i}=await e.fetchPrivyRoute(l.AcceptCardConsents,{body:{environment:t,accept_electronic_disclosure:n,accept_bank_terms:r}});return i},Wi=async({sendTransaction:e,evmChainId:t,stablecoinAddress:n,spenderAddress:r})=>{let i={to:n,chainId:t,data:(0,p.encodeFunctionData)({abi:p.erc20Abi,functionName:`approve`,args:[r,p.maxUint256]})};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})}},Gi=[{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`}]}],Ki=async({sendTransaction:e,evmChainId:t,spenderAddress:n,vaultAddress:r})=>{let i={to:n,chainId:t,data:(0,p.encodeFunctionData)({abi:Gi,functionName:`publicCall`,args:[(0,p.concat)([(0,p.stringToHex)(`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})}},qi=async(e,{environment:t,walletId:n,chainId:r,asset:i})=>e.fetchPrivyRoute(l.CreateCard,{body:{environment:t,wallet_id:n,chain_id:r,asset:i}}),Q=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(l.GetCardCustomer,{query:{environment:t}});return n},Ji=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(l.UpsertCardCustomer,{body:{environment:t}});return n},Yi=async(e,{environment:t,limit:n,cursor:r})=>e.fetchPrivyRoute(l.ListCards,{query:{environment:t,...n===void 0?{}:{limit:n},...r?{cursor:r}:{}}}),Xi=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:(0,p.encodeFunctionData)({abi:p.erc20Abi,functionName:`allowance`,args:[n,i]})},`latest`]});if(!(0,p.isHex)(a)||a===`0x`)throw Error(`Could not read the spend approval`);return(0,p.decodeFunctionResult)({abi:p.erc20Abi,functionName:`allowance`,data:a})},Zi=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:(0,p.encodeFunctionData)({abi:Gi,functionName:`publicGetCall`,args:[(0,p.concat)([(0,p.stringToHex)(`TEGP`),n])]})},`latest`]});if(!(0,p.isHex)(i)||i===`0x`)throw Error(`Could not read the card vault choice`);let[a]=(0,p.decodeAbiParameters)([{type:`address`}],(0,p.decodeFunctionResult)({abi:Gi,functionName:`publicGetCall`,data:i}));return a},Qi=2e3,$i=1e3,ea=new Map([[`morpho`,`Morpho`],[`aave`,`Aave`]]),ta=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}},na=e=>{try{return new URL(e).protocol===`https:`?e:null}catch{return null}},$=e=>e instanceof Error&&e.message?e.message:void 0,ra=({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)),m=async()=>Xi({provider:await d.getProvider(),evmChainId:f,owner:d.address,stablecoinAddress:c,spenderAddress:s}),h=async()=>Zi({provider:await d.getProvider(),evmChainId:f,owner:d.address,spenderAddress:s});return{kind:`supported`,isApproved:async()=>await m()>0n&&(o.kind!==`opt_in`||await h()!==p.zeroAddress),approve:async()=>{if(await Wi({sendTransaction:d.sendTransaction,evmChainId:f,stablecoinAddress:c,spenderAddress:s}),o.kind!==`opt_in`)return;let a=await X({operation:m,until:e=>e>0n,delay:0,interval:$i,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 h();if(i.aborted||u!==p.zeroAddress)return;await Ki({sendTransaction:d.sendTransaction,evmChainId:f,spenderAddress:s,vaultAddress:o.vaultAddress});let g=await X({operation:h,until:e=>e.toLowerCase()===o.vaultAddress.toLowerCase(),delay:0,interval:$i,attempts:60,signal:i});if(g.status===`max_attempts`)throw Error(`The vault choice did not land in time`,{cause:g.error});g.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)}},m=async a=>{if(!a.aborted)try{let o=await Yi(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 qi(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=ea.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)})}},h=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 Ji(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:Qi,attempts:60,signal:n})).status!==`success`)return;continue;case`under_review`:s({status:`under-review`});return;case`ready`:await m(n);return;case`rejected`:s({status:`rejected`,reason:i.rejection_reasons?.[0]?.reason});return;case`error`:s({status:`error`});return;default:return}}},g=async({page:n,url:r,until:i,signal:o})=>{let s=na(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:Qi,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`},_=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=ta(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 h(r)},ee=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:ee,start(e){s({status:`get-started`,pending:!0}),h(e)},acceptDisclosure(n){(async()=>{s({status:`accepting-disclosure`});try{await Ui(e,{environment:t,acceptElectronicDisclosure:!0})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}n.aborted||await h(n)})()},acceptBankTerms(n){let r=a.openHostedPage();(async()=>{s({status:`accepting-bank-terms`});let i;try{i=await Ui(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 g({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 _(`provider`,n);return}await h(n);return}r?.dismiss(),await h(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 g({url:t.url,until:n,signal:e});if(r!==`aborted`){if(r===`blocked`){s({status:`error`});return}if(r===`closed`||r===`stalled`){await _(t.kind,e);return}await h(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){ee(e)}}},ia=async(e,{cardId:t,environment:n,statementPeriod:r})=>(await e.fetchPrivyRouteRaw(l.DownloadCardStatement,{params:{card_id:t,statement_period:r},query:{environment:n}})).blob(),aa=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),oa=e=>Number.isFinite(e)?aa.format(Math.abs(e)/100):``,sa=({amount:e,status:t})=>e===0?`none`:t===`posted`&&e>0?`credit`:`debit`,ca=({amount:e,status:t})=>{if(!Number.isFinite(e))return{text:``,isCredit:!1};let n=oa(e);switch(sa({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}}},la={month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`},ua=new Intl.DateTimeFormat(void 0,la),da=new Intl.DateTimeFormat(void 0,{...la,year:`numeric`}),fa=({unixSeconds:e})=>{let t=new Date(e*1e3);return Number.isNaN(t.getTime())?``:(t.getFullYear()===new Date().getFullYear()?ua:da).format(t)},pa={usdc:`USDC`,pathusd:`PathUSD`,path_usd:`PathUSD`,ousd:`OUSD`},ma=e=>e?pa[e.toLowerCase()]??e:``,ha=async(e,{cardId:t,environment:n})=>{let{data:r}=await Yi(e,{environment:n,limit:20});return r.find(e=>e.id===t)??null},ga=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.`,_a=async(e,{cardId:t,environment:n,nonce:r})=>{let{data:i}=await e.fetchPrivyRoute(l.GetCardEphemeralKey,{params:{card_id:t},body:{environment:n,nonce:r}});return i.ephemeral_key_secret},va=async(e,{appId:t,environment:n})=>{let{data:r}=await e.fetchPrivyRoute(l.GetCardsConfig,{params:{app_id:t},query:{environment:n}});return{publishableKey:r.publishable_key,cardLogoUrl:r.card_logo_url??null,stripeAccount:r.stripe_account}},ya=`eip155:42431`,ba=[`eip155:11155111`,`eip155:11155420`,`eip155:80002`,`eip155:84532`,`eip155:421614`,`eip155:43113`],xa=[`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,`solana:devnet`],Sa={...Object.fromEntries(ba.flatMap(e=>{let t=Hn[Number.parseInt(e.replace(`eip155:`,``))];return t?[[e,{stablecoinAddress:t,spenderAddress:`0x8cc0d9e8a157b73d1172a22f5066048bda46c0e3`}]]:[]})),[ya]:{stablecoinAddress:`0x20C0000000000000000000000000000000000000`,spenderAddress:`0x1955a82a01E8c0A31371792b3045341eB8b938e2`},...Object.fromEntries(xa.map(e=>[e,{stablecoinAddress:Un.devnet,programId:`cardWArqhdV5jeRXXjUti7cHAa4mj41Nj3Apc6RPZH2`,merchantId:1n}]))},Ca=(e,t)=>{let n=Sa[e];if(n)return t===`ousd`&&e===ya&&`spenderAddress`in n?{stablecoinAddress:`0x20c0000000000000000000006a37DA5C996874BE`,spenderAddress:`0x249E4Ce1A8fd56d7C362c108aDf409eeDCb940aB`}:n},wa={"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":`solana:mainnet`,"solana:mainnet":`solana:mainnet`,"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":`solana:devnet`,"solana:devnet":`solana:devnet`},Ta=(e,t,n)=>{let r=t??Ca(e,n);if(!r)return null;let i=wa[e];return i?`programId`in r?{...r,kind:`svm`,chain:i,merchantId:BigInt(r.merchantId)}:Ea(e,t):e.startsWith(`eip155:`)&&`spenderAddress`in r?{kind:`evm`,...r}:Ea(e,t)},Ea=(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),Da=e=>e.status===`pending`?`pending`:e.status===`declined`?`declined`:e.status===`expired`?`expired`:e.status===`reversed`?`reversed`:sa(e)===`credit`?`credit`:null,Oa=({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`))}},ka=({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},Aa=async(e,{cardId:t,environment:n,limit:r,cursor:i})=>e.fetchPrivyRoute(l.ListCardTransactions,{params:{card_id:t},query:{environment:n,...r===void 0?{}:{limit:r},...i?{cursor:i}:{}}}),ja=async(e,{cardId:t,environment:n,reason:r})=>e.fetchPrivyRoute(l.ReplaceCard,{params:{card_id:t},body:{environment:n,replacement_reason:r}}),Ma=({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}),Na=async(e,{cardId:t,environment:n,encryptedNumber:r})=>e.fetchPrivyRoute(l.UpdateCardPin,{params:{card_id:t},body:{environment:n,pin:{encrypted_number:r}}}),Pa=async(e,{cardId:t,environment:n,status:r})=>e.fetchPrivyRoute(l.UpdateCard,{params:{card_id:t},body:{environment:n,status:r}});var Fa=Tn;exports.ALL_WALLET_CLIENT_TYPES=br,exports.BICONOMY=`biconomy`,exports.COINBASE_SMART_WALLET=`coinbase_smart_wallet`,exports.ConnectedStandardSolanaWallet=Hi,exports.DATA_SUFFIX_PLUGIN_ID=se,exports.EmbeddedProviderError=Ce,exports.InMemoryCache=Dn,exports.KERNEL=`kernel`,exports.LIGHT_ACCOUNT=`light_account`,exports.LIST_CARDS_MAX_LIMIT=20,exports.LocalStorage=En,exports.MoonpayApiError=pe,exports.NEXUS=`nexus`,exports.PrivyApiError=C,exports.PrivyClientError=w,exports.PrivyConnectorError=Se,exports.PrivyEmbeddedWalletErrorCode=ve,exports.PrivyProviderRpcError=ke,exports.ProviderErrors=E,exports.SAFE=`safe`,exports.SUPPORTED_CONNECTOR_TYPES=xr,exports.SolanaClient=ar,exports.SolanaUsdcAddressMap=Un,exports.THIRDWEB=`thirdweb`,exports.UsdcAddressMap=Hn,exports.acceptCardConsents=Ui,exports.addSessionSigners=Ri,exports.approveSpend=Wi,exports.buildSolanaOffchainMessage=pr,exports.chainToMoonpayCurrency=hn,exports.chooseTempoEarnVault=Ki,exports.cookies=I,exports.countryCodesAndNumbers=Rn,exports.create=ht,exports.createCard=qi,exports.createCardSignUp=ra,exports.createDataSuffixPlugin=le,exports.createErrorFormatter=he,exports.createSiwsMessage=or,Object.defineProperty(exports,"crossApp",{enumerable:!0,get:function(){return Ur}}),Object.defineProperty(exports,"cryptoDepositAccount",{enumerable:!0,get:function(){return ji}}),exports.default=Fa,Object.defineProperty(exports,"delegatedActions",{enumerable:!0,get:function(){return Ar}}),Object.defineProperty(exports,"depositAddress",{enumerable:!0,get:function(){return ni}}),exports.deriveSolanaApplicationDomain=fr,exports.downloadCardStatement=ia,exports.errorIndicatesMaxMfaRetries=De,exports.errorIndicatesMfaCanceled=ge,exports.errorIndicatesMfaRateLimit=Oe,exports.errorIndicatesMfaTimeout=Te,exports.errorIndicatesMfaVerificationFailed=Ee,exports.errorIndicatesRecoveryIsNeeded=we,exports.formatLamportsAmount=Tr,exports.formatPhoneNumber=Fn,exports.formatSignedTransactionAmount=ca,exports.formatTokenAmount=wr,exports.formatTransactionDate=fa,exports.formatUsdAmount=oa,exports.formatWalletAddress=Sr,exports.formatWeiAmount=Cr,exports.fundingMethodToMoonpayPaymentMethod=gn,exports.generateAuthorizationSignature=O,exports.generateWalletIdempotencyKey=Gn,exports.getAllUserEmbeddedBitcoinWallets=On,exports.getAllUserEmbeddedEthereumWallets=It,exports.getAllUserEmbeddedSolanaWallets=Rt,exports.getCardAssetDisplayName=ma,exports.getCardById=ha,exports.getCardCustomer=Q,exports.getCardDisclosure=ga,exports.getCardEphemeralKey=_a,exports.getCardsConfig=va,exports.getCoinbaseOnRampUrl=Qn,exports.getCountryCallingCode=y.getCountryCallingCode,exports.getDataSuffixPlugin=ce,exports.getEntropyDetailsFromAccount=jn,exports.getEntropyDetailsFromUser=An,exports.getFiatOnrampProviderBrand=ir,exports.getFiatOnrampProviderId=nr,exports.getIsTokenUsdc=Wn,exports.getJsonRpcEndpointFromChain=Ke,exports.getOrCreateCardCustomer=Ji,exports.getPhoneCountryCodeAndNumber=Bn,exports.getPlaceholderPhoneNumber=zn,exports.getSolanaClusterDisplayName=lr,exports.getSolanaRpcEndpointForCluster=sr,exports.getSolanaUsdcMintAddressForCluster=cr,exports.getSpendApproval=Ta,exports.getTransactionBadge=Da,exports.getUserEmbeddedEthereumWallet=K,exports.getUserEmbeddedSolanaWallet=zt,exports.getUserEmbeddedWallet=Lt,exports.getUserSmartWallet=Mn,exports.getWallet=Ni,exports.getWalletAction=Ii,exports.handleSignUpClose=Oa,exports.isCardExpired=ka,exports.isEmbeddedWalletAccount=Ft,exports.isExtensionContext=bt,exports.isSupportedChainIdForCoinbaseOnramp=$n,exports.isSupportedChainIdForMoonpay=mn,exports.isUnifiedWallet=T,exports.lastFourDigits=In,exports.listCardTransactions=Aa,exports.listCards=Yi,exports.listWalletActions=Li,exports.parseSolanaOffchainMessage=mr,exports.phoneNumberTypingFormatter=Ln,exports.poll=X,exports.rawSign=Mi,exports.readSpendAllowance=Xi,exports.readTempoEarnVault=Zi,exports.removeSessionSigners=zi,exports.replaceCard=ja,exports.rpc=j,exports.shouldWriteSessionCookies=xt,exports.throwIfInvalidRecoveryUpgradePath=qe,exports.toCoinbaseAssetId=tr,exports.toCoinbaseBlockchainFromChainId=er,exports.toE164=Pn,exports.toObjectKeys=Vn,exports.toTransactionRow=Ma,exports.toWalletApiUnsignedEthTransaction=Ae,exports.transfer=Fi,exports.updateCardPin=Na,exports.updateCardStatus=Pa,exports.updateWallet=Pi,exports.validatePhoneNumber=Nn,Object.keys(d).forEach(function(e){e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return d[e]}})});
|
|
34
|
+
- https://privy.io`;function pr({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 mr({name:e}){switch(e){case`mainnet-beta`:return`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`;case`devnet`:return`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`;default:throw Error(`USDC not supported on cluster ${e}`)}}function hr(e){switch(e){case`mainnet-beta`:return`Solana`;case`testnet`:return`Testnet`;case`devnet`:return`Devnet`}}const gr=`solana offchain`,_r=1232;function vr(e){let t=l.encoding.utf8.toBytes(e),n=new Uint8Array(32);return n.set(t.slice(0,32)),n}function yr({message:e,signerPublicKey:t,domain:n}){let r=l.encoding.utf8.toBytes(e);if(t.length!==32)throw Error(`Signer public key must be 32 bytes`);let i=85+r.length;if(i>_r)throw Error(`Combined message length (${i}) exceeds maximum (${_r})`);let a=vr(n),o=new Uint8Array(i),s=0;o[s]=255,s+=1;let c=l.encoding.utf8.toBytes(gr);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 br(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))!==gr)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 xr=[`privy`],Sr=[`metamask`,`phantom`,`brave_wallet`,`rainbow`],Cr=[`coinbase_wallet`],wr=`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(`.`),Tr=[`unknown`],Er=[...Sr,...Cr,...wr,...xr,...Tr],Dr=[`injected`,`wallet_connect`,`wallet_connect_v2`,`coinbase_wallet`,`embedded`];function Or(e){return e?`${e.slice(0,5)}…${e.slice(-4)}`:``}function kr({wei:e,precision:t=3}){return parseFloat((0,h.formatEther)(e)).toFixed(t).replace(/0+$/,``).replace(/\.$/,``)}function Ar({amount:e,decimals:t}){return(0,h.formatUnits)(BigInt(e),t)}function jr({lamports:e}){return(0,h.formatUnits)(e,9)}const Mr=e=>[...Ht(e),...Wt(e)],Nr=(e,t)=>e.imported?e:q(t)??Gt(t),Pr=e=>async({address:t,chainType:n})=>{let{user:r}=await e.user.get();if(!r)throw new S({code:`delegated_actions_before_logged_in`,error:`Must be logged in to delegate wallets`});if(n!==`solana`&&n!==`ethereum`)throw new S({code:`unsupported_chain_type`,error:`Only Solana and Ethereum embedded wallets are supported for delegation and revocation.`});let i=Mr(r).find(e=>e.chain_type===n&&e.address===t);if(!i)throw new S({code:`delegated_actions_wallet_not_found`,error:`Address to delegate is not associated with current user.`});if(w(i))throw new S({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=Nr(i,r);if(!a)throw new S({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}},Fr=e=>async()=>{let{user:t}=await e.user.get();if(!t)throw new S({code:`delegated_actions_before_logged_in`,error:`Must be logged in to revoke delegated wallets`});let n=Mr(t);if(n.some(w))throw new S({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 S({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 Ir=o({delegateWallet:()=>Pr,revokeWallets:()=>Fr});const Lr=({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 S({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},Rr=({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 S({code:`login_with_oauth_returned_with_invalid_credentials`,error:`Auth session oauth returned invalid credentials`});let{user:l,oauth_tokens:u}=await e.auth.oauth.linkWithCode(c,s,i);return u&&await e.crossApp.updateOnCrossAppAuthentication(n,u),l};function zr(e,t){return e.linked_accounts.filter(e=>e.type===`cross_app`).flatMap(e=>e.smart_wallets).some(e=>e.address===t)}const Br=(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)),Vr=({client:e,openAuthSession:t})=>{let n=Rr({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))},Hr=({client:e,openAuthSession:t})=>{let n=Vr({client:e,openAuthSession:t});return async({user:r,request:i,redirectUrl:a,address:o})=>{let s=Br(r,o);if(!s)throw new S({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 S({code:`cross_app_invalid_app`,error:`Invalid connected app`});if(u.read_only)throw new S({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 S({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 S({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});if(m===`PRIVY_CROSS_APP_ACTION_ERROR`)throw new S({code:`cross_app_request_error`,error:h});if(m!==`PRIVY_CROSS_APP_ACTION_RESPONSE`)throw new S({code:`cross_app_request_error`,error:`Cross app request returned an invalid result`});return{result:h}}};function Ur(e){if(!e)throw new S({code:`attempted_cross_app_request_before_logged_in`,error:`Must be logged in to sign messages with a cross-app wallet`})}const Wr=({client:e,openAuthSession:t})=>{let n=Hr({client:e,openAuthSession:t});return async({user:e,address:t,message:r,redirectUrl:i})=>{Ur(e);let a={method:zr(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 Gr(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 Kr=({client:e,openAuthSession:t})=>{let n=Hr({client:e,openAuthSession:t});return async({user:e,typedData:t,address:r,redirectUrl:i})=>{Ur(e);let a={method:zr(e,r)?`privy_signSmartWalletTypedData`:`eth_signTypedData_v4`,params:[r,Gr(t)]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{signature:o}}},qr=({client:e,openAuthSession:t})=>{let n=Hr({client:e,openAuthSession:t});return async({user:e,transaction:t,address:r,redirectUrl:i})=>{Ur(e);let a={method:zr(e,r)?`privy_sendSmartWalletTx`:`eth_sendTransaction`,params:[t]},{result:o}=await n({user:e,request:a,address:r,redirectUrl:i});return{transactionHash:o}}};var Jr=o({sendTransaction:()=>qr,signMessage:()=>Wr,signTypedData:()=>Kr}),Yr=o({linkWithCrossAppAuth:()=>Rr,loginWithCrossAppAuth:()=>Lr,wallet:()=>Jr});function Xr(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 Zr(e,t){let n=Xr(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 Qr(e){let{user:t}=await e.privy.user.get();if(!t)return{ok:!1,error:`NOT_AUTHENTICATED`};let n=Zr(e.caip2,t);if(n)return{ok:!0,address:n};let r=Xr(e.caip2);if(!r)return{ok:!1,error:`UNSUPPORTED_CHAIN`};try{let t=await e.privy.fetchPrivyRoute(u.WalletCreate,{body:{chain_type:r}});return await e.privy.user.get(),await e.onWalletCreated?.(),{ok:!0,address:t.address}}catch{return{ok:!1,error:`REFUND_WALLET_CREATION_FAILED`}}}async function $r(e){let{user:t}=await e.privy.user.get();if(!t)throw Error(`NOT_AUTHENTICATED`);let n=e.refundAddress;if(!n){let t=await Qr({privy:e.privy,caip2:e.sourceChain,onWalletCreated:e.onWalletCreated});if(!t.ok)throw Error(t.error);n=t.address}let r=await e.privy.fetchPrivyRoute(u.CreateDepositAddressQuote,{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 ei(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const Z=async({operation:e,until:t,delay:n,interval:r,attempts:i,signal:a})=>{n&&await ei(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 ei(r)}catch(e){e instanceof Error&&(c=e),o<i&&await ei(r)}}return{status:`max_attempts`,result:s,attempts:o,error:c}},ti=2e3,ni=1800*1e3;function ri(e,t){return Math.ceil(t/e)}function ii(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 ai(e){return await e.privy.fetchPrivyRoute(u.GetDepositAddressOrder,{params:{order_id:e.orderId}})}async function oi(e){let t=e.pollIntervalMs??ti,n=e.timeoutMs??ni,r=e.signal??new AbortController().signal;return ii(await Z({operation:async()=>{let t=await e.privy.fetchPrivyRoute(u.GetNextDepositAddressOrder,{params:{deposit_address_id:e.depositAddressId},query:{after:e.quoteCreatedAt}});if(t.order)return await e.privy.fetchPrivyRoute(u.GetDepositAddressOrder,{params:{order_id:t.order.id}})},until:e=>e!==void 0,delay:t,interval:t,attempts:ri(t,n),signal:r}))}async function si(e){let t=e.pollIntervalMs??ti,n=e.timeoutMs??ni,r=e.signal??new AbortController().signal;return ii(await Z({operation:()=>e.privy.fetchPrivyRoute(u.GetDepositAddressOrder,{params:{order_id:e.orderId}}),until:e=>e.status!==`executing`,delay:t,interval:t,attempts:ri(t,n),signal:r}))}var ci=o({generateDepositAddress:()=>$r,getConfig:()=>li,getDeposit:()=>ai,resolveRefundAddress:()=>Qr,waitForCompletion:()=>si,waitForDeposit:()=>oi});async function li(e){let t=await e.fetchPrivyRoute(u.GetDepositConfig,{});return{currencies:t.currencies,chains:t.chains}}function ui(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 di(e,t,n){let{walletId:r}=n,i=ui(n),a=e.getCompiledPath(u.CreateCryptoDepositAccount,{params:{wallet_id:r}}),o=String(Date.now()+N),{signature:s}=await j(t,{version:1,url:a,method:u.CreateCryptoDepositAccount.method,headers:{"privy-app-id":e.app.appId,[M]:o},body:i});if(Date.now()>Number(o))throw new S({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});let c=await e.fetchPrivyRoute(u.CreateCryptoDepositAccount,{body:i,params:{wallet_id:r},headers:{"privy-authorization-signature":s,[M]: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}}}),c}async function fi(e,t){let n=await e.fetchPrivyRoute(u.CreateCryptoDepositAccountQuote,{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 pi(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 mi(e,t){return e.fetchPrivyRoute(u.SearchCryptoDepositAccountConfig,{query:{q:t}})}async function hi(e,t){return e.fetchPrivyRoute(u.GetCryptoDepositAccountOrder,{params:{wallet_id:t.walletId,order_id:t.orderId}})}async function gi(e,t){return e.fetchPrivyRoute(u.GetCryptoDepositAccountNextOrder,{params:{wallet_id:t.walletId},query:{after:t.after}})}const _i={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`},vi=[{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`}],yi=new Set([`native`,`native-token`,`0x0000000000000000000000000000000000000000`,`11111111111111111111111111111111`]);function bi(e){return yi.has(e.toLowerCase())}function xi(e){return e.includes(`:`)}function Si(e){return xi(e)?e:_i[e.toLowerCase()]||(/^\d+$/.test(e)?`eip155:${e}`:e)}function Ci(e){return bi(e)}function wi(e){let t=e.toLowerCase();return vi.find(e=>e.id===t||e.symbol.toLowerCase()===t)}function Ti({symbol:e,address:t}){return wi(e)?.id??t}function Ei({asset:e,symbol:t,addresses:n}){let r=e.toLowerCase();return t.toLowerCase()===r?!0:Ci(e)?n.some(bi):n.some(e=>e.toLowerCase()===r)}function Di({config:e,chain:t,asset:n}){let r=t?Si(t):void 0;for(let t of e.currencies){let e=r?t.chains.filter(e=>Si(e.caip2)===r):t.chains;if(e.length!==0&&Ei({asset:n,symbol:t.symbol,addresses:e.map(e=>e.address)}))return t.symbol}return n.toUpperCase()}function Oi(e,t,n){return ki(e,n)===ki(t,n)}function ki(e,t){if(/^eip155:\d+$/i.test(e))return e.toLowerCase();let n=Si(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 Ai(e,t){return t.asset===`*`||Ei({asset:t.asset,symbol:e.symbol,addresses:e.chains.map(e=>e.address)})}function ji({caip2:e,asset:t,config:n}){return!t.chain||t.chain===`*`||Oi(t.chain,e,n)}function Mi({currency:e,source:t,config:n}){switch(t.mode){case`all`:return e.chains;case`include`:{let r=t.values.filter(t=>Ai(e,t));return r.length===0?[]:e.chains.filter(e=>r.some(t=>ji({caip2:e.caip2,asset:t,config:n})))}case`exclude`:{let r=t.values.filter(t=>Ai(e,t));return r.length===0?e.chains:e.chains.filter(e=>!r.some(t=>ji({caip2:e.caip2,asset:t,config:n})))}default:return e.chains}}function Ni(e,t){return{currencies:e.currencies.map(n=>({...n,chains:Mi({currency:n,source:t,config:e})})).filter(e=>e.chains.length>0),chains:e.chains}}const Pi=/^T[1-9A-HJ-NP-Za-km-z]{33}$/,Fi=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function Ii(e,t){switch(t){case`evm`:case`hypevm`:return(0,h.isAddress)(e,{strict:!1});case`svm`:return Fi.test(e)&&!Pi.test(e);case`tron`:case`tvm`:return Pi.test(e);default:return!1}}function Li({accounts:e,selectedChain:t}){return e.find(e=>Ii(e.deposit_address,t.vmType))?.deposit_address}var Ri=o({createCryptoDepositAccount:()=>di,filterDepositConfig:()=>Ni,findCatalogSymbol:()=>Di,getCryptoDepositAccountNextOrder:()=>gi,getCryptoDepositAccountOrder:()=>hi,getCryptoDepositAccountQuote:()=>fi,indicativeRateFromQuote:()=>pi,isNativeAssetAlias:()=>Ci,pickDepositAddressForChain:()=>Li,quoteSourceAsset:()=>Ti,resolveChainAlias:()=>Si,searchCryptoDepositAccountConfig:()=>mi});async function zi(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(u.WalletRawSign,{params:{wallet_id:n}}),a=String(Date.now()+N),{signature:o}=await j(t,{version:1,url:i,method:u.WalletRawSign.method,headers:{"privy-app-id":e.app.appId,[M]:a},body:{...r}});if(Date.now()>Number(a))throw new S({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(u.WalletRawSign,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[M]:a}})}async function Bi(e,{wallet_id:t}){return await e.fetchPrivyRoute(u.WalletGet,{params:{wallet_id:t}})}async function Vi(e,{wallet_id:t},n,r){let i=e.getCompiledPath(u.WalletUpdate,{params:{wallet_id:t}}),a=String(Date.now()+N),{signature:o}=await j(n,{version:1,url:i,method:u.WalletUpdate.method,headers:{"privy-app-id":e.app.appId,[M]:a},body:r});if(Date.now()>Number(a))throw new S({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(u.WalletUpdate,{params:{wallet_id:t},body:r,headers:{"privy-authorization-signature":o,[M]:a}})}async function Hi(e,t,{wallet_id:n,...r}){let i=e.getCompiledPath(u.WalletTransfer,{params:{wallet_id:n}}),a=String(Date.now()+N),{signature:o}=await j(t,{version:1,url:i,method:u.WalletTransfer.method,headers:{"privy-app-id":e.app.appId,[M]:a},body:{...r}});if(Date.now()>Number(a))throw new S({error:`Wallet request expired before it could be sent. Please try again.`,code:`embedded_wallet_request_expired`});return await e.fetchPrivyRoute(u.WalletTransfer,{body:r,params:{wallet_id:n},headers:{"privy-authorization-signature":o,[M]:a}})}async function Ui(e,{wallet_id:t,action_id:n}){return await e.fetchPrivyRoute(u.WalletGetAction,{params:{wallet_id:t,action_id:n}})}async function Wi(e,{wallet_id:t,...n}){return await e.fetchPrivyRoute(u.WalletListActions,{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 Gi({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(w(t)){if(n.length===0)throw Error(`Must specify at least one signer to add.`);let r={wallet_id:t.id},i=await Bi(e,r);await Vi(e,r,Ji(e),{additional_signers:i.additional_signers.concat(n)})}else{if(t.delegated)return qi(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=Nr(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 qi(e)}async function Ki({client:e,wallet:t}){return w(t)?await Vi(e,{wallet_id:t.id},Ji(e),{additional_signers:[]}):await e.delegated.revoke(),qi(e)}async function qi(e){let{user:t}=await e.user.get();if(!t)throw Error(`Could not refresh user`);return{user:t}}function Ji(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}var Yi=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 Xi=async(e,{environment:t,acceptElectronicDisclosure:n,acceptBankTerms:r})=>{let{data:i}=await e.fetchPrivyRoute(u.AcceptCardConsents,{body:{environment:t,accept_electronic_disclosure:n,accept_bank_terms:r}});return i},Zi=async({sendTransaction:e,evmChainId:t,stablecoinAddress:n,spenderAddress:r})=>{let i={to:n,chainId:t,data:(0,h.encodeFunctionData)({abi:h.erc20Abi,functionName:`approve`,args:[r,h.maxUint256]})};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})}},Qi=({cardCreatedAt:e,environment:t,now:n=new Date})=>{let r=new Intl.DateTimeFormat(void 0,{month:`long`,year:`numeric`,timeZone:`UTC`}),i=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1),a=+(t===`production`),o=[];for(let e=0;e<24;e++){let t=Date.UTC(n.getUTCFullYear(),n.getUTCMonth()-a-e,1);if(t<i)break;let s=new Date(t),c=`${s.getUTCFullYear()}-${String(s.getUTCMonth()+1).padStart(2,`0`)}`;o.push({value:c,label:r.format(s)})}return o},$i=[{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`}]}],ea=async({sendTransaction:e,evmChainId:t,spenderAddress:n,vaultAddress:r})=>{let i={to:n,chainId:t,data:(0,h.encodeFunctionData)({abi:$i,functionName:`publicCall`,args:[(0,h.concat)([(0,h.stringToHex)(`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})}},ta=async(e,{environment:t,walletId:n,chainId:r,asset:i})=>e.fetchPrivyRoute(u.CreateCard,{body:{environment:t,wallet_id:n,chain_id:r,asset:i}}),Q=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(u.GetCardCustomer,{query:{environment:t}});return n},na=async(e,{environment:t})=>{let{data:n}=await e.fetchPrivyRoute(u.UpsertCardCustomer,{body:{environment:t}});return n},ra=async(e,{environment:t,limit:n,cursor:r})=>e.fetchPrivyRoute(u.ListCards,{query:{environment:t,...n===void 0?{}:{limit:n},...r?{cursor:r}:{}}}),ia=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:(0,h.encodeFunctionData)({abi:h.erc20Abi,functionName:`allowance`,args:[n,i]})},`latest`]});if(!(0,h.isHex)(a)||a===`0x`)throw Error(`Could not read the spend approval`);return(0,h.decodeFunctionResult)({abi:h.erc20Abi,functionName:`allowance`,data:a})},aa=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:(0,h.encodeFunctionData)({abi:$i,functionName:`publicGetCall`,args:[(0,h.concat)([(0,h.stringToHex)(`TEGP`),n])]})},`latest`]});if(!(0,h.isHex)(i)||i===`0x`)throw Error(`Could not read the card vault choice`);let[a]=(0,h.decodeAbiParameters)([{type:`address`}],(0,h.decodeFunctionResult)({abi:$i,functionName:`publicGetCall`,data:i}));return a},oa=2e3,sa=1e3,ca=new Map([[`morpho`,`Morpho`],[`aave`,`Aave`]]),la=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}},ua=e=>{try{return new URL(e).protocol===`https:`?e:null}catch{return null}},$=e=>e instanceof Error&&e.message?e.message:void 0,da=({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()=>ia({provider:await d.getProvider(),evmChainId:f,owner:d.address,stablecoinAddress:c,spenderAddress:s}),m=async()=>aa({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()!==h.zeroAddress),approve:async()=>{if(await Zi({sendTransaction:d.sendTransaction,evmChainId:f,stablecoinAddress:c,spenderAddress:s}),o.kind!==`opt_in`)return;let a=await Z({operation:p,until:e=>e>0n,delay:0,interval:sa,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!==h.zeroAddress)return;await ea({sendTransaction:d.sendTransaction,evmChainId:f,spenderAddress:s,vaultAddress:o.vaultAddress});let g=await Z({operation:m,until:e=>e.toLowerCase()===o.vaultAddress.toLowerCase(),delay:0,interval:sa,attempts:60,signal:i});if(g.status===`max_attempts`)throw Error(`The vault choice did not land in time`,{cause:g.error});g.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 ra(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 ta(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=ca.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 na(e,{environment:t})}catch(e){n.aborted||s({status:`error`,message:$(e)});return}continue;case`electronic_disclosure_required`:s({status:`disclosure-prompt`,disclosureUrl:i.disclosure_url});return;case`bank_terms_required`:s({status:`bank-terms-prompt`,bankInfo:i.bank_info});return;case`provider_terms_required`:c={kind:`provider`,url:i.tos_url},s({status:`provider-terms-prompt`});return;case`kyc_required`:c={kind:`kyc`,url:i.kyc_url},s({status:`kyc-prompt`});return;case`pending`:if(s({status:`pending`}),(await Z({operation:()=>Q(e,{environment:t}),until:e=>e.status!==`pending`,delay:0,interval:oa,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}}},g=async({page:n,url:r,until:i,signal:o})=>{let s=ua(r);if(!s)return n?.dismiss(),`blocked`;let c=n??a.openHostedPage(s);if(!c)return`blocked`;n&&n.navigate(s);let l=await Z({operation:()=>Q(e,{environment:t}),until:e=>i(e)||c.isClosed(),delay:0,interval:oa,attempts:60,signal:o});if(l.status===`aborted`)return c.dismiss(),`aborted`;if(l.status===`max_attempts`)return`stalled`;if(i(l.result))return c.dismiss(),`advanced`;let u=await Z({operation:()=>Q(e,{environment:t}),until:i,delay:0,interval:1e3,attempts:5,signal:o});return u.status===`aborted`?(c.dismiss(),`aborted`):u.status===`success`?`advanced`:`closed`},_=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=la(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)},v=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:v,start(e){s({status:`get-started`,pending:!0}),m(e)},acceptDisclosure(n){(async()=>{s({status:`accepting-disclosure`});try{await Xi(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 Xi(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 g({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 _(`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 g({url:t.url,until:n,signal:e});if(r!==`aborted`){if(r===`blocked`){s({status:`error`});return}if(r===`closed`||r===`stalled`){await _(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){v(e)}}},fa=async(e,{cardId:t,environment:n,statementPeriod:r})=>(await e.fetchPrivyRouteRaw(u.DownloadCardStatement,{params:{card_id:t,statement_period:r},query:{environment:n}})).blob(),pa=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),ma=e=>Number.isFinite(e)?pa.format(Math.abs(e)/100):``,ha=({amount:e,status:t})=>e===0?`none`:t===`posted`&&e>0?`credit`:`debit`,ga=({amount:e,status:t})=>{if(!Number.isFinite(e))return{text:``,isCredit:!1};let n=ma(e);switch(ha({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}}},_a={month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`},va=new Intl.DateTimeFormat(void 0,_a),ya=new Intl.DateTimeFormat(void 0,{..._a,year:`numeric`}),ba=({unixSeconds:e})=>{let t=new Date(e*1e3);return Number.isNaN(t.getTime())?``:(t.getFullYear()===new Date().getFullYear()?va:ya).format(t)},xa={usdc:`USDC`,pathusd:`PathUSD`,path_usd:`PathUSD`,ousd:`OUSD`},Sa=e=>e?xa[e.toLowerCase()]??e:``,Ca=async(e,{cardId:t,environment:n})=>{let{data:r}=await ra(e,{environment:n,limit:20});return r.find(e=>e.id===t)??null},wa=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.`,Ta=async(e,{cardId:t,environment:n,nonce:r})=>{let{data:i}=await e.fetchPrivyRoute(u.GetCardEphemeralKey,{params:{card_id:t},body:{environment:n,nonce:r}});return i.ephemeral_key_secret},Ea=async(e,{appId:t,environment:n})=>{let{data:r}=await e.fetchPrivyRoute(u.GetCardsConfig,{params:{app_id:t},query:{environment:n}});return{publishableKey:r.publishable_key,cardLogoUrl:r.card_logo_url??null,stripeAccount:r.stripe_account}},Da=`eip155:42431`,Oa=[`eip155:11155111`,`eip155:11155420`,`eip155:80002`,`eip155:84532`,`eip155:421614`,`eip155:43113`],ka=[`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`,`solana:devnet`],Aa={...Object.fromEntries(Oa.flatMap(e=>{let t=Jn[Number.parseInt(e.replace(`eip155:`,``))];return t?[[e,{stablecoinAddress:t,spenderAddress:`0x8cc0d9e8a157b73d1172a22f5066048bda46c0e3`}]]:[]})),[Da]:{stablecoinAddress:`0x20C0000000000000000000000000000000000000`,spenderAddress:`0x1955a82a01E8c0A31371792b3045341eB8b938e2`},...Object.fromEntries(ka.map(e=>[e,{stablecoinAddress:Yn.devnet,programId:`cardWArqhdV5jeRXXjUti7cHAa4mj41Nj3Apc6RPZH2`,merchantId:1n}]))},ja=(e,t)=>{let n=Aa[e];if(n)return t===`ousd`&&e===Da&&`spenderAddress`in n?{stablecoinAddress:`0x20c0000000000000000000006a37DA5C996874BE`,spenderAddress:`0x249E4Ce1A8fd56d7C362c108aDf409eeDCb940aB`}:n},Ma={"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":`solana:mainnet`,"solana:mainnet":`solana:mainnet`,"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":`solana:devnet`,"solana:devnet":`solana:devnet`},Na=(e,t,n)=>{let r=t??ja(e,n);if(!r)return null;let i=Ma[e];return i?`programId`in r?{...r,kind:`svm`,chain:i,merchantId:BigInt(r.merchantId)}:Pa(e,t):e.startsWith(`eip155:`)&&`spenderAddress`in r?{kind:`evm`,...r}:Pa(e,t)},Pa=(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),Fa=e=>e.status===`pending`?`pending`:e.status===`declined`?`declined`:e.status===`expired`?`expired`:e.status===`reversed`?`reversed`:ha(e)===`credit`?`credit`:null,Ia=({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`))}},La=({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},Ra=async(e,{cardId:t,environment:n,limit:r,cursor:i})=>e.fetchPrivyRoute(u.ListCardTransactions,{params:{card_id:t},query:{environment:n,...r===void 0?{}:{limit:r},...i?{cursor:i}:{}}}),za=async(e,{cardId:t,environment:n,reason:r})=>e.fetchPrivyRoute(u.ReplaceCard,{params:{card_id:t},body:{environment:n,replacement_reason:r}}),Ba=({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}),Va=async(e,{cardId:t,environment:n,encryptedNumber:r})=>e.fetchPrivyRoute(u.UpdateCardPin,{params:{card_id:t},body:{environment:n,pin:{encrypted_number:r}}}),Ha=async(e,{cardId:t,environment:n,status:r})=>e.fetchPrivyRoute(u.UpdateCard,{params:{card_id:t},body:{environment:n,status:r}});var Ua=jn;exports.ALL_WALLET_CLIENT_TYPES=Er,exports.BICONOMY=`biconomy`,exports.COINBASE_SMART_WALLET=`coinbase_smart_wallet`,exports.ConnectedStandardSolanaWallet=Yi,exports.DATA_SUFFIX_PLUGIN_ID=se,exports.EmbeddedProviderError=we,exports.InMemoryCache=Nn,exports.KERNEL=`kernel`,exports.LIGHT_ACCOUNT=`light_account`,exports.LIST_CARDS_MAX_LIMIT=20,exports.LocalStorage=Mn,exports.MoonpayApiError=de,exports.NEXUS=`nexus`,exports.PrivyApiError=x,exports.PrivyClientError=S,exports.PrivyConnectorError=Ce,exports.PrivyEmbeddedWalletErrorCode=be,exports.PrivyProviderRpcError=Ae,exports.ProviderErrors=E,exports.SAFE=`safe`,exports.SUPPORTED_CONNECTOR_TYPES=Dr,exports.SolanaClient=dr,exports.SolanaUsdcAddressMap=Yn,exports.THIRDWEB=`thirdweb`,exports.UsdcAddressMap=Jn,exports.acceptCardConsents=Xi,exports.addSessionSigners=Gi,exports.approveSpend=Zi,exports.buildRecentMonths=Qi,exports.buildSolanaOffchainMessage=yr,exports.chainToMoonpayCurrency=xn,exports.chooseTempoEarnVault=ea,exports.cookies=L,exports.countryCodesAndNumbers=Wn,exports.create=xt,exports.createCard=ta,exports.createCardSignUp=da,exports.createDataSuffixPlugin=le,exports.createErrorFormatter=pe,exports.createSiwsMessage=fr,Object.defineProperty(exports,"crossApp",{enumerable:!0,get:function(){return Yr}}),Object.defineProperty(exports,"cryptoDepositAccount",{enumerable:!0,get:function(){return Ri}}),exports.default=Ua,Object.defineProperty(exports,"delegatedActions",{enumerable:!0,get:function(){return Ir}}),Object.defineProperty(exports,"depositAddress",{enumerable:!0,get:function(){return ci}}),exports.deriveSolanaApplicationDomain=vr,exports.downloadCardStatement=fa,exports.errorIndicatesMaxMfaRetries=Oe,exports.errorIndicatesMfaCanceled=me,exports.errorIndicatesMfaRateLimit=ke,exports.errorIndicatesMfaTimeout=Ee,exports.errorIndicatesMfaVerificationFailed=De,exports.errorIndicatesRecoveryIsNeeded=Te,exports.formatLamportsAmount=jr,exports.formatPhoneNumber=Vn,exports.formatSignedTransactionAmount=ga,exports.formatTokenAmount=Ar,exports.formatTransactionDate=ba,exports.formatUsdAmount=ma,exports.formatWalletAddress=Or,exports.formatWeiAmount=kr,exports.fundingMethodToMoonpayPaymentMethod=Sn,exports.generateAuthorizationSignature=j,exports.generateWalletIdempotencyKey=Zn,exports.getAllUserEmbeddedBitcoinWallets=Pn,exports.getAllUserEmbeddedEthereumWallets=Ht,exports.getAllUserEmbeddedSolanaWallets=Wt,exports.getCardAssetDisplayName=Sa,exports.getCardById=Ca,exports.getCardCustomer=Q,exports.getCardDisclosure=wa,exports.getCardEphemeralKey=Ta,exports.getCardsConfig=Ea,exports.getCoinbaseOnRampUrl=ir,exports.getCountryCallingCode=b.getCountryCallingCode,exports.getDataSuffixPlugin=ce,exports.getEntropyDetailsFromAccount=Ln,exports.getEntropyDetailsFromUser=In,exports.getFiatOnrampProviderBrand=ur,exports.getFiatOnrampProviderId=cr,exports.getIsTokenUsdc=Xn,exports.getJsonRpcEndpointFromChain=$e,exports.getOrCreateCardCustomer=na,exports.getPhoneCountryCodeAndNumber=Kn,exports.getPlaceholderPhoneNumber=Gn,exports.getSolanaClusterDisplayName=hr,exports.getSolanaRpcEndpointForCluster=pr,exports.getSolanaUsdcMintAddressForCluster=mr,exports.getSpendApproval=Na,exports.getTransactionBadge=Fa,exports.getUserEmbeddedEthereumWallet=q,exports.getUserEmbeddedSolanaWallet=Gt,exports.getUserEmbeddedWallet=Ut,exports.getUserSmartWallet=Rn,exports.getWallet=Bi,exports.getWalletAction=Ui,exports.handleSignUpClose=Ia,exports.isCardExpired=La,exports.isEmbeddedWalletAccount=Vt,exports.isExtensionContext=Et,exports.isSupportedChainIdForCoinbaseOnramp=ar,exports.isSupportedChainIdForMoonpay=bn,exports.isUnifiedWallet=w,exports.lastFourDigits=Hn,exports.listCardTransactions=Ra,exports.listCards=ra,exports.listWalletActions=Wi,exports.parseSolanaOffchainMessage=br,exports.phoneNumberTypingFormatter=Un,exports.poll=Z,exports.rawSign=zi,exports.readSpendAllowance=ia,exports.readTempoEarnVault=aa,exports.removeSessionSigners=Ki,exports.replaceCard=za,exports.rpc=P,exports.shouldWriteSessionCookies=Dt,exports.throwIfInvalidRecoveryUpgradePath=et,exports.toCoinbaseAssetId=sr,exports.toCoinbaseBlockchainFromChainId=or,exports.toE164=Bn,exports.toObjectKeys=qn,exports.toTransactionRow=Ba,exports.toWalletApiUnsignedEthTransaction=it,exports.transfer=Hi,exports.updateCardPin=Va,exports.updateCardStatus=Ha,exports.updateWallet=Vi,exports.validatePhoneNumber=zn,Object.keys(f).forEach(function(e){e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return f[e]}})});
|
|
35
35
|
//# sourceMappingURL=index.js.map
|