@privy-io/js-sdk-core 0.26.2 → 0.26.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PrivyInternal.js +1 -1
- package/dist/index.cjs.js +1 -1
- package/package.json +2 -2
package/dist/PrivyInternal.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"fetch-retry";import{v4 as e}from"uuid";import{PrivyErrorCode as s}from"@privy-io/api-base";import{getPathWithParams as i,AppConfig as n,AnalyticsEvent as a,RefreshSession as o}from"@privy-io/public-api";import{PrivyApiError as r}from"./Error.js";import{Session as h}from"./Session.js";import c from"./toAbortSignalTimeout.js";import"eventemitter3";import"js-cookie";import"./Token.js";import"jose";const l="privy:caid";class d{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.26.
|
|
1
|
+
import t from"fetch-retry";import{v4 as e}from"uuid";import{PrivyErrorCode as s}from"@privy-io/api-base";import{getPathWithParams as i,AppConfig as n,AnalyticsEvent as a,RefreshSession as o}from"@privy-io/public-api";import{PrivyApiError as r}from"./Error.js";import{Session as h}from"./Session.js";import c from"./toAbortSignalTimeout.js";import"eventemitter3";import"js-cookie";import"./Token.js";import"jose";const l="privy:caid";class d{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.26.3";_fetch;nativeAppIdentifier;callbacks;_cache=new Map;session;constructor(e){this._storage=e.storage,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,"undefined"==typeof document&&(this.nativeAppIdentifier=e.nativeAppIdentifier),this.session=new h({storage:this._storage,isUsingServerCookies:!1}),this._fetch=t(fetch,{retries:3,retryDelay:500})}get isReady(){return Boolean(this._config)}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){this.isReady||(this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.callbacks?.setIsReady?.(!0),this.createAnalyticsEvent("sdk_initialize",{}))}async fetch(t,{body:e,params:s,headers:n,options:a={onRequest:this._beforeRequest.bind(this)}}){const o=`${this.baseUrl}${i(t.path,s)}`,h=new Request(o,{method:t.method,body:JSON.stringify(e),headers:n}),c=await a.onRequest(h),l=await this._fetch(h,c),d=await l.json();if(l.status>299)throw new r(d);return d}async _beforeRequestWithoutInitialize(t){const e=await this.session.getToken(),s=new Headers(t.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),s.set("Authorization",`Bearer ${e}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");const i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:c(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(t){return await this._initialize(),this._beforeRequestWithoutInitialize(t)}async _beforeRequest(t){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(t)}async getAppConfig(){return await this.fetch(n,{params:{app_id:this.appId},options:{onRequest:this._beforeRequestWithoutInitialize.bind(this)}})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{const t=await this._storage.get(l);if("string"==typeof t&&t.length>0)return this._analyticsId=t,t}catch(t){console.error("Unable to load clientId",t)}try{this._analyticsId=e()}catch(t){console.error("Unable to generate uuidv4",t)}if(!this._analyticsId)return null;try{await this._storage.put(l,this._analyticsId)}catch(t){console.error(`Unable to store clientId: ${this._analyticsId}`,t)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(l)}catch(t){console.error("Unable to delete clientId",t)}}async createAnalyticsEvent(t,e){try{await this.fetch(a,{body:{event_name:t,client_id:await this._getOrGenerateClientAnalyticsId(),payload:e},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}catch(t){}}async refreshSession(){const t=await this.session.getRefreshToken()??void 0,e=t??"key",s=this._cache.get(e);if(s)return await s;const i=this._refreshSession(t);this._cache.set(e,i);try{return await i}catch(t){throw t}finally{this._cache.delete(e)}}async _refreshSession(t){const e=await this.session.getToken();if(!this.session.hasRefreshCredentials(e,t??null))throw await this._initialize(),new Error("missing_or_invalid_token");try{const{session_update_action:e,...s}=await this.fetch(o,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}});return this.callbacks?.setUser?.(s.user),"set"===e&&await Promise.all([this.session.storeToken(s.token),this.session.storeRefreshToken(s.refresh_token),this.session.storeIdentityToken(s.identity_token)]),"clear"===e&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===e&&s.token&&(await this.session.storeToken(s.token),s.identity_token&&await this.session.storeIdentityToken(s.identity_token)),s}catch(t){throw(t instanceof r&&t.code===s.MISSING_OR_INVALID_TOKEN||t instanceof Error&&"missing_or_invalid_token"===t.message)&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),t}}async getAccessToken(){const[t,e]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(t)&&this.session.hasRefreshCredentials(t,e))try{return await this.refreshSession(),await this.session.getToken()}catch(t){return null}return t}async getIdentityToken(){return await this.session.getIdentityToken()}}export{d as PrivyInternal};
|
|
2
2
|
//# sourceMappingURL=PrivyInternal.js.map
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@privy-io/public-api"),t=require("jose"),r=require("eventemitter3"),s=require("@ethersproject/abstract-signer"),a=require("@ethersproject/providers"),i=require("@ethersproject/bignumber"),n=require("@ethersproject/contracts"),o=require("@ethersproject/transactions"),c=require("@ethersproject/units"),l=require("fetch-retry"),d=require("uuid"),h=require("@privy-io/api-base"),p=require("js-cookie");function y(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var m=u(t),_=y(r),v=y(l),w=y(p);class g{_privyInternal;constructor(e){this._privyInternal=e}async syncWithToken(t){const r=await this._privyInternal.fetch(e.CustomJWTAuthenticate,{body:{token:t}});return await Promise.all([this._privyInternal.session.storeToken(r.token),this._privyInternal.session.storeRefreshToken(r.refresh_token),this._privyInternal.session.storeIdentityToken(r.identity_token)]),this._privyInternal.callbacks?.setUser?.(r.user),r}}class f{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(t,r){return this._privyInternal.fetch(e.PasswordlessInit,{body:{email:t,token:r}})}async loginWithCode(t,r){const s=await this._privyInternal.fetch(e.PasswordlessAuthenticate,{body:{email:t,code:r}});return await Promise.all([this._privyInternal.session.storeToken(s.token),this._privyInternal.session.storeRefreshToken(s.refresh_token),this._privyInternal.session.storeIdentityToken(s.identity_token)]),this._privyInternal.callbacks?.setUser?.(s.user),s}async linkWithCode(t,r){await this._privyInternal.fetch(e.PasswordlessLink,{body:{email:t,code:r}});return(await this._privyInternal.refreshSession()).user}async unlink(t){await this._privyInternal.fetch(e.PasswordlessUnlink,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}}class b{_privyInternal;constructor(e){this._privyInternal=e}async initializeAuth({relyingParty:t,redirectUrl:r,token:s}){return await this._privyInternal.fetch(e.FarcasterInit,{body:{relying_party:t,redirect_url:r,token:s}})}async getFarcasterStatus({channel_token:t}){return await this._privyInternal.fetch(e.FarcasterStatus,{headers:{"farcaster-channel-token":t}})}async authenticate({channel_token:t,message:r,signature:s,fid:a}){const i=await this._privyInternal.fetch(e.FarcasterAuthenticate,{body:{channel_token:t,message:r,signature:s,fid:a}});return await Promise.all([this._privyInternal.session.storeToken(i.token),this._privyInternal.session.storeRefreshToken(i.refresh_token),this._privyInternal.session.storeIdentityToken(i.identity_token)]),this._privyInternal.callbacks?.setUser?.(i.user),i}async link({channel_token:t,message:r,signature:s,fid:a}){await this._privyInternal.fetch(e.FarcasterLink,{body:{channel_token:t,message:r,signature:s,fid:a}});return(await this._privyInternal.refreshSession()).user}async unlink({fid:t}){await this._privyInternal.fetch(e.FarcasterUnlink,{body:{fid:t}});return(await this._privyInternal.refreshSession()).user}}class k extends Error{error;code;constructor({error:e,code:t}){super(e),this.error=e,this.code=t}}class I extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}}const E="privy:state_code",x="privy:code_verifier";function P(){return t.base64url.encode((e=36,crypto.getRandomValues(new Uint8Array(e))));var e}function T(){return P()}async function S({codeVerifier:e,method:r="S256",digest:s=crypto.subtle.digest.bind(crypto.subtle)}){if("S256"==r){const r=await async function(e,t){const r=(new TextEncoder).encode(e),s=await t("SHA-256",r);return new Uint8Array(s)}(e,s);return t.base64url.encode(r)}return e}class C{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t,r){const s=P(),a=T(),i=await S({codeVerifier:s,digest:this._crypto?.digest});return await Promise.all([this._storage.put(x,s),this._storage.put(E,a)]),this._privyInternal.fetch(e.OAuthInit,{body:{redirect_to:r,provider:t,code_challenge:i,state_code:a}})}async loginWithCode(t,r,s,a){const[i,n]=await Promise.all([this._storage.get(x),this._storage.get(E)]);if(n!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:n??"",returnedStateCode:r??""}),new I({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});const o=await this._privyInternal.fetch(e.OAuthAuthenticate,{body:{authorization_code:t,code_type:a,state_code:n,code_verifier:i}});return await Promise.all([this._privyInternal.session.storeToken(o.token),this._privyInternal.session.storeRefreshToken(o.refresh_token),this._privyInternal.session.storeIdentityToken(o.identity_token)]),this._privyInternal.callbacks?.setUser?.(o.user),await Promise.all([this._storage.del(x),this._storage.del(E)]),o}async linkWithCode(t,r,s,a){const[i,n]=await Promise.all([this._storage.get(x),this._storage.get(E)]);if(n!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:n??"",returnedStateCode:r??""}),new I({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});await this._privyInternal.fetch(e.OAuthLink,{body:{authorization_code:t,code_type:a,state_code:n,code_verifier:i}});const o=await this._privyInternal.refreshSession();return await Promise.all([this._storage.del(x),this._storage.del(E)]),o.user}async unlink(t,r){await this._privyInternal.fetch(e.OAuthUnlink,{body:{provider:t,subject:r}});return(await this._privyInternal.refreshSession()).user}}class R{_privyInternal;constructor(e){this._privyInternal=e}async generateRegistrationOptions(t){return await this._privyInternal.fetch(e.PasskeyLinkInit,{body:{relying_party:t}})}async generateAuthenticationOptions(t){return await this._privyInternal.fetch(e.PasskeyAuthenticateInit,{body:{relying_party:t}})}async loginWithPasskey(t,r,s){const a=await this._privyInternal.fetch(e.PasskeyAuthenticate,{body:{relying_party:s,challenge:r,authenticator_response:{type:t.type,id:t.id,raw_id:t.rawId,response:{signature:t.response.signature,client_data_json:t.response.clientDataJSON,authenticator_data:t.response.authenticatorData,user_handle:t.response.userHandle||void 0},authenticator_attachment:t.authenticatorAttachment||void 0,client_extension_results:{app_id:t.clientExtensionResults.appid||void 0,cred_props:t.clientExtensionResults.credProps||void 0,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret||void 0}}}});return await Promise.all([this._privyInternal.session.storeToken(a.token),this._privyInternal.session.storeRefreshToken(a.refresh_token),this._privyInternal.session.storeIdentityToken(a.identity_token)]),this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithPasskey(t,r){await this._privyInternal.fetch(e.PasskeyLink,{body:{relying_party:r,authenticator_response:{type:t.type,id:t.id,raw_id:t.rawId,response:{client_data_json:t.response.clientDataJSON,attestation_object:t.response.attestationObject,authenticator_data:t.response.authenticatorData||void 0,transports:t.response.transports||void 0,public_key:t.response.publicKey||void 0,public_key_algorithm:t.response.publicKeyAlgorithm||void 0},authenticator_attachment:t.authenticatorAttachment||void 0,client_extension_results:{app_id:t.clientExtensionResults.appid||void 0,cred_props:t.clientExtensionResults.credProps||void 0,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret||void 0}}}});return(await this._privyInternal.refreshSession()).user}}class A{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(t,r){return this._privyInternal.fetch(e.PasswordlessSmsInit,{body:{phoneNumber:t,token:r}})}async loginWithCode(t,r){const s=await this._privyInternal.fetch(e.PasswordlessSmsAuthenticate,{body:{phoneNumber:t,code:r}});return await Promise.all([this._privyInternal.session.storeToken(s.token),this._privyInternal.session.storeRefreshToken(s.refresh_token),this._privyInternal.session.storeIdentityToken(s.identity_token)]),this._privyInternal.callbacks?.setUser?.(s.user),s}async linkWithCode(t,r){await this._privyInternal.fetch(e.PasswordlessSmsLink,{body:{phoneNumber:t,code:r}});return(await this._privyInternal.refreshSession()).user}async unlink(t){await this._privyInternal.fetch(e.PasswordlessSmsUnlink,{body:{phoneNumber:t}});return(await this._privyInternal.refreshSession()).user}}class U{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async linkWithSiwe(t,r,s){const a=r||this._wallet,i=s||this._preparedMessage;if(!a)throw new Error("A wallet must be provided in the init step or as an argument to linkWithSiwe");if(!i)throw new Error("A message must be generated and signed before being used to link a wallet to privy");try{await this._privyInternal.fetch(e.SiweLink,{body:{message:i,signature:t,chainId:a.chainId,walletClientType:a.walletClientType,connectorType:a.connectorType}});return(await this._privyInternal.refreshSession()).user}catch(e){throw e}}async loginWithSiwe(t,r,s){const a=r||this._wallet,i=s||this._preparedMessage;if(!a)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!i)throw new Error("A message must be generated and signed before being used to login to privy with a wallet");try{const r=await this._privyInternal.fetch(e.SiweAuthenticate,{body:{signature:t,message:i,chainId:a.chainId,walletClientType:a.walletClientType,connectorType:a.connectorType}});return await Promise.all([this._privyInternal.session.storeToken(r.token),this._privyInternal.session.storeRefreshToken(r.refresh_token),this._privyInternal.session.storeIdentityToken(r.identity_token)]),this._privyInternal.callbacks?.setUser?.(r.user),r}catch(e){throw e}}async init(t,r,s){this._wallet=t;const a=await this._privyInternal.fetch(e.SiweInit,{body:{address:t.address}}),{nonce:i}=a,n=`${(o={chainId:t.chainId.toString().replace("eip155:",""),address:t.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:r,nonce:i,uri:s}).domain} wants you to sign in with your Ethereum account:\n${o.address}\n\n${o.statement}\n\nURI: ${o.uri}\nVersion: 1\nChain ID: ${o.chainId}\nNonce: ${o.nonce}\nIssued At: ${o.issuedAt}\nResources:\n- https://privy.io`;var o;return this._preparedMessage=n,{nonce:i,message:n}}}class F{_privyInternal;customProvider;phone;email;oauth;siwe;passkey;farcaster;constructor(e,t,r){this._privyInternal=e,this.customProvider=new g(this._privyInternal),this.phone=new A(this._privyInternal),this.email=new f(this._privyInternal),this.oauth=new C(this._privyInternal,t,r),this.siwe=new U(this._privyInternal),this.passkey=new R(this._privyInternal),this.farcaster=new b(this._privyInternal)}async logout(){try{const t=await this._privyInternal.session.getRefreshToken()??void 0;await this._privyInternal.fetch(e.Logout,{body:{refresh_token:t}})}catch(e){console.warn("Error destroying session")}await Promise.all([this._privyInternal.session.destroyLocalState({reason:"logout"}),this._privyInternal.destroyClientAnalyticsId()]),this._privyInternal.callbacks?.setUser?.(null)}}const O={id:42161,name:"Arbitrum One",network:"arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-mainnet.rpc.privy.systems"]},alchemy:{http:["https://arb-mainnet.g.alchemy.com/v2"],webSocket:["wss://arb-mainnet.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-mainnet.infura.io/v3"],webSocket:["wss://arbitrum-mainnet.infura.io/ws/v3"]},default:{http:["https://arb1.arbitrum.io/rpc"]},public:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://arbiscan.io"},default:{name:"Arbiscan",url:"https://arbiscan.io"}}},N={id:421613,name:"Arbitrum Goerli",network:"arbitrum-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"AGOR",decimals:18},rpcUrls:{default:{http:["https://goerli-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"}},testnet:!0},L={id:421614,name:"Arbitrum Sepolia",network:"arbitrum-sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]},public:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Blockscout",url:"https://sepolia-explorer.arbitrum.io"}},testnet:!0},G={id:43114,name:"Avalanche",network:"avalanche",nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]},public:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://snowtrace.io"},default:{name:"SnowTrace",url:"https://snowtrace.io"}}},D={id:43113,name:"Avalanche Fuji",network:"avalanche-fuji",nativeCurrency:{decimals:18,name:"Avalanche Fuji",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax-test.network/ext/bc/C/rpc"]},public:{http:["https://api.avax-test.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://testnet.snowtrace.io"},default:{name:"SnowTrace",url:"https://testnet.snowtrace.io"}},testnet:!0},M={id:8453,network:"base",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-mainnet.rpc.privy.systems"]},blast:{http:["https://base-mainnet.blastapi.io"],webSocket:["wss://base-mainnet.blastapi.io"]},default:{http:["https://mainnet.base.org"]},public:{http:["https://mainnet.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://basescan.org"},default:{name:"Basescan",url:"https://basescan.org"}},testnet:!0},q={id:84531,network:"base-goerli",name:"Base Goerli Testnet",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://goerli.basescan.org"}},testnet:!0},j={id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.base.org"]},public:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Blockscout",url:"https://base-sepolia.blockscout.com"}},testnet:!0},W={id:42220,name:"Celo Mainnet",network:"celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]},infura:{http:["https://celo-mainnet.infura.io/v3"]},public:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/mainnet"},etherscan:{name:"CeloScan",url:"https://celoscan.io"}},testnet:!1},z={id:44787,name:"Celo Alfajores Testnet",network:"celo-alfajores",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://alfajores-forno.celo-testnet.org"]},infura:{http:["https://celo-alfajores.infura.io/v3"]},public:{http:["https://alfajores-forno.celo-testnet.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/alfajores"},etherscan:{name:"CeloScan",url:"https://alfajores.celoscan.io/"}},testnet:!0},H={id:314,name:"Filecoin - Mainnet",network:"filecoin-mainnet",nativeCurrency:{decimals:18,name:"filecoin",symbol:"FIL"},rpcUrls:{default:{http:["https://api.node.glif.io/rpc/v1"]},public:{http:["https://api.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filfox",url:"https://filfox.info/en"},filscan:{name:"Filscan",url:"https://filscan.io"},filscout:{name:"Filscout",url:"https://filscout.io/en"},glif:{name:"Glif",url:"https://explorer.glif.io"}}},$={id:314159,name:"Filecoin - Calibration testnet",network:"filecoin-calibration",nativeCurrency:{decimals:18,name:"testnet filecoin",symbol:"tFIL"},rpcUrls:{default:{http:["https://api.calibration.node.glif.io/rpc/v1"]},public:{http:["https://api.calibration.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filscan",url:"https://calibration.filscan.io"}}},B={id:17069,name:"Garnet Holesky",network:"garnet-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.garnetchain.com"]},public:{http:["https://rpc.garnetchain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.garnetchain.com"}}},J={id:5,network:"goerli",name:"Goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.ankr.com/eth_goerli"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.etherscan.io"}},testnet:!0},K={id:17e3,name:"Holesky",network:"holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-holesky.publicnode.com"]},public:{http:["https://ethereum-holesky.publicnode.com"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://holesky.etherscan.io"},default:{name:"EtherScan",url:"https://holesky.etherscan.io"}}},V={id:59144,network:"linea-mainnet",name:"Linea Mainnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]},public:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://lineascan.build"},etherscan:{name:"Etherscan",url:"https://lineascan.build"}},testnet:!1},Y={id:59140,network:"linea-testnet",name:"Linea Goerli Testnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-goerli.infura.io/v3"],webSocket:["wss://linea-goerli.infura.io/ws/v3"]},default:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]},public:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.lineascan.build"},etherscan:{name:"Etherscan",url:"https://goerli.lineascan.build"}},testnet:!0},Q={id:1,network:"homestead",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://mainnet.rpc.privy.systems"]},alchemy:{http:["https://eth-mainnet.g.alchemy.com/v2"],webSocket:["wss://eth-mainnet.g.alchemy.com/v2"]},infura:{http:["https://mainnet.infura.io/v3"],webSocket:["wss://mainnet.infura.io/ws/v3"]},default:{http:["https://cloudflare-eth.com"]},public:{http:["https://cloudflare-eth.com"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://etherscan.io"},default:{name:"Etherscan",url:"https://etherscan.io"}}},Z={id:10,name:"OP Mainnet",network:"optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-mainnet.rpc.privy.systems"]},alchemy:{http:["https://opt-mainnet.g.alchemy.com/v2"],webSocket:["wss://opt-mainnet.g.alchemy.com/v2"]},infura:{http:["https://optimism-mainnet.infura.io/v3"],webSocket:["wss://optimism-mainnet.infura.io/ws/v3"]},default:{http:["https://mainnet.optimism.io"]},public:{http:["https://mainnet.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://optimistic.etherscan.io"},default:{name:"Optimism Explorer",url:"https://explorer.optimism.io"}}},X={id:420,name:"Optimism Goerli Testnet",network:"optimism-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.optimism.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"}},testnet:!0},ee={id:11155420,name:"Optimism Sepolia",network:"optimism-sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.optimism.io"]},public:{http:["https://sepolia.optimism.io"]},infura:{http:["https://optimism-sepolia.infura.io/v3"]}},blockExplorers:{default:{name:"Blockscout",url:"https://optimism-sepolia.blockscout.com"}},testnet:!0},te={id:137,name:"Polygon Mainnet",network:"matic",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{privy:{http:["https://polygon-mainnet.rpc.privy.systems"]},alchemy:{http:["https://polygon-mainnet.g.alchemy.com/v2"],webSocket:["wss://polygon-mainnet.g.alchemy.com/v2"]},infura:{http:["https://polygon-mainnet.infura.io/v3"],webSocket:["wss://polygon-mainnet.infura.io/ws/v3"]},default:{http:["https://polygon-rpc.com"]},public:{http:["https://polygon-rpc.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://polygonscan.com"},default:{name:"PolygonScan",url:"https://polygonscan.com"}}},re={id:80001,name:"Mumbai",network:"maticmum",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{default:{http:["https://matic-mumbai.chainstacklabs.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"}},testnet:!0},se={id:690,name:"Redstone",network:"redstone",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.redstonechain.com"]},public:{http:["https://rpc.redstonechain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.redstone.xyz/"}}},ae={id:17001,name:"Redstone Holesky",network:"redstone-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.holesky.redstone.xyz"]},public:{http:["https://rpc.holesky.redstone.xyz"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"},default:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"}}},ie={id:11155111,network:"sepolia",name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"SEP",decimals:18},rpcUrls:{privy:{http:["https://sepolia.rpc.privy.systems"]},alchemy:{http:["https://eth-sepolia.g.alchemy.com/v2"],webSocket:["wss://eth-sepolia.g.alchemy.com/v2"]},infura:{http:["https://sepolia.infura.io/v3"],webSocket:["wss://sepolia.infura.io/ws/v3"]},default:{http:["https://rpc.sepolia.org"]},public:{http:["https://rpc.sepolia.org"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://sepolia.etherscan.io"},default:{name:"Etherscan",url:"https://sepolia.etherscan.io"}},testnet:!0},ne={id:7777777,name:"Zora",network:"zora",nativeCurrency:{decimals:18,name:"Ether",symbol:"ETH"},rpcUrls:{default:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]},public:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://explorer.zora.energy"}}},oe={id:999999999,name:"Zora Sepolia",network:"zora-sepolia",nativeCurrency:{decimals:18,name:"Zora Sepolia",symbol:"ETH"},rpcUrls:{default:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]},public:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]}},blockExplorers:{default:{name:"Zora Sepolia Explorer",url:"https://sepolia.explorer.zora.energy/"}},testnet:!0},ce={id:999,name:"Zora Goerli Testnet",network:"zora-testnet",nativeCurrency:{decimals:18,name:"Zora Goerli",symbol:"ETH"},rpcUrls:{default:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]},public:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://testnet.explorer.zora.energy"}},testnet:!0},le={mainnet:Q,goerli:J,sepolia:ie,arbitrum:O,arbitrumGoerli:N,arbitrumSepolia:L,optimism:Z,optimismGoerli:X,optimismSepolia:ee,polygon:te,polygonMumbai:re,celo:W,celoAlfajores:z,filecoin:H,filecoinCalibration:$,base:M,baseGoerli:q,baseSepolia:j,linea:V,lineaTestnet:Y,avalanche:G,avalancheFuji:D,holesky:K,redstone:se,garnetHolesky:B,redstoneHolesky:ae,zora:ne,zoraSepolia:oe,zoraTestnet:ce},de=[Q,J,ie,O,N,L,Z,X,ee,te,re,W,z,H,$,M,q,j,{id:80085,network:"berachain-artio",name:"Berachain Artio",nativeCurrency:{name:"BERA",symbol:"BERA",decimals:18},rpcUrls:{default:{http:["https://berachain-artio.rpc.privy.systems"]},public:{http:["https://berachain-artio.rpc.privy.systems"]}},blockExplorers:{default:{name:"Beratrail",url:"https://artio.beratrail.io"}},testnet:!0},V,Y,G,D,K,se,B,ae,ne,oe,ce],he=new Set(de.map((e=>e.id))),pe=["error","invalid_request_arguments","wallet_not_on_device","invalid_recovery_pin","insufficient_funds"];var ye;exports.PrivyEmbeddedWalletErrorCode=void 0,(ye=exports.PrivyEmbeddedWalletErrorCode||(exports.PrivyEmbeddedWalletErrorCode={})).MISSING_OR_INVALID_PRIVY_APP_ID="missing_or_invalid_privy_app_id",ye.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID="missing_or_invalid_privy_account_id",ye.INVALID_DATA="invalid_data",ye.LINKED_TO_ANOTHER_USER="linked_to_another_user",ye.ALLOWLIST_REJECTED="allowlist_rejected",ye.OAUTH_USER_DENIED="oauth_user_denied",ye.UNKNOWN_AUTH_ERROR="unknown_auth_error",ye.USER_EXITED_AUTH_FLOW="exited_auth_flow",ye.MUST_BE_AUTHENTICATED="must_be_authenticated",ye.UNKNOWN_CONNECT_WALLET_ERROR="unknown_connect_wallet_error",ye.GENERIC_CONNECT_WALLET_ERROR="generic_connect_wallet_error",ye.CLIENT_REQUEST_TIMEOUT="client_request_timeout",ye.INVALID_CREDENTIALS="invalid_credentials";class ue extends Error{cause;privyErrorCode;constructor(e,t,r){super(e),t instanceof Error&&(this.cause=t),this.privyErrorCode=r}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}}class me extends ue{type="provider_error";code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}class _e extends Error{type;constructor(e,t){super(t),this.type=e}}class ve extends ue{type="connector_error";constructor(e,t,r){super(e,t,r)}}class we extends Error{code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}const ge={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:"Don’t see your wallet? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}};function fe(e){return function(e){const t=e.type;return"string"==typeof t&&pe.includes(t)}(e)&&"wallet_not_on_device"===e.type}class be extends me{details;constructor(e){const t=e;super(t.message,t.code,t.data);const r=Object.values(ge).find((e=>e.eipCode===t.code));this.details=r||ge.UNKNOWN_ERROR,-32002===t.code&&(t.message?.includes("already pending for origin")?t.message?.includes("wallet_requestPermissions")?this.details=ge.E32002_CONNECTION_ALREADY_PENDING:this.details=ge.E32002_REQUEST_ALREADY_PENDING:t.message?.includes("Already processing")&&t.message.includes("eth_requestAccounts")&&(this.details=ge.E32002_WALLET_LOCKED))}}const ke=["eth_sign","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation"],Ie=e=>i.BigNumber.from(e);function Ee(e){if("number"==typeof e||"bigint"==typeof e||"string"==typeof e)return e;if("function"==typeof e.toHexString)return e.toHexString();throw new Error(`Expected numeric value but received ${e}`)}function xe(e){const t={};return void 0!==e.to&&(t.to=e.to),void 0!==e.data&&(t.data=e.data),void 0!==e.chainId&&(t.chainId=e.chainId),void 0!==e.type&&(t.type=e.type),void 0!==e.accessList&&(t.accessList=e.accessList),void 0!==e.nonce&&(t.nonce=Ie(e.nonce).toNumber()),void 0!==e.gasLimit&&(t.gasLimit=Ie(e.gasLimit)),void 0!==e.gasPrice&&(t.gasPrice=Ie(e.gasPrice)),void 0!==e.value&&(t.value=Ie(e.value)),void 0!==e.maxFeePerGas&&(t.maxFeePerGas=Ie(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=Ie(e.maxPriorityFeePerGas)),t}const Pe=e=>[O.id,N.id,L.id].includes(e),Te=e=>[56,97].includes(e),Se=81457,Ce=168587773,Re="0x420000000000000000000000000000000000000F",Ae=["function getL1Fee(bytes memory _data) external view returns (uint256)"],Ue=e=>[M.id,q.id,j.id,Z.id,X.id,ee.id,ne.id,ce.id,oe.id,Se,Ce].includes(e);const Fe={id:80002,name:"Polygon Amoy",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{privy:{http:["https://polygon-amoy.rpc.privy.systems"]},infura:{http:["https://polygon-amoy.infura.io/v3"],webSocket:["wss://polygon-amoy.infura.io/ws/v3"]},default:{http:["https://rpc-amoy.polygon.technology"]}},blockExplorers:{default:{name:"OK LINK",url:"https://www.oklink.com/amoy"}},testnet:!0},Oe=v.default(fetch,{retries:3,retryDelay:500}),Ne=e=>[te.id,re.id,Fe.id].includes(e),Le=e=>({maxPriorityFee:c.parseUnits(e.maxPriorityFee.toFixed(9),"gwei").toHexString(),maxFee:c.parseUnits(e.maxFee.toFixed(9),"gwei").toHexString()}),Ge=async e=>{let t="";switch(e){case te.id:t="https://gasstation.polygon.technology/v2";break;case re.id:t="https://gasstation-testnet.polygon.technology/v2";break;case Fe.id:t="https://gasstation.polygon.technology/amoy";break;default:throw Error(`chainId ${e} does not support polygon gas stations`)}const r=await Oe(t),s=await r.json();if(r.status>399)throw s;return{safeLow:Le((a=s).safeLow),standard:Le(a.standard),fast:Le(a.fast)};var a};async function De(e,t){try{return(await t.estimateGas(e)).toHexString()}catch(r){let s;if("message"in r&&r.message.includes("insufficient funds")&&(console.warn(`Gas estimation failed with error: ${r}. Retrying gas estimation by omitting the 'value'`),s=await async function({txRequest:e,provider:t}){try{const r={...e,value:void 0};return(await t.estimateGas(r)).toHexString()}catch(e){return console.warn(`Gas estimation failed with error: ${e} when omitting the 'value'`),null}}({txRequest:e,provider:t})),s||(console.warn(`Gas estimation failed with error: ${r}. Retrying gas estimation by omitting the 'from'`),s=await async function({txRequest:e,provider:t}){try{const r={...e,from:void 0};return(await t.estimateGas(r)).toHexString()}catch(e){return console.warn(`Gas estimation failed with error: ${e} when omitting the 'from' address`),null}}({txRequest:e,provider:t})),!s)throw r;return s}}const Me=(e,t,r,s)=>{const i=Number(e),n=t.find((e=>e.id===i));if(!n)throw new ve(`Unsupported chainId ${e}`,4901);let o;if(o=n.rpcUrls.privyWalletOverride&&n.rpcUrls.privyWalletOverride.http[0]?new a.StaticJsonRpcProvider(n.rpcUrls.privyWalletOverride.http[0]):r.rpcUrls&&r.rpcUrls[i]?new a.StaticJsonRpcProvider(r.rpcUrls[i]):n.rpcUrls.privy?.http[0]?new a.StaticJsonRpcProvider({url:n.rpcUrls.privy.http[0],headers:{"privy-app-id":s.appId}}):n.rpcUrls.public?.http[0]?new a.StaticJsonRpcProvider(n.rpcUrls.public?.http[0]):new a.StaticJsonRpcProvider(n.rpcUrls.default?.http[0]),!o)throw new ve(`No RPC url found for ${e}`);return o};function qe(e){return/^-?0x[a-f0-9]+$/i.test(e)}function je(e){const t="number"==typeof e,r="bigint"==typeof e,s="string"==typeof e&&qe(e);return t||r||s}async function We(e,t,r){if(t.chainId=Number(t.chainId),function(e){const t=["gasLimit","gasPrice","value","maxPriorityFeePerGas","maxFeePerGas"];for(const r of t){const t=e[r];if(void 0!==t&&!je(t))throw new Error(`Transaction request property '${r}' must be a valid number, bigint, or hex string representing a quantity`)}if("number"!=typeof e.chainId)throw new Error("Transaction request property 'chainId' must be a number")}(t),t.from||(t.from=e),!t.nonce){const a=new s.VoidSigner(e,r);t.nonce=await a.getTransactionCount("pending")}return t.gasLimit||(t.gas?(t.gasLimit=t.gas,delete t.gas):t.gasLimit=await De(t,r)),"string"==typeof t.type&&qe(t.type)&&(t.type=Number(t.type)),[23294,23295].includes(t.chainId)&&(t.type=0),t=Ne(t.chainId)?await async function(e){if(!Ne(e.chainId))throw new Error("Invalid chain ID for Polygon gas estimation.");if(void 0===e.type&&(e.type=2),e.maxPriorityFeePerGas&&e.maxFeePerGas)return e;try{const{standard:t}=await Ge(e.chainId);e.maxPriorityFeePerGas||(e.maxPriorityFeePerGas=t.maxPriorityFee),e.maxFeePerGas||(e.maxFeePerGas=t.maxFee),e.gasPrice&&(console.warn("`gasPrice` is not supported on this chain and will be ignored. Use `maxPriorityFeePerGas` and/or `maxFeePerGas` instead."),delete e.gasPrice)}catch(e){throw new Error(`Failed to set gas prices from Polygon gas station with error: ${e}.`)}return e}(t):Pe(t.chainId)?await(async(e,t)=>{if(!Pe(e.chainId))throw new Error("Invalid chain ID for Arbitrum gas estimation.");if(void 0===e.type&&(e.type=2),e.maxFeePerGas)return e;try{const{lastBaseFeePerGas:r}=await t.getFeeData();if(r){const t=r.mul(i.BigNumber.from(120)).div(i.BigNumber.from(100));e.maxFeePerGas=Ee(t),e.maxPriorityFeePerGas=Ee(i.BigNumber.from(0))}}catch(e){throw new Error(`Failed to set gas price for Arbitrum transaction: ${e}.`)}return e})(t,r):Ue(t.chainId)?await(async(e,t)=>{if(!Ue(e.chainId))throw new Error("Invalid chain ID for OP Stack gas estimation.");if(void 0===e.type&&(e.type=2),e.gasPrice&&(console.warn("`gasPrice` is not supported on this chain and will be ignored. Use `maxPriorityFeePerGas` and/or `maxFeePerGas` instead."),delete e.gasPrice),e.maxPriorityFeePerGas&&e.maxFeePerGas)return e;try{if(!e.maxPriorityFeePerGas){const r=await t.send("eth_maxPriorityFeePerGas",[]);e.maxPriorityFeePerGas=r}if(e.maxFeePerGas&&(console.warn("maxFeePerGas is specified without maxPriorityFeePerGas - this can result in hung transactions."),e.maxPriorityFeePerGas>=e.maxFeePerGas))throw new Error("Overridden maxFeePerGas is less than or equal to the calculated maxPriorityFeePerGas. Please set both values or maxPriorityFeePerGas alone for correct gas estimation.");if(!e.maxFeePerGas){const{lastBaseFeePerGas:r}=await t.getFeeData();if(!r)throw new Error("Unable to fetch baseFee for last block.");const s=i.BigNumber.from(r).mul(i.BigNumber.from(126)).div(i.BigNumber.from(100)).add(i.BigNumber.from(e.maxPriorityFeePerGas));e.maxFeePerGas=Ee(s)}}catch(e){throw new Error(`Failed to set gas price for OP stack transaction: ${e}.`)}return e})(t,r):Te(t.chainId)?await(async(e,t)=>{if(!Te(e.chainId))throw new Error("Invalid chain ID for BSC gas estimation.");if(void 0===e.type?e.type=0:1!=e.type&&2!=e.type||console.warn("Transaction request type specified is incompatible for chain and will result in undefined behavior. Please use transaction type 0."),!e.gasPrice){const r=await t.getFeeData();e.gasPrice=r.gasPrice?.toHexString()}return e})(t,r):await(async(e,t)=>{if(void 0===e.type&&(e.type=2),2===e.type){if(!e.maxFeePerGas||!e.maxPriorityFeePerGas){const r=await t.getFeeData();e.maxFeePerGas||(e.maxFeePerGas=r.maxFeePerGas?.toHexString()),e.maxPriorityFeePerGas||(e.maxPriorityFeePerGas=r.maxPriorityFeePerGas?.toHexString())}}else if(!e.gasPrice){const r=await t.getFeeData();e.gasPrice=r.gasPrice?.toHexString()}return e})(t,r),0===t.type&&delete t.accessList,2!==t.type&&(delete t.maxPriorityFeePerGas,delete t.maxFeePerGas),t}function ze({currentRecoveryMethod:e,upgradeToRecoveryMethod:t}){switch(e){case"privy":case"user-passcode":return!0;case"icloud":case"google-drive":if(e===t)throw new Error("Cannot upgrade to the existing cloud platform");return!0;default:throw new Error("Unknown recovery method")}}class He extends _.default{_walletProxy;_privyInternal;_address;_chainId;_chains;_jsonRpcProvider;constructor({walletProxy:e,privyInternal:t,address:r,chains:s,chainId:a=s[0].id}){super(),this._walletProxy=e,this._privyInternal=t,this._address=r,this._chainId=a,this._chains=s,this._jsonRpcProvider=Me(a,s,{rpcUrls:[]},{appId:this._privyInternal.appId})}async request(e){if(t=e.method,ke.includes(t))return this.handleIFrameRpc(e);var t;switch(e.method){case"eth_accounts":case"eth_requestAccounts":return this._address?[this._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_sendTransaction":{const t=e.params?.[0];return this.handleSendTransaction(t)}case"eth_populateTransactionRequest":{const t=e.params?.[0];return this.handlePopulateTransaction(t)}default:return this.handleJsonRpc(e)}}ensureChainId(e){const t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),t}internalSwitchEthereumChain(e){e&&Number(e)!==this._chainId&&(this._chainId=Number(e),this._jsonRpcProvider=Me(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit("chainChanged",e))}async handlePopulateTransaction(e){const t=this.ensureChainId(e);return We(this._address,t,this._jsonRpcProvider)}async handleSendTransaction(e){const t=this.ensureChainId(e),r=await We(this._address,t,this._jsonRpcProvider),s=await this.handleIFrameRpc({method:"eth_signTransaction",params:[r]});return await this.handleJsonRpc({method:"eth_sendRawTransaction",params:[s]})}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw new Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;const t={...e.params[0],chainId:`0x${this._chainId.toString(16)}`};this.internalSwitchEthereumChain(t.chainId);try{return await this._jsonRpcProvider.send("eth_estimateGas",[t])}catch(e){console.warn(`Gas estimation failed with error: ${e}. Retrying gas estimation by omitting the 'from' address`);try{return delete t.from,await this._jsonRpcProvider.send("eth_estimateGas",[t])}catch(t){throw console.warn(`Gas estimation failed with error: ${t} when omitting the 'from' address`),e}}}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new we(`Invalid params for ${e.method}`,4200);let t;if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new we(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{const t=await this._privyInternal.getAccessToken();if(!t)throw new Error("Missing privy token. User must be logged in");this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_started",{method:e.method,address:this._address});const r=await this._walletProxy.rpc({request:e,address:this._address,accessToken:t});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_completed",{method:e.method,address:this._address}),r.response.data}catch(t){console.error(t);const r=t instanceof Error?t.message:"Unable to make wallet request";throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_failed",{method:e.method,address:this._address,error:r}),new I({code:"embedded_wallet_request_error",error:r})}}async handleJsonRpc(e){return this._jsonRpcProvider.send(e.method,e.params??[])}toJSON(){return`PrivyEIP1193Provider { address: '${this._address}', chainId: ${this._chainId}, request: [Function] }`}}class $e{_walletProxy;_privyInternal;_publicKey;constructor({walletProxy:e,privyInternal:t,publicKey:r}){this._walletProxy=e,this._privyInternal=t,this._publicKey=r}async request(e){const t=await this._privyInternal.getAccessToken();if(!t)throw new I({error:"Missing access token",code:"attempted_rpc_call_before_logged_in"});return(await this._walletProxy.solanaRpc({accessToken:t,request:e,publicKey:this._publicKey})).response.data}}function Be(e){return void 0!==e.error}const Je=(Ke=0,()=>"id-"+Ke++);var Ke;const Ve=(e,t)=>"bigint"==typeof t?t.toString():t,Ye=e=>new Promise((t=>{setTimeout(t,e)})),Qe=(e,{ms:t,msg:r})=>Promise.race([e,new Promise(((e,s)=>{setTimeout((()=>{s(new Error(r))}),t??15e3)}))]),Ze=new class{callbacks={};enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){const r=this.callbacks[t];if(!r)throw new Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:wallet:create":case"privy:wallet:connect":case"privy:wallet:recover":case"privy:wallet:rpc":case"privy:wallet:set-recovery":case"privy:solana-wallet:create":case"privy:solana-wallet:connect":case"privy:solana-wallet:recover":case"privy:solana-wallet:rpc":return r;default:throw new Error(`invalid wallet event type ${e}`)}}};class Xe{ready;cache;_embeddedWalletMessagePoster;constructor(e){this.ready=!1,this.cache=new Map,this._embeddedWalletMessagePoster=e}ping(e=15e3){return Qe(this.invoke("privy:iframe:ready",{},this._embeddedWalletMessagePoster),{msg:"Ping reached timeout",ms:e})}create(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connect(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recover(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}setRecovery(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:set-recovery",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: setRecovery",ms:6e4})}rpc(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:rpc",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: rpc"})}createSolana(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connectSolana(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recoverSolana(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}solanaRpc(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:rpc",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: rpc"})}handleEmbeddedWalletMessages(e){switch(e.event){case"privy:iframe:ready":const t=Ze.dequeue(e.event,e.id);return Be(e)?t.reject(new _e(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":const r=Ze.dequeue(e.event,e.id);return Be(e)?r.reject(new _e(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:connect":const s=Ze.dequeue(e.event,e.id);return Be(e)?s.reject(new _e(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:recover":const a=Ze.dequeue(e.event,e.id);return Be(e)?a.reject(new _e(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:rpc":const i=Ze.dequeue(e.event,e.id);return Be(e)?i.reject(new _e(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:set-recovery":const n=Ze.dequeue(e.event,e.id);return Be(e)?n.reject(new _e(e.error.type,e.error.message)):n.resolve(e.data);case"privy:solana-wallet:create":const o=Ze.dequeue(e.event,e.id);return Be(e)?o.reject(new _e(e.error.type,e.error.message)):o.resolve(e.data);case"privy:solana-wallet:connect":const c=Ze.dequeue(e.event,e.id);return Be(e)?c.reject(new _e(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:recover":const l=Ze.dequeue(e.event,e.id);return Be(e)?l.reject(new _e(e.error.type,e.error.message)):l.resolve(e.data);case"privy:solana-wallet:rpc":const d=Ze.dequeue(e.event,e.id);return Be(e)?d.reject(new _e(e.error.type,e.error.message)):d.resolve(e.data)}}waitForReady(){return this.ready?Promise.resolve():new Promise((async(e,t)=>{for(;!this.ready;)this.invoke("privy:iframe:ready",{},this._embeddedWalletMessagePoster).then((()=>{this.ready=!0,e()})).catch(t),await Ye(150)}))}invoke(e,t,r){const s=((e,t)=>`${e}${JSON.stringify(t,Ve)}`)(e,t);if("privy:wallet:create"===e||"privy:solana-wallet:create"===e){const e=this.cache.get(s);if(e)return e}const a=new Promise(((s,a)=>{const i=Je();Ze.enqueue(i,{resolve:s,reject:a}),r.postMessage(JSON.stringify({id:i,event:e,data:t}),"*")})).finally((()=>{this.cache.delete(s)}));return this.cache.set(s,a),a}}class et{_privyInternal;_proxy;_chains=Array.from(de);constructor(e,t,r){this._privyInternal=e,t&&(this._proxy=new Xe(t)),r&&(this._chains=r)}setMessagePoster(e){this._proxy=new Xe(e)}async create(e,t,r,s,a){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");let i;if(i=t||(e?"user-passcode":"privy"),e&&"string"!=typeof e)throw new Error("Invalid recovery password, must be a string");if("privy"===i&&this._privyInternal.config?.embedded_wallet_config.require_user_password_on_create)throw new Error("Password not provided yet is required by App configuration");const n=await this._privyInternal.getAccessToken();if(!n)throw new Error("User must be logged in to create an embedded wallet");const{address:o}=await this._proxy.create({accessToken:n,recoveryMethod:i,recoveryPassword:e,recoveryAccessToken:r,recoverySecretOverride:s,iCloudRecordNameOverride:a});if(!o)throw new Error("Failed to create wallet");const{user:c}=await this._privyInternal.refreshSession();return{user:c,provider:new He({address:o,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}}async createSolana(e){if(!this._proxy)throw new I({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_creation_error"});const t=await this._privyInternal.getAccessToken();if(!t)throw new I({error:"User must be logged in to create an embedded wallet",code:"embedded_wallet_creation_error"});if(e?.ethereumAccount){if("privy"!==e.ethereumAccount.recovery_method)throw new I({error:"Cannot create Solana wallet for user with Ethereum wallet with user-controlled recovery",code:"embedded_wallet_creation_error"});await this.getProvider(e.ethereumAccount)}const{publicKey:r}=await this._proxy.createSolana({accessToken:t,ethereumAddress:e?.ethereumAccount?.address});if(!r)throw new I({error:"Failed to create wallet",code:"embedded_wallet_creation_error"});return this._privyInternal.callbacks?.setUser&&await this._privyInternal.refreshSession(),new $e({publicKey:r,privyInternal:this._privyInternal,walletProxy:this._proxy})}async hasEmbeddedWallet(){const{user:e,token:t}=await this._privyInternal.refreshSession();if(!e||!t)throw new Error("User must be logged in to interact with embedded wallets");return!!this._getEmbeddedWallet(e)}async isPasswordRequired(){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const{user:e,token:t}=await this._privyInternal.refreshSession();if(!e||!t)throw new Error("User must be logged in to interact with embedded wallets");const r=this._getEmbeddedWallet(e);if(!r)return!1;if("privy"===r.recovery_method)return!1;try{return await this._proxy.connect({accessToken:t,address:r.address}),!1}catch(e){return fe(e)}}async getProvider(e,t,r,s){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const a=await this._load(e,t,r,s);return new He({address:a,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}async getSolanaProvider(e){if(!this._proxy)throw new I({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_webview_not_loaded"});const t=await this._loadSolana(e);return new $e({publicKey:t,privyInternal:this._privyInternal,walletProxy:this._proxy})}async setPassword(e,t){const{provider:r}=await this.setRecovery({wallet:e,recoveryMethod:"user-passcode",password:t});return r}async setRecovery({wallet:e,...t}){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");ze({currentRecoveryMethod:e.recovery_method,upgradeToRecoveryMethod:"icloud-native"===t.recoveryMethod?"icloud":t.recoveryMethod});const r=await this._load(e),s=await this._privyInternal.getAccessToken();if(!s)throw new Error("User must be logged in to interact with embedded wallets");const a=e.recovery_method;this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_set_recovery_started",{address:e.address,target_recovery_method:t.recoveryMethod,existing_recovery_method:a});try{await this._proxy.setRecovery({accessToken:s,address:r,recoveryMethod:t.recoveryMethod,recoveryPassword:"user-passcode"===t.recoveryMethod?t.password:void 0,recoveryAccessToken:"google-drive"===t.recoveryMethod||"icloud"===t.recoveryMethod?t.recoveryAccessToken:void 0,recoverySecretOverride:"icloud-native"===t.recoveryMethod?t.recoverySecretOverride:void 0,iCloudRecordNameOverride:"icloud-native"===t.recoveryMethod?t.iCloudRecordNameOverride:void 0}),this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_set_recovery_completed",{address:e.address,target_recovery_method:t.recoveryMethod,existing_recovery_method:a});const{user:i}=await this._privyInternal.refreshSession();return{user:i,provider:new He({address:r,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}}catch(t){throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_set_recovery_failed",{address:e.address,recovery_method:e.recovery_method,error:t instanceof Error?t.message:"Unable to recover wallet"}),t}}getURL(){const 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}getMessageHandler(){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");return this._proxy.handleEmbeddedWalletMessages.bind(this._proxy)}onMessage(e){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");return this._proxy.handleEmbeddedWalletMessages(e)}async ping(e){try{if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");return await this._proxy.ping(e),!0}catch(e){return console.error(e),!1}}async _load(e,t,r,s){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const a=await this._privyInternal.getAccessToken();if(!a)throw new Error("User must be logged in to interact with embedded wallets");const i=e.address;try{return await this._proxy.connect({accessToken:a,address:i}),i}catch(n){if(fe(n)){try{if("privy"===e.recovery_method){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:e.recovery_method});const t=await this._proxy.recover({accessToken:a,address:i});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:e.recovery_method}),t.address}if("user-passcode"===e.recovery_method&&t){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:e.recovery_method});const r=await this._proxy.recover({accessToken:a,address:i,recoveryPassword:t});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:e.recovery_method}),r.address}if(["google-drive","icloud"].includes(e.recovery_method)&&r){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:e.recovery_method});const t=await this._proxy.recover({accessToken:a,address:i,recoveryAccessToken:r});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:e.recovery_method}),t.address}if("icloud"===e.recovery_method&&s){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:"icloud-native"});const t=await this._proxy.recover({accessToken:a,address:i,recoverySecretOverride:s});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:"icloud-native"}),t.address}}catch(t){throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_failed",{address:e.address,recovery_method:e.recovery_method,error:t instanceof Error?t.message:"Unable to recover wallet"}),t}throw n}throw n}}async _loadSolana(e){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const t=await this._privyInternal.getAccessToken();if(!t)throw new Error("User must be logged in to interact with embedded wallets");const r=e.public_key;try{return await this._proxy.connectSolana({accessToken:t,publicKey:r}),r}catch(e){if(fe(e)){return(await this._proxy.recoverSolana({accessToken:t,publicKey:r})).publicKey}throw e}}_getEmbeddedWallet(e){return e?.linked_accounts.find((e=>"wallet"===e.type&&"embedded"===e.connector_type&&"privy"===e.wallet_client_type))}}class tt{static parse(e){try{return new tt(e)}catch(e){return null}}value;_decoded;constructor(e){this.value=e,this._decoded=m.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()>=1e3*(this.expiration-e)}}const rt="privy:token",st="privy-token",at="privy:refresh_token",it="privy-refresh-token",nt="privy:id-token",ot="privy-id-token",ct="privy-session",lt="privy:session_transfer_token",dt=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","forked_token_cleared","token_stored","refresh_token_stored","identity_token_stored"];class ht extends _.default{static events=dt;_storage;_isUsingServerCookies=!1;constructor(e){super(),this._storage=e.storage}set isUsingServerCookies(e){this._isUsingServerCookies=e}async getToken(){const e=await this._storage.get(rt);try{return"string"==typeof e?new tt(e).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getRefreshToken(){try{const e=await this._storage.get(at);return"string"==typeof e?e:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getRefreshToken_error"}),null}}async getIdentityToken(){try{const e=await this._storage.get(nt);return"string"==typeof e?e:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getIdentityToken_error"}),null}}async getForkedToken(){try{const e=await this._storage.get(lt);return"string"==typeof e?e:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getForkedToken_error"}),null}}get mightHaveServerCookies(){try{const e=w.default.get(ct);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e,t){return this.mightHaveServerCookies||"string"==typeof e&&"string"==typeof t}async hasRecoveryCredentials(){return"string"==typeof await this.getForkedToken()}tokenIsActive(e){if(!e)return!1;const t=tt.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){const t=await Promise.all([this._storage.del(rt),this._storage.del(at),this._storage.del(nt),this.clearForkedToken()]);return e?.reason&&this.emit("storage_cleared",{reason:e.reason}),t}async storeToken(e){if("string"==typeof e){const t=await this._storage.get(rt);if(await this._storage.put(rt,e),!this._isUsingServerCookies){const t=tt.parse(e)?.expiration;w.default.set(st,e,{sameSite:"Strict",secure:!0,expires:t?new Date(1e3*t):void 0})}t!==e&&this.emit("token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{const e=await this._storage.get(rt);await this._storage.del(rt),w.default.remove(st),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storeRefreshToken(e){"string"==typeof e?(await this._storage.put(at,e),this._isUsingServerCookies||(w.default.set(ct,"t",{sameSite:"Strict",secure:!0,expires:30}),w.default.set(it,e,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(at),w.default.remove(it),w.default.remove(ct),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async storeIdentityToken(e){if("string"==typeof e){const t=await this._storage.get(nt);if(await this._storage.put(nt,e),!this._isUsingServerCookies){const t=tt.parse(e)?.expiration;w.default.set(ot,e,{sameSite:"Strict",secure:!0,expires:t?new Date(1e3*t):void 0})}t!==e&&this.emit("identity_token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{const e=await this._storage.get(nt);await this._storage.del(nt),w.default.remove(ot),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async clearForkedToken(){await this._storage.del(lt)}}const pt=e=>{const t=new AbortController;return setTimeout((()=>t.abort()),e),t.signal},yt="privy:caid";class ut{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.26.2";_fetch;nativeAppIdentifier;callbacks;_cache=new Map;session;constructor(e){this._storage=e.storage,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,"undefined"==typeof document&&(this.nativeAppIdentifier=e.nativeAppIdentifier),this.session=new ht({storage:this._storage,isUsingServerCookies:!1}),this._fetch=v.default(fetch,{retries:3,retryDelay:500})}get isReady(){return Boolean(this._config)}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){this.isReady||(this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.callbacks?.setIsReady?.(!0),this.createAnalyticsEvent("sdk_initialize",{}))}async fetch(t,{body:r,params:s,headers:a,options:i={onRequest:this._beforeRequest.bind(this)}}){const n=`${this.baseUrl}${e.getPathWithParams(t.path,s)}`,o=new Request(n,{method:t.method,body:JSON.stringify(r),headers:a}),c=await i.onRequest(o),l=await this._fetch(o,c),d=await l.json();if(l.status>299)throw new k(d);return d}async _beforeRequestWithoutInitialize(e){const t=await this.session.getToken(),r=new Headers(e.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-client",this._sdkVersion),r.set("Authorization",`Bearer ${t}`),r.set("Content-Type","application/json"),r.set("Accept","application/json");const s=await this._getOrGenerateClientAnalyticsId();return s&&r.set("privy-ca-id",s),this.nativeAppIdentifier&&r.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:pt(2e4),headers:r,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(e.AppConfig,{params:{app_id:this.appId},options:{onRequest:this._beforeRequestWithoutInitialize.bind(this)}})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{const e=await this._storage.get(yt);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){console.error("Unable to load clientId",e)}try{this._analyticsId=d.v4()}catch(e){console.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(yt,this._analyticsId)}catch(e){console.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(yt)}catch(e){console.error("Unable to delete clientId",e)}}async createAnalyticsEvent(t,r){try{await this.fetch(e.AnalyticsEvent,{body:{event_name:t,client_id:await this._getOrGenerateClientAnalyticsId(),payload:r},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}catch(e){}}async refreshSession(){const e=await this.session.getRefreshToken()??void 0,t=e??"key",r=this._cache.get(t);if(r)return await r;const s=this._refreshSession(e);this._cache.set(t,s);try{return await s}catch(e){throw e}finally{this._cache.delete(t)}}async _refreshSession(t){const r=await this.session.getToken();if(!this.session.hasRefreshCredentials(r,t??null))throw await this._initialize(),new Error("missing_or_invalid_token");try{const{session_update_action:r,...s}=await this.fetch(e.RefreshSession,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}});return this.callbacks?.setUser?.(s.user),"set"===r&&await Promise.all([this.session.storeToken(s.token),this.session.storeRefreshToken(s.refresh_token),this.session.storeIdentityToken(s.identity_token)]),"clear"===r&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===r&&s.token&&(await this.session.storeToken(s.token),s.identity_token&&await this.session.storeIdentityToken(s.identity_token)),s}catch(e){throw(e instanceof k&&e.code===h.PrivyErrorCode.MISSING_OR_INVALID_TOKEN||e instanceof Error&&"missing_or_invalid_token"===e.message)&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),e}}async getAccessToken(){const[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t))try{return await this.refreshSession(),await this.session.getToken()}catch(e){return null}return e}async getIdentityToken(){return await this.session.getIdentityToken()}}class mt{_privyInternal;constructor(e){this._privyInternal=e}async init(t){return this._privyInternal.fetch(e.RecoveryOAuthInitICloud,{body:{client_type:t}})}async getICloudConfiguration(t){return this._privyInternal.fetch(e.RecoveryConfigurationICloud,{body:{client_type:t}})}}class _t{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t){const r=P(),s=T(),a=await S({codeVerifier:r,digest:this._crypto?.digest});return await Promise.all([this._storage.put(x,r),this._storage.put(E,s)]),this._privyInternal.fetch(e.RecoveryOAuthInit,{body:{redirect_to:t,code_challenge:a,state_code:s}})}async authorize(t,r){const[s,a]=await Promise.all([this._storage.get(x),this._storage.get(E)]);if(a!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"recovery_oauth",storedStateCode:a??"",returnedStateCode:r??""}),new I({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});const i=await this._privyInternal.fetch(e.RecoveryOAuthAuthenticate,{body:{authorization_code:t,state_code:a,code_verifier:s}});return await Promise.all([this._storage.del(x),this._storage.del(E)]),i}}class vt{_privyInternal;auth;icloudAuth;constructor(e,t,r){this._privyInternal=e,this.auth=new _t(this._privyInternal,t,r),this.icloudAuth=new mt(this._privyInternal)}async getRecoveryKeyMaterial(t,r){return this._privyInternal.fetch(e.RecoveryKeyMaterial,{body:{chain_type:r},params:{address:t}})}}class wt{_privyInternal;constructor(e){this._privyInternal=e}async get(){try{const{user:e}=await this._privyInternal.refreshSession();return{user:e}}catch(e){throw e}}}const gt=["metamask","phantom","brave_wallet","rainbow","coinbase_wallet","metamask","trust","safe","rainbow","uniswap","zerion","argent","spot","omni","cryptocom","blockchain","safepal","bitkeep","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","privy","unknown"];exports.ALL_WALLET_CLIENT_TYPES=gt,exports.DEFAULT_SUPPORTED_CHAINS=de,exports.DEFAULT_SUPPORTED_CHAIN_IDS=he,exports.EmbeddedProviderError=we,exports.InMemoryCache=class{_cache={};get(e){return this._cache[e]}put(e,t){void 0!==t?this._cache[e]=t:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}},exports.LocalStorage=class{async get(e){const t=localStorage.getItem(e);return null===t?void 0:JSON.parse(t)}put(e,t){void 0!==t?localStorage.setItem(e,JSON.stringify(t)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map((([e])=>e))}},exports.PrivyApiError=k,exports.PrivyClientError=I,exports.PrivyConnectorError=ve,exports.PrivyProviderRpcError=be,exports.ProviderErrors=ge,exports.QuantityToBigNumber=Ie,exports.SUPPORTED_CONNECTOR_TYPES=["injected","wallet_connect","wallet_connect_v2","coinbase_wallet","embedded"],exports.calculateTotalGasEstimate=async function(e,t){if(!e.gasLimit)throw new be("gasLimit was not successfully set for transaction.");const r=Ie(e.gasLimit);let s=i.BigNumber.from(0);if(2==e.type){if(!e.maxFeePerGas)throw new be("maxFeePerGas was not successfully set for transaction of type 2.");s=Ie(e.maxFeePerGas)}else{if(!e.gasPrice)throw new be("gasPrice was not successfully set for transaction of type 0 or 1.");s=Ie(e.gasPrice)}let a=r.mul(s),c=i.BigNumber.from(0);if(e.chainId&&Ue(e.chainId))try{c=await async function(e,t){if(!e.chainId||e.chainId&&!Ue(e.chainId))return i.BigNumber.from(0);let r=i.BigNumber.from(0);try{const s=new n.Contract(Re,Ae,t),a=xe(e),i=o.serialize(a);r=await s.getL1Fee(i)}catch(e){}return r}(e,t),a=a.add(c)}catch(e){}return{totalGasEstimate:a,l1ExecutionFeeEstimate:c}},exports.chainDefs=le,exports.convertBigNumberish=Ee,exports.default=class{auth;user;embeddedWallet;recovery;_privyInternal;constructor({clientId:e,...t}){this._privyInternal=new ut({...t,appClientId:e}),this.user=new wt(this._privyInternal),this.auth=new F(this._privyInternal,t.storage,t.crypto),this.embeddedWallet=new et(this._privyInternal,t.embeddedWalletMessagePoster,t.supportedChains),this.recovery=new vt(this._privyInternal,t.storage,t.crypto)}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}getAccessToken(){return this._privyInternal.getAccessToken()}getIdentityToken(){return this._privyInternal.getIdentityToken()}},exports.errorIndicatesRecoveryIsNeeded=fe,exports.getUserEmbeddedSolanaWallet=e=>{if(!e)return null;const t=e.linked_accounts.find((e=>"wallet"===e.type&&"privy"===e.wallet_client_type&&"embedded"===e.connector_type&&"solana"===e.chain_type));return t||null},exports.getUserEmbeddedWallet=e=>{if(!e)return null;const t=e.linked_accounts.find((e=>"wallet"===e.type&&"privy"===e.wallet_client_type&&"embedded"===e.connector_type&&"ethereum"===e.chain_type));return t||null},exports.populateTransactionRequest=We,exports.throwIfInvalidRecoveryUpgradePath=ze,exports.toEthersUnsignedTransaction=xe,exports.toObjectKeys=(e,t=!0)=>e.reduce(((e,r)=>({...e,[r]:t})),{});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@privy-io/public-api"),t=require("jose"),r=require("eventemitter3"),s=require("@ethersproject/abstract-signer"),a=require("@ethersproject/providers"),i=require("@ethersproject/bignumber"),n=require("@ethersproject/contracts"),o=require("@ethersproject/transactions"),c=require("@ethersproject/units"),l=require("fetch-retry"),d=require("uuid"),h=require("@privy-io/api-base"),p=require("js-cookie");function y(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var m=u(t),_=y(r),v=y(l),w=y(p);class g{_privyInternal;constructor(e){this._privyInternal=e}async syncWithToken(t){const r=await this._privyInternal.fetch(e.CustomJWTAuthenticate,{body:{token:t}});return await Promise.all([this._privyInternal.session.storeToken(r.token),this._privyInternal.session.storeRefreshToken(r.refresh_token),this._privyInternal.session.storeIdentityToken(r.identity_token)]),this._privyInternal.callbacks?.setUser?.(r.user),r}}class f{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(t,r){return this._privyInternal.fetch(e.PasswordlessInit,{body:{email:t,token:r}})}async loginWithCode(t,r){const s=await this._privyInternal.fetch(e.PasswordlessAuthenticate,{body:{email:t,code:r}});return await Promise.all([this._privyInternal.session.storeToken(s.token),this._privyInternal.session.storeRefreshToken(s.refresh_token),this._privyInternal.session.storeIdentityToken(s.identity_token)]),this._privyInternal.callbacks?.setUser?.(s.user),s}async linkWithCode(t,r){await this._privyInternal.fetch(e.PasswordlessLink,{body:{email:t,code:r}});return(await this._privyInternal.refreshSession()).user}async unlink(t){await this._privyInternal.fetch(e.PasswordlessUnlink,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}}class b{_privyInternal;constructor(e){this._privyInternal=e}async initializeAuth({relyingParty:t,redirectUrl:r,token:s}){return await this._privyInternal.fetch(e.FarcasterInit,{body:{relying_party:t,redirect_url:r,token:s}})}async getFarcasterStatus({channel_token:t}){return await this._privyInternal.fetch(e.FarcasterStatus,{headers:{"farcaster-channel-token":t}})}async authenticate({channel_token:t,message:r,signature:s,fid:a}){const i=await this._privyInternal.fetch(e.FarcasterAuthenticate,{body:{channel_token:t,message:r,signature:s,fid:a}});return await Promise.all([this._privyInternal.session.storeToken(i.token),this._privyInternal.session.storeRefreshToken(i.refresh_token),this._privyInternal.session.storeIdentityToken(i.identity_token)]),this._privyInternal.callbacks?.setUser?.(i.user),i}async link({channel_token:t,message:r,signature:s,fid:a}){await this._privyInternal.fetch(e.FarcasterLink,{body:{channel_token:t,message:r,signature:s,fid:a}});return(await this._privyInternal.refreshSession()).user}async unlink({fid:t}){await this._privyInternal.fetch(e.FarcasterUnlink,{body:{fid:t}});return(await this._privyInternal.refreshSession()).user}}class k extends Error{error;code;constructor({error:e,code:t}){super(e),this.error=e,this.code=t}}class I extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}}const E="privy:state_code",x="privy:code_verifier";function P(){return t.base64url.encode((e=36,crypto.getRandomValues(new Uint8Array(e))));var e}function T(){return P()}async function S({codeVerifier:e,method:r="S256",digest:s=crypto.subtle.digest.bind(crypto.subtle)}){if("S256"==r){const r=await async function(e,t){const r=(new TextEncoder).encode(e),s=await t("SHA-256",r);return new Uint8Array(s)}(e,s);return t.base64url.encode(r)}return e}class C{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t,r){const s=P(),a=T(),i=await S({codeVerifier:s,digest:this._crypto?.digest});return await Promise.all([this._storage.put(x,s),this._storage.put(E,a)]),this._privyInternal.fetch(e.OAuthInit,{body:{redirect_to:r,provider:t,code_challenge:i,state_code:a}})}async loginWithCode(t,r,s,a){const[i,n]=await Promise.all([this._storage.get(x),this._storage.get(E)]);if(n!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:n??"",returnedStateCode:r??""}),new I({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});const o=await this._privyInternal.fetch(e.OAuthAuthenticate,{body:{authorization_code:t,code_type:a,state_code:n,code_verifier:i}});return await Promise.all([this._privyInternal.session.storeToken(o.token),this._privyInternal.session.storeRefreshToken(o.refresh_token),this._privyInternal.session.storeIdentityToken(o.identity_token)]),this._privyInternal.callbacks?.setUser?.(o.user),await Promise.all([this._storage.del(x),this._storage.del(E)]),o}async linkWithCode(t,r,s,a){const[i,n]=await Promise.all([this._storage.get(x),this._storage.get(E)]);if(n!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:n??"",returnedStateCode:r??""}),new I({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});await this._privyInternal.fetch(e.OAuthLink,{body:{authorization_code:t,code_type:a,state_code:n,code_verifier:i}});const o=await this._privyInternal.refreshSession();return await Promise.all([this._storage.del(x),this._storage.del(E)]),o.user}async unlink(t,r){await this._privyInternal.fetch(e.OAuthUnlink,{body:{provider:t,subject:r}});return(await this._privyInternal.refreshSession()).user}}class R{_privyInternal;constructor(e){this._privyInternal=e}async generateRegistrationOptions(t){return await this._privyInternal.fetch(e.PasskeyLinkInit,{body:{relying_party:t}})}async generateAuthenticationOptions(t){return await this._privyInternal.fetch(e.PasskeyAuthenticateInit,{body:{relying_party:t}})}async loginWithPasskey(t,r,s){const a=await this._privyInternal.fetch(e.PasskeyAuthenticate,{body:{relying_party:s,challenge:r,authenticator_response:{type:t.type,id:t.id,raw_id:t.rawId,response:{signature:t.response.signature,client_data_json:t.response.clientDataJSON,authenticator_data:t.response.authenticatorData,user_handle:t.response.userHandle||void 0},authenticator_attachment:t.authenticatorAttachment||void 0,client_extension_results:{app_id:t.clientExtensionResults.appid||void 0,cred_props:t.clientExtensionResults.credProps||void 0,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret||void 0}}}});return await Promise.all([this._privyInternal.session.storeToken(a.token),this._privyInternal.session.storeRefreshToken(a.refresh_token),this._privyInternal.session.storeIdentityToken(a.identity_token)]),this._privyInternal.callbacks?.setUser?.(a.user),a}async linkWithPasskey(t,r){await this._privyInternal.fetch(e.PasskeyLink,{body:{relying_party:r,authenticator_response:{type:t.type,id:t.id,raw_id:t.rawId,response:{client_data_json:t.response.clientDataJSON,attestation_object:t.response.attestationObject,authenticator_data:t.response.authenticatorData||void 0,transports:t.response.transports||void 0,public_key:t.response.publicKey||void 0,public_key_algorithm:t.response.publicKeyAlgorithm||void 0},authenticator_attachment:t.authenticatorAttachment||void 0,client_extension_results:{app_id:t.clientExtensionResults.appid||void 0,cred_props:t.clientExtensionResults.credProps||void 0,hmac_create_secret:t.clientExtensionResults.hmacCreateSecret||void 0}}}});return(await this._privyInternal.refreshSession()).user}}class A{_privyInternal;constructor(e){this._privyInternal=e}async sendCode(t,r){return this._privyInternal.fetch(e.PasswordlessSmsInit,{body:{phoneNumber:t,token:r}})}async loginWithCode(t,r){const s=await this._privyInternal.fetch(e.PasswordlessSmsAuthenticate,{body:{phoneNumber:t,code:r}});return await Promise.all([this._privyInternal.session.storeToken(s.token),this._privyInternal.session.storeRefreshToken(s.refresh_token),this._privyInternal.session.storeIdentityToken(s.identity_token)]),this._privyInternal.callbacks?.setUser?.(s.user),s}async linkWithCode(t,r){await this._privyInternal.fetch(e.PasswordlessSmsLink,{body:{phoneNumber:t,code:r}});return(await this._privyInternal.refreshSession()).user}async unlink(t){await this._privyInternal.fetch(e.PasswordlessSmsUnlink,{body:{phoneNumber:t}});return(await this._privyInternal.refreshSession()).user}}class U{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async linkWithSiwe(t,r,s){const a=r||this._wallet,i=s||this._preparedMessage;if(!a)throw new Error("A wallet must be provided in the init step or as an argument to linkWithSiwe");if(!i)throw new Error("A message must be generated and signed before being used to link a wallet to privy");try{await this._privyInternal.fetch(e.SiweLink,{body:{message:i,signature:t,chainId:a.chainId,walletClientType:a.walletClientType,connectorType:a.connectorType}});return(await this._privyInternal.refreshSession()).user}catch(e){throw e}}async loginWithSiwe(t,r,s){const a=r||this._wallet,i=s||this._preparedMessage;if(!a)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!i)throw new Error("A message must be generated and signed before being used to login to privy with a wallet");try{const r=await this._privyInternal.fetch(e.SiweAuthenticate,{body:{signature:t,message:i,chainId:a.chainId,walletClientType:a.walletClientType,connectorType:a.connectorType}});return await Promise.all([this._privyInternal.session.storeToken(r.token),this._privyInternal.session.storeRefreshToken(r.refresh_token),this._privyInternal.session.storeIdentityToken(r.identity_token)]),this._privyInternal.callbacks?.setUser?.(r.user),r}catch(e){throw e}}async init(t,r,s){this._wallet=t;const a=await this._privyInternal.fetch(e.SiweInit,{body:{address:t.address}}),{nonce:i}=a,n=`${(o={chainId:t.chainId.toString().replace("eip155:",""),address:t.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:r,nonce:i,uri:s}).domain} wants you to sign in with your Ethereum account:\n${o.address}\n\n${o.statement}\n\nURI: ${o.uri}\nVersion: 1\nChain ID: ${o.chainId}\nNonce: ${o.nonce}\nIssued At: ${o.issuedAt}\nResources:\n- https://privy.io`;var o;return this._preparedMessage=n,{nonce:i,message:n}}}class F{_privyInternal;customProvider;phone;email;oauth;siwe;passkey;farcaster;constructor(e,t,r){this._privyInternal=e,this.customProvider=new g(this._privyInternal),this.phone=new A(this._privyInternal),this.email=new f(this._privyInternal),this.oauth=new C(this._privyInternal,t,r),this.siwe=new U(this._privyInternal),this.passkey=new R(this._privyInternal),this.farcaster=new b(this._privyInternal)}async logout(){try{const t=await this._privyInternal.session.getRefreshToken()??void 0;await this._privyInternal.fetch(e.Logout,{body:{refresh_token:t}})}catch(e){console.warn("Error destroying session")}await Promise.all([this._privyInternal.session.destroyLocalState({reason:"logout"}),this._privyInternal.destroyClientAnalyticsId()]),this._privyInternal.callbacks?.setUser?.(null)}}const O={id:42161,name:"Arbitrum One",network:"arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-mainnet.rpc.privy.systems"]},alchemy:{http:["https://arb-mainnet.g.alchemy.com/v2"],webSocket:["wss://arb-mainnet.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-mainnet.infura.io/v3"],webSocket:["wss://arbitrum-mainnet.infura.io/ws/v3"]},default:{http:["https://arb1.arbitrum.io/rpc"]},public:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://arbiscan.io"},default:{name:"Arbiscan",url:"https://arbiscan.io"}}},N={id:421613,name:"Arbitrum Goerli",network:"arbitrum-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"AGOR",decimals:18},rpcUrls:{default:{http:["https://goerli-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"}},testnet:!0},L={id:421614,name:"Arbitrum Sepolia",network:"arbitrum-sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://arbitrum-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]},public:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Blockscout",url:"https://sepolia-explorer.arbitrum.io"}},testnet:!0},G={id:43114,name:"Avalanche",network:"avalanche",nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]},public:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://snowtrace.io"},default:{name:"SnowTrace",url:"https://snowtrace.io"}}},D={id:43113,name:"Avalanche Fuji",network:"avalanche-fuji",nativeCurrency:{decimals:18,name:"Avalanche Fuji",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax-test.network/ext/bc/C/rpc"]},public:{http:["https://api.avax-test.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://testnet.snowtrace.io"},default:{name:"SnowTrace",url:"https://testnet.snowtrace.io"}},testnet:!0},M={id:8453,network:"base",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-mainnet.rpc.privy.systems"]},blast:{http:["https://base-mainnet.blastapi.io"],webSocket:["wss://base-mainnet.blastapi.io"]},default:{http:["https://mainnet.base.org"]},public:{http:["https://mainnet.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://basescan.org"},default:{name:"Basescan",url:"https://basescan.org"}},testnet:!0},q={id:84531,network:"base-goerli",name:"Base Goerli Testnet",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://goerli.basescan.org"}},testnet:!0},j={id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://base-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.base.org"]},public:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Blockscout",url:"https://base-sepolia.blockscout.com"}},testnet:!0},W={id:42220,name:"Celo Mainnet",network:"celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]},infura:{http:["https://celo-mainnet.infura.io/v3"]},public:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/mainnet"},etherscan:{name:"CeloScan",url:"https://celoscan.io"}},testnet:!1},z={id:44787,name:"Celo Alfajores Testnet",network:"celo-alfajores",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://alfajores-forno.celo-testnet.org"]},infura:{http:["https://celo-alfajores.infura.io/v3"]},public:{http:["https://alfajores-forno.celo-testnet.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/alfajores"},etherscan:{name:"CeloScan",url:"https://alfajores.celoscan.io/"}},testnet:!0},H={id:314,name:"Filecoin - Mainnet",network:"filecoin-mainnet",nativeCurrency:{decimals:18,name:"filecoin",symbol:"FIL"},rpcUrls:{default:{http:["https://api.node.glif.io/rpc/v1"]},public:{http:["https://api.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filfox",url:"https://filfox.info/en"},filscan:{name:"Filscan",url:"https://filscan.io"},filscout:{name:"Filscout",url:"https://filscout.io/en"},glif:{name:"Glif",url:"https://explorer.glif.io"}}},$={id:314159,name:"Filecoin - Calibration testnet",network:"filecoin-calibration",nativeCurrency:{decimals:18,name:"testnet filecoin",symbol:"tFIL"},rpcUrls:{default:{http:["https://api.calibration.node.glif.io/rpc/v1"]},public:{http:["https://api.calibration.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filscan",url:"https://calibration.filscan.io"}}},B={id:17069,name:"Garnet Holesky",network:"garnet-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.garnetchain.com"]},public:{http:["https://rpc.garnetchain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.garnetchain.com"}}},J={id:5,network:"goerli",name:"Goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.ankr.com/eth_goerli"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.etherscan.io"}},testnet:!0},K={id:17e3,name:"Holesky",network:"holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-holesky.publicnode.com"]},public:{http:["https://ethereum-holesky.publicnode.com"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://holesky.etherscan.io"},default:{name:"EtherScan",url:"https://holesky.etherscan.io"}}},V={id:59144,network:"linea-mainnet",name:"Linea Mainnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]},public:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://lineascan.build"},etherscan:{name:"Etherscan",url:"https://lineascan.build"}},testnet:!1},Y={id:59140,network:"linea-testnet",name:"Linea Goerli Testnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-goerli.infura.io/v3"],webSocket:["wss://linea-goerli.infura.io/ws/v3"]},default:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]},public:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.lineascan.build"},etherscan:{name:"Etherscan",url:"https://goerli.lineascan.build"}},testnet:!0},Q={id:1,network:"homestead",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://mainnet.rpc.privy.systems"]},alchemy:{http:["https://eth-mainnet.g.alchemy.com/v2"],webSocket:["wss://eth-mainnet.g.alchemy.com/v2"]},infura:{http:["https://mainnet.infura.io/v3"],webSocket:["wss://mainnet.infura.io/ws/v3"]},default:{http:["https://cloudflare-eth.com"]},public:{http:["https://cloudflare-eth.com"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://etherscan.io"},default:{name:"Etherscan",url:"https://etherscan.io"}}},Z={id:10,name:"OP Mainnet",network:"optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-mainnet.rpc.privy.systems"]},alchemy:{http:["https://opt-mainnet.g.alchemy.com/v2"],webSocket:["wss://opt-mainnet.g.alchemy.com/v2"]},infura:{http:["https://optimism-mainnet.infura.io/v3"],webSocket:["wss://optimism-mainnet.infura.io/ws/v3"]},default:{http:["https://mainnet.optimism.io"]},public:{http:["https://mainnet.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://optimistic.etherscan.io"},default:{name:"Optimism Explorer",url:"https://explorer.optimism.io"}}},X={id:420,name:"Optimism Goerli Testnet",network:"optimism-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://goerli.optimism.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"}},testnet:!0},ee={id:11155420,name:"Optimism Sepolia",network:"optimism-sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{privy:{http:["https://optimism-sepolia.rpc.privy.systems"]},default:{http:["https://sepolia.optimism.io"]},public:{http:["https://sepolia.optimism.io"]},infura:{http:["https://optimism-sepolia.infura.io/v3"]}},blockExplorers:{default:{name:"Blockscout",url:"https://optimism-sepolia.blockscout.com"}},testnet:!0},te={id:137,name:"Polygon Mainnet",network:"matic",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{privy:{http:["https://polygon-mainnet.rpc.privy.systems"]},alchemy:{http:["https://polygon-mainnet.g.alchemy.com/v2"],webSocket:["wss://polygon-mainnet.g.alchemy.com/v2"]},infura:{http:["https://polygon-mainnet.infura.io/v3"],webSocket:["wss://polygon-mainnet.infura.io/ws/v3"]},default:{http:["https://polygon-rpc.com"]},public:{http:["https://polygon-rpc.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://polygonscan.com"},default:{name:"PolygonScan",url:"https://polygonscan.com"}}},re={id:80001,name:"Mumbai",network:"maticmum",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{default:{http:["https://matic-mumbai.chainstacklabs.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"}},testnet:!0},se={id:690,name:"Redstone",network:"redstone",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.redstonechain.com"]},public:{http:["https://rpc.redstonechain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.redstone.xyz/"}}},ae={id:17001,name:"Redstone Holesky",network:"redstone-holesky",nativeCurrency:{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.holesky.redstone.xyz"]},public:{http:["https://rpc.holesky.redstone.xyz"]}},blockExplorers:{etherscan:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"},default:{name:"EtherScan",url:"https://explorer.holesky.redstone.xyz"}}},ie={id:11155111,network:"sepolia",name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"SEP",decimals:18},rpcUrls:{privy:{http:["https://sepolia.rpc.privy.systems"]},alchemy:{http:["https://eth-sepolia.g.alchemy.com/v2"],webSocket:["wss://eth-sepolia.g.alchemy.com/v2"]},infura:{http:["https://sepolia.infura.io/v3"],webSocket:["wss://sepolia.infura.io/ws/v3"]},default:{http:["https://rpc.sepolia.org"]},public:{http:["https://rpc.sepolia.org"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://sepolia.etherscan.io"},default:{name:"Etherscan",url:"https://sepolia.etherscan.io"}},testnet:!0},ne={id:7777777,name:"Zora",network:"zora",nativeCurrency:{decimals:18,name:"Ether",symbol:"ETH"},rpcUrls:{default:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]},public:{http:["https://rpc.zora.energy"],webSocket:["wss://rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://explorer.zora.energy"}}},oe={id:999999999,name:"Zora Sepolia",network:"zora-sepolia",nativeCurrency:{decimals:18,name:"Zora Sepolia",symbol:"ETH"},rpcUrls:{default:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]},public:{http:["https://sepolia.rpc.zora.energy"],webSocket:["wss://sepolia.rpc.zora.energy"]}},blockExplorers:{default:{name:"Zora Sepolia Explorer",url:"https://sepolia.explorer.zora.energy/"}},testnet:!0},ce={id:999,name:"Zora Goerli Testnet",network:"zora-testnet",nativeCurrency:{decimals:18,name:"Zora Goerli",symbol:"ETH"},rpcUrls:{default:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]},public:{http:["https://testnet.rpc.zora.energy"],webSocket:["wss://testnet.rpc.zora.energy"]}},blockExplorers:{default:{name:"Explorer",url:"https://testnet.explorer.zora.energy"}},testnet:!0},le={mainnet:Q,goerli:J,sepolia:ie,arbitrum:O,arbitrumGoerli:N,arbitrumSepolia:L,optimism:Z,optimismGoerli:X,optimismSepolia:ee,polygon:te,polygonMumbai:re,celo:W,celoAlfajores:z,filecoin:H,filecoinCalibration:$,base:M,baseGoerli:q,baseSepolia:j,linea:V,lineaTestnet:Y,avalanche:G,avalancheFuji:D,holesky:K,redstone:se,garnetHolesky:B,redstoneHolesky:ae,zora:ne,zoraSepolia:oe,zoraTestnet:ce},de=[Q,J,ie,O,N,L,Z,X,ee,te,re,W,z,H,$,M,q,j,{id:80085,network:"berachain-artio",name:"Berachain Artio",nativeCurrency:{name:"BERA",symbol:"BERA",decimals:18},rpcUrls:{default:{http:["https://berachain-artio.rpc.privy.systems"]},public:{http:["https://berachain-artio.rpc.privy.systems"]}},blockExplorers:{default:{name:"Beratrail",url:"https://artio.beratrail.io"}},testnet:!0},V,Y,G,D,K,se,B,ae,ne,oe,ce],he=new Set(de.map((e=>e.id))),pe=["error","invalid_request_arguments","wallet_not_on_device","invalid_recovery_pin","insufficient_funds"];var ye;exports.PrivyEmbeddedWalletErrorCode=void 0,(ye=exports.PrivyEmbeddedWalletErrorCode||(exports.PrivyEmbeddedWalletErrorCode={})).MISSING_OR_INVALID_PRIVY_APP_ID="missing_or_invalid_privy_app_id",ye.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID="missing_or_invalid_privy_account_id",ye.INVALID_DATA="invalid_data",ye.LINKED_TO_ANOTHER_USER="linked_to_another_user",ye.ALLOWLIST_REJECTED="allowlist_rejected",ye.OAUTH_USER_DENIED="oauth_user_denied",ye.UNKNOWN_AUTH_ERROR="unknown_auth_error",ye.USER_EXITED_AUTH_FLOW="exited_auth_flow",ye.MUST_BE_AUTHENTICATED="must_be_authenticated",ye.UNKNOWN_CONNECT_WALLET_ERROR="unknown_connect_wallet_error",ye.GENERIC_CONNECT_WALLET_ERROR="generic_connect_wallet_error",ye.CLIENT_REQUEST_TIMEOUT="client_request_timeout",ye.INVALID_CREDENTIALS="invalid_credentials";class ue extends Error{cause;privyErrorCode;constructor(e,t,r){super(e),t instanceof Error&&(this.cause=t),this.privyErrorCode=r}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}}class me extends ue{type="provider_error";code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}class _e extends Error{type;constructor(e,t){super(t),this.type=e}}class ve extends ue{type="connector_error";constructor(e,t,r){super(e,t,r)}}class we extends Error{code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}const ge={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:"Don’t see your wallet? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}};function fe(e){return function(e){const t=e.type;return"string"==typeof t&&pe.includes(t)}(e)&&"wallet_not_on_device"===e.type}class be extends me{details;constructor(e){const t=e;super(t.message,t.code,t.data);const r=Object.values(ge).find((e=>e.eipCode===t.code));this.details=r||ge.UNKNOWN_ERROR,-32002===t.code&&(t.message?.includes("already pending for origin")?t.message?.includes("wallet_requestPermissions")?this.details=ge.E32002_CONNECTION_ALREADY_PENDING:this.details=ge.E32002_REQUEST_ALREADY_PENDING:t.message?.includes("Already processing")&&t.message.includes("eth_requestAccounts")&&(this.details=ge.E32002_WALLET_LOCKED))}}const ke=["eth_sign","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation"],Ie=e=>i.BigNumber.from(e);function Ee(e){if("number"==typeof e||"bigint"==typeof e||"string"==typeof e)return e;if("function"==typeof e.toHexString)return e.toHexString();throw new Error(`Expected numeric value but received ${e}`)}function xe(e){const t={};return void 0!==e.to&&(t.to=e.to),void 0!==e.data&&(t.data=e.data),void 0!==e.chainId&&(t.chainId=e.chainId),void 0!==e.type&&(t.type=e.type),void 0!==e.accessList&&(t.accessList=e.accessList),void 0!==e.nonce&&(t.nonce=Ie(e.nonce).toNumber()),void 0!==e.gasLimit&&(t.gasLimit=Ie(e.gasLimit)),void 0!==e.gasPrice&&(t.gasPrice=Ie(e.gasPrice)),void 0!==e.value&&(t.value=Ie(e.value)),void 0!==e.maxFeePerGas&&(t.maxFeePerGas=Ie(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=Ie(e.maxPriorityFeePerGas)),t}const Pe=e=>[O.id,N.id,L.id].includes(e),Te=e=>[56,97].includes(e),Se=81457,Ce=168587773,Re="0x420000000000000000000000000000000000000F",Ae=["function getL1Fee(bytes memory _data) external view returns (uint256)"],Ue=e=>[M.id,q.id,j.id,Z.id,X.id,ee.id,ne.id,ce.id,oe.id,Se,Ce].includes(e);const Fe={id:80002,name:"Polygon Amoy",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{privy:{http:["https://polygon-amoy.rpc.privy.systems"]},infura:{http:["https://polygon-amoy.infura.io/v3"],webSocket:["wss://polygon-amoy.infura.io/ws/v3"]},default:{http:["https://rpc-amoy.polygon.technology"]}},blockExplorers:{default:{name:"OK LINK",url:"https://www.oklink.com/amoy"}},testnet:!0},Oe=v.default(fetch,{retries:3,retryDelay:500}),Ne=e=>[te.id,re.id,Fe.id].includes(e),Le=e=>({maxPriorityFee:c.parseUnits(e.maxPriorityFee.toFixed(9),"gwei").toHexString(),maxFee:c.parseUnits(e.maxFee.toFixed(9),"gwei").toHexString()}),Ge=async e=>{let t="";switch(e){case te.id:t="https://gasstation.polygon.technology/v2";break;case re.id:t="https://gasstation-testnet.polygon.technology/v2";break;case Fe.id:t="https://gasstation.polygon.technology/amoy";break;default:throw Error(`chainId ${e} does not support polygon gas stations`)}const r=await Oe(t),s=await r.json();if(r.status>399)throw s;return{safeLow:Le((a=s).safeLow),standard:Le(a.standard),fast:Le(a.fast)};var a};async function De(e,t){try{return(await t.estimateGas(e)).toHexString()}catch(r){let s;if("message"in r&&r.message.includes("insufficient funds")&&(console.warn(`Gas estimation failed with error: ${r}. Retrying gas estimation by omitting the 'value'`),s=await async function({txRequest:e,provider:t}){try{const r={...e,value:void 0};return(await t.estimateGas(r)).toHexString()}catch(e){return console.warn(`Gas estimation failed with error: ${e} when omitting the 'value'`),null}}({txRequest:e,provider:t})),s||(console.warn(`Gas estimation failed with error: ${r}. Retrying gas estimation by omitting the 'from'`),s=await async function({txRequest:e,provider:t}){try{const r={...e,from:void 0};return(await t.estimateGas(r)).toHexString()}catch(e){return console.warn(`Gas estimation failed with error: ${e} when omitting the 'from' address`),null}}({txRequest:e,provider:t})),!s)throw r;return s}}const Me=(e,t,r,s)=>{const i=Number(e),n=t.find((e=>e.id===i));if(!n)throw new ve(`Unsupported chainId ${e}`,4901);let o;if(o=n.rpcUrls.privyWalletOverride&&n.rpcUrls.privyWalletOverride.http[0]?new a.StaticJsonRpcProvider(n.rpcUrls.privyWalletOverride.http[0]):r.rpcUrls&&r.rpcUrls[i]?new a.StaticJsonRpcProvider(r.rpcUrls[i]):n.rpcUrls.privy?.http[0]?new a.StaticJsonRpcProvider({url:n.rpcUrls.privy.http[0],headers:{"privy-app-id":s.appId}}):n.rpcUrls.public?.http[0]?new a.StaticJsonRpcProvider(n.rpcUrls.public?.http[0]):new a.StaticJsonRpcProvider(n.rpcUrls.default?.http[0]),!o)throw new ve(`No RPC url found for ${e}`);return o};function qe(e){return/^-?0x[a-f0-9]+$/i.test(e)}function je(e){const t="number"==typeof e,r="bigint"==typeof e,s="string"==typeof e&&qe(e);return t||r||s}async function We(e,t,r){if(t.chainId=Number(t.chainId),function(e){const t=["gasLimit","gasPrice","value","maxPriorityFeePerGas","maxFeePerGas"];for(const r of t){const t=e[r];if(void 0!==t&&!je(t))throw new Error(`Transaction request property '${r}' must be a valid number, bigint, or hex string representing a quantity`)}if("number"!=typeof e.chainId)throw new Error("Transaction request property 'chainId' must be a number")}(t),t.from||(t.from=e),!t.nonce){const a=new s.VoidSigner(e,r);t.nonce=await a.getTransactionCount("pending")}return t.gasLimit||(t.gas?(t.gasLimit=t.gas,delete t.gas):t.gasLimit=await De(t,r)),"string"==typeof t.type&&qe(t.type)&&(t.type=Number(t.type)),[23294,23295].includes(t.chainId)&&(t.type=0),t=Ne(t.chainId)?await async function(e){if(!Ne(e.chainId))throw new Error("Invalid chain ID for Polygon gas estimation.");if(void 0===e.type&&(e.type=2),e.maxPriorityFeePerGas&&e.maxFeePerGas)return e;try{const{standard:t}=await Ge(e.chainId);e.maxPriorityFeePerGas||(e.maxPriorityFeePerGas=t.maxPriorityFee),e.maxFeePerGas||(e.maxFeePerGas=t.maxFee),e.gasPrice&&(console.warn("`gasPrice` is not supported on this chain and will be ignored. Use `maxPriorityFeePerGas` and/or `maxFeePerGas` instead."),delete e.gasPrice)}catch(e){throw new Error(`Failed to set gas prices from Polygon gas station with error: ${e}.`)}return e}(t):Pe(t.chainId)?await(async(e,t)=>{if(!Pe(e.chainId))throw new Error("Invalid chain ID for Arbitrum gas estimation.");if(void 0===e.type&&(e.type=2),e.maxFeePerGas)return e;try{const{lastBaseFeePerGas:r}=await t.getFeeData();if(r){const t=r.mul(i.BigNumber.from(120)).div(i.BigNumber.from(100));e.maxFeePerGas=Ee(t),e.maxPriorityFeePerGas=Ee(i.BigNumber.from(0))}}catch(e){throw new Error(`Failed to set gas price for Arbitrum transaction: ${e}.`)}return e})(t,r):Ue(t.chainId)?await(async(e,t)=>{if(!Ue(e.chainId))throw new Error("Invalid chain ID for OP Stack gas estimation.");if(void 0===e.type&&(e.type=2),e.gasPrice&&(console.warn("`gasPrice` is not supported on this chain and will be ignored. Use `maxPriorityFeePerGas` and/or `maxFeePerGas` instead."),delete e.gasPrice),e.maxPriorityFeePerGas&&e.maxFeePerGas)return e;try{if(!e.maxPriorityFeePerGas){const r=await t.send("eth_maxPriorityFeePerGas",[]);e.maxPriorityFeePerGas=r}if(e.maxFeePerGas&&(console.warn("maxFeePerGas is specified without maxPriorityFeePerGas - this can result in hung transactions."),e.maxPriorityFeePerGas>=e.maxFeePerGas))throw new Error("Overridden maxFeePerGas is less than or equal to the calculated maxPriorityFeePerGas. Please set both values or maxPriorityFeePerGas alone for correct gas estimation.");if(!e.maxFeePerGas){const{lastBaseFeePerGas:r}=await t.getFeeData();if(!r)throw new Error("Unable to fetch baseFee for last block.");const s=i.BigNumber.from(r).mul(i.BigNumber.from(126)).div(i.BigNumber.from(100)).add(i.BigNumber.from(e.maxPriorityFeePerGas));e.maxFeePerGas=Ee(s)}}catch(e){throw new Error(`Failed to set gas price for OP stack transaction: ${e}.`)}return e})(t,r):Te(t.chainId)?await(async(e,t)=>{if(!Te(e.chainId))throw new Error("Invalid chain ID for BSC gas estimation.");if(void 0===e.type?e.type=0:1!=e.type&&2!=e.type||console.warn("Transaction request type specified is incompatible for chain and will result in undefined behavior. Please use transaction type 0."),!e.gasPrice){const r=await t.getFeeData();e.gasPrice=r.gasPrice?.toHexString()}return e})(t,r):await(async(e,t)=>{if(void 0===e.type&&(e.type=2),2===e.type){if(!e.maxFeePerGas||!e.maxPriorityFeePerGas){const r=await t.getFeeData();e.maxFeePerGas||(e.maxFeePerGas=r.maxFeePerGas?.toHexString()),e.maxPriorityFeePerGas||(e.maxPriorityFeePerGas=r.maxPriorityFeePerGas?.toHexString())}}else if(!e.gasPrice){const r=await t.getFeeData();e.gasPrice=r.gasPrice?.toHexString()}return e})(t,r),0===t.type&&delete t.accessList,2!==t.type&&(delete t.maxPriorityFeePerGas,delete t.maxFeePerGas),t}function ze({currentRecoveryMethod:e,upgradeToRecoveryMethod:t}){switch(e){case"privy":case"user-passcode":return!0;case"icloud":case"google-drive":if(e===t)throw new Error("Cannot upgrade to the existing cloud platform");return!0;default:throw new Error("Unknown recovery method")}}class He extends _.default{_walletProxy;_privyInternal;_address;_chainId;_chains;_jsonRpcProvider;constructor({walletProxy:e,privyInternal:t,address:r,chains:s,chainId:a=s[0].id}){super(),this._walletProxy=e,this._privyInternal=t,this._address=r,this._chainId=a,this._chains=s,this._jsonRpcProvider=Me(a,s,{rpcUrls:[]},{appId:this._privyInternal.appId})}async request(e){if(t=e.method,ke.includes(t))return this.handleIFrameRpc(e);var t;switch(e.method){case"eth_accounts":case"eth_requestAccounts":return this._address?[this._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_sendTransaction":{const t=e.params?.[0];return this.handleSendTransaction(t)}case"eth_populateTransactionRequest":{const t=e.params?.[0];return this.handlePopulateTransaction(t)}default:return this.handleJsonRpc(e)}}ensureChainId(e){const t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),t}internalSwitchEthereumChain(e){e&&Number(e)!==this._chainId&&(this._chainId=Number(e),this._jsonRpcProvider=Me(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit("chainChanged",e))}async handlePopulateTransaction(e){const t=this.ensureChainId(e);return We(this._address,t,this._jsonRpcProvider)}async handleSendTransaction(e){const t=this.ensureChainId(e),r=await We(this._address,t,this._jsonRpcProvider),s=await this.handleIFrameRpc({method:"eth_signTransaction",params:[r]});return await this.handleJsonRpc({method:"eth_sendRawTransaction",params:[s]})}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw new Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;const t={...e.params[0],chainId:`0x${this._chainId.toString(16)}`};this.internalSwitchEthereumChain(t.chainId);try{return await this._jsonRpcProvider.send("eth_estimateGas",[t])}catch(e){console.warn(`Gas estimation failed with error: ${e}. Retrying gas estimation by omitting the 'from' address`);try{return delete t.from,await this._jsonRpcProvider.send("eth_estimateGas",[t])}catch(t){throw console.warn(`Gas estimation failed with error: ${t} when omitting the 'from' address`),e}}}handleSwitchEthereumChain(e){if(!e.params||!Array.isArray(e.params))throw new we(`Invalid params for ${e.method}`,4200);let t;if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new we(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{const t=await this._privyInternal.getAccessToken();if(!t)throw new Error("Missing privy token. User must be logged in");this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_started",{method:e.method,address:this._address});const r=await this._walletProxy.rpc({request:e,address:this._address,accessToken:t});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_completed",{method:e.method,address:this._address}),r.response.data}catch(t){console.error(t);const r=t instanceof Error?t.message:"Unable to make wallet request";throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_failed",{method:e.method,address:this._address,error:r}),new I({code:"embedded_wallet_request_error",error:r})}}async handleJsonRpc(e){return this._jsonRpcProvider.send(e.method,e.params??[])}toJSON(){return`PrivyEIP1193Provider { address: '${this._address}', chainId: ${this._chainId}, request: [Function] }`}}class $e{_walletProxy;_privyInternal;_publicKey;constructor({walletProxy:e,privyInternal:t,publicKey:r}){this._walletProxy=e,this._privyInternal=t,this._publicKey=r}async request(e){const t=await this._privyInternal.getAccessToken();if(!t)throw new I({error:"Missing access token",code:"attempted_rpc_call_before_logged_in"});return(await this._walletProxy.solanaRpc({accessToken:t,request:e,publicKey:this._publicKey})).response.data}}function Be(e){return void 0!==e.error}const Je=(Ke=0,()=>"id-"+Ke++);var Ke;const Ve=(e,t)=>"bigint"==typeof t?t.toString():t,Ye=e=>new Promise((t=>{setTimeout(t,e)})),Qe=(e,{ms:t,msg:r})=>Promise.race([e,new Promise(((e,s)=>{setTimeout((()=>{s(new Error(r))}),t??15e3)}))]),Ze=new class{callbacks={};enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){const r=this.callbacks[t];if(!r)throw new Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:wallet:create":case"privy:wallet:connect":case"privy:wallet:recover":case"privy:wallet:rpc":case"privy:wallet:set-recovery":case"privy:solana-wallet:create":case"privy:solana-wallet:connect":case"privy:solana-wallet:recover":case"privy:solana-wallet:rpc":return r;default:throw new Error(`invalid wallet event type ${e}`)}}};class Xe{ready;cache;_embeddedWalletMessagePoster;constructor(e){this.ready=!1,this.cache=new Map,this._embeddedWalletMessagePoster=e}ping(e=15e3){return Qe(this.invoke("privy:iframe:ready",{},this._embeddedWalletMessagePoster),{msg:"Ping reached timeout",ms:e})}create(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connect(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recover(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}setRecovery(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:set-recovery",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: setRecovery",ms:6e4})}rpc(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:wallet:rpc",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: rpc"})}createSolana(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connectSolana(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recoverSolana(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}solanaRpc(e){return Qe(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:rpc",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: rpc"})}handleEmbeddedWalletMessages(e){switch(e.event){case"privy:iframe:ready":const t=Ze.dequeue(e.event,e.id);return Be(e)?t.reject(new _e(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":const r=Ze.dequeue(e.event,e.id);return Be(e)?r.reject(new _e(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:connect":const s=Ze.dequeue(e.event,e.id);return Be(e)?s.reject(new _e(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:recover":const a=Ze.dequeue(e.event,e.id);return Be(e)?a.reject(new _e(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:rpc":const i=Ze.dequeue(e.event,e.id);return Be(e)?i.reject(new _e(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:set-recovery":const n=Ze.dequeue(e.event,e.id);return Be(e)?n.reject(new _e(e.error.type,e.error.message)):n.resolve(e.data);case"privy:solana-wallet:create":const o=Ze.dequeue(e.event,e.id);return Be(e)?o.reject(new _e(e.error.type,e.error.message)):o.resolve(e.data);case"privy:solana-wallet:connect":const c=Ze.dequeue(e.event,e.id);return Be(e)?c.reject(new _e(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:recover":const l=Ze.dequeue(e.event,e.id);return Be(e)?l.reject(new _e(e.error.type,e.error.message)):l.resolve(e.data);case"privy:solana-wallet:rpc":const d=Ze.dequeue(e.event,e.id);return Be(e)?d.reject(new _e(e.error.type,e.error.message)):d.resolve(e.data)}}waitForReady(){return this.ready?Promise.resolve():new Promise((async(e,t)=>{for(;!this.ready;)this.invoke("privy:iframe:ready",{},this._embeddedWalletMessagePoster).then((()=>{this.ready=!0,e()})).catch(t),await Ye(150)}))}invoke(e,t,r){const s=((e,t)=>`${e}${JSON.stringify(t,Ve)}`)(e,t);if("privy:wallet:create"===e||"privy:solana-wallet:create"===e){const e=this.cache.get(s);if(e)return e}const a=new Promise(((s,a)=>{const i=Je();Ze.enqueue(i,{resolve:s,reject:a}),r.postMessage(JSON.stringify({id:i,event:e,data:t}),"*")})).finally((()=>{this.cache.delete(s)}));return this.cache.set(s,a),a}}class et{_privyInternal;_proxy;_chains=Array.from(de);constructor(e,t,r){this._privyInternal=e,t&&(this._proxy=new Xe(t)),r&&(this._chains=r)}setMessagePoster(e){this._proxy=new Xe(e)}async create(e,t,r,s,a){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");let i;if(i=t||(e?"user-passcode":"privy"),e&&"string"!=typeof e)throw new Error("Invalid recovery password, must be a string");if("privy"===i&&this._privyInternal.config?.embedded_wallet_config.require_user_password_on_create)throw new Error("Password not provided yet is required by App configuration");const n=await this._privyInternal.getAccessToken();if(!n)throw new Error("User must be logged in to create an embedded wallet");const{address:o}=await this._proxy.create({accessToken:n,recoveryMethod:i,recoveryPassword:e,recoveryAccessToken:r,recoverySecretOverride:s,iCloudRecordNameOverride:a});if(!o)throw new Error("Failed to create wallet");const{user:c}=await this._privyInternal.refreshSession();return{user:c,provider:new He({address:o,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}}async createSolana(e){if(!this._proxy)throw new I({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_creation_error"});const t=await this._privyInternal.getAccessToken();if(!t)throw new I({error:"User must be logged in to create an embedded wallet",code:"embedded_wallet_creation_error"});if(e?.ethereumAccount){if("privy"!==e.ethereumAccount.recovery_method)throw new I({error:"Cannot create Solana wallet for user with Ethereum wallet with user-controlled recovery",code:"embedded_wallet_creation_error"});await this.getProvider(e.ethereumAccount)}const{publicKey:r}=await this._proxy.createSolana({accessToken:t,ethereumAddress:e?.ethereumAccount?.address});if(!r)throw new I({error:"Failed to create wallet",code:"embedded_wallet_creation_error"});return this._privyInternal.callbacks?.setUser&&await this._privyInternal.refreshSession(),new $e({publicKey:r,privyInternal:this._privyInternal,walletProxy:this._proxy})}async hasEmbeddedWallet(){const{user:e,token:t}=await this._privyInternal.refreshSession();if(!e||!t)throw new Error("User must be logged in to interact with embedded wallets");return!!this._getEmbeddedWallet(e)}async isPasswordRequired(){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const{user:e,token:t}=await this._privyInternal.refreshSession();if(!e||!t)throw new Error("User must be logged in to interact with embedded wallets");const r=this._getEmbeddedWallet(e);if(!r)return!1;if("privy"===r.recovery_method)return!1;try{return await this._proxy.connect({accessToken:t,address:r.address}),!1}catch(e){return fe(e)}}async getProvider(e,t,r,s){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const a=await this._load(e,t,r,s);return new He({address:a,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}async getSolanaProvider(e){if(!this._proxy)throw new I({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_webview_not_loaded"});const t=await this._loadSolana(e);return new $e({publicKey:t,privyInternal:this._privyInternal,walletProxy:this._proxy})}async setPassword(e,t){const{provider:r}=await this.setRecovery({wallet:e,recoveryMethod:"user-passcode",password:t});return r}async setRecovery({wallet:e,...t}){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");ze({currentRecoveryMethod:e.recovery_method,upgradeToRecoveryMethod:"icloud-native"===t.recoveryMethod?"icloud":t.recoveryMethod});const r=await this._load(e),s=await this._privyInternal.getAccessToken();if(!s)throw new Error("User must be logged in to interact with embedded wallets");const a=e.recovery_method;this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_set_recovery_started",{address:e.address,target_recovery_method:t.recoveryMethod,existing_recovery_method:a});try{await this._proxy.setRecovery({accessToken:s,address:r,recoveryMethod:t.recoveryMethod,recoveryPassword:"user-passcode"===t.recoveryMethod?t.password:void 0,recoveryAccessToken:"google-drive"===t.recoveryMethod||"icloud"===t.recoveryMethod?t.recoveryAccessToken:void 0,recoverySecretOverride:"icloud-native"===t.recoveryMethod?t.recoverySecretOverride:void 0,iCloudRecordNameOverride:"icloud-native"===t.recoveryMethod?t.iCloudRecordNameOverride:void 0}),this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_set_recovery_completed",{address:e.address,target_recovery_method:t.recoveryMethod,existing_recovery_method:a});const{user:i}=await this._privyInternal.refreshSession();return{user:i,provider:new He({address:r,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}}catch(t){throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_set_recovery_failed",{address:e.address,recovery_method:e.recovery_method,error:t instanceof Error?t.message:"Unable to recover wallet"}),t}}getURL(){const 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}getMessageHandler(){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");return this._proxy.handleEmbeddedWalletMessages.bind(this._proxy)}onMessage(e){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");return this._proxy.handleEmbeddedWalletMessages(e)}async ping(e){try{if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");return await this._proxy.ping(e),!0}catch(e){return console.error(e),!1}}async _load(e,t,r,s){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const a=await this._privyInternal.getAccessToken();if(!a)throw new Error("User must be logged in to interact with embedded wallets");const i=e.address;try{return await this._proxy.connect({accessToken:a,address:i}),i}catch(n){if(fe(n)){try{if("privy"===e.recovery_method){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:e.recovery_method});const t=await this._proxy.recover({accessToken:a,address:i});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:e.recovery_method}),t.address}if("user-passcode"===e.recovery_method&&t){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:e.recovery_method});const r=await this._proxy.recover({accessToken:a,address:i,recoveryPassword:t});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:e.recovery_method}),r.address}if(["google-drive","icloud"].includes(e.recovery_method)&&r){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:e.recovery_method});const t=await this._proxy.recover({accessToken:a,address:i,recoveryAccessToken:r});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:e.recovery_method}),t.address}if("icloud"===e.recovery_method&&s){this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_started",{address:e.address,recovery_method:"icloud-native"});const t=await this._proxy.recover({accessToken:a,address:i,recoverySecretOverride:s});return this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_completed",{address:e.address,recovery_method:"icloud-native"}),t.address}}catch(t){throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_recovery_failed",{address:e.address,recovery_method:e.recovery_method,error:t instanceof Error?t.message:"Unable to recover wallet"}),t}throw n}throw n}}async _loadSolana(e){if(!this._proxy)throw new Error("Embedded wallet proxy not initialized");const t=await this._privyInternal.getAccessToken();if(!t)throw new Error("User must be logged in to interact with embedded wallets");const r=e.public_key;try{return await this._proxy.connectSolana({accessToken:t,publicKey:r}),r}catch(e){if(fe(e)){return(await this._proxy.recoverSolana({accessToken:t,publicKey:r})).publicKey}throw e}}_getEmbeddedWallet(e){return e?.linked_accounts.find((e=>"wallet"===e.type&&"embedded"===e.connector_type&&"privy"===e.wallet_client_type))}}class tt{static parse(e){try{return new tt(e)}catch(e){return null}}value;_decoded;constructor(e){this.value=e,this._decoded=m.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()>=1e3*(this.expiration-e)}}const rt="privy:token",st="privy-token",at="privy:refresh_token",it="privy-refresh-token",nt="privy:id-token",ot="privy-id-token",ct="privy-session",lt="privy:session_transfer_token",dt=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","forked_token_cleared","token_stored","refresh_token_stored","identity_token_stored"];class ht extends _.default{static events=dt;_storage;_isUsingServerCookies=!1;constructor(e){super(),this._storage=e.storage}set isUsingServerCookies(e){this._isUsingServerCookies=e}async getToken(){const e=await this._storage.get(rt);try{return"string"==typeof e?new tt(e).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getRefreshToken(){try{const e=await this._storage.get(at);return"string"==typeof e?e:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getRefreshToken_error"}),null}}async getIdentityToken(){try{const e=await this._storage.get(nt);return"string"==typeof e?e:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getIdentityToken_error"}),null}}async getForkedToken(){try{const e=await this._storage.get(lt);return"string"==typeof e?e:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getForkedToken_error"}),null}}get mightHaveServerCookies(){try{const e=w.default.get(ct);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e,t){return this.mightHaveServerCookies||"string"==typeof e&&"string"==typeof t}async hasRecoveryCredentials(){return"string"==typeof await this.getForkedToken()}tokenIsActive(e){if(!e)return!1;const t=tt.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){const t=await Promise.all([this._storage.del(rt),this._storage.del(at),this._storage.del(nt),this.clearForkedToken()]);return e?.reason&&this.emit("storage_cleared",{reason:e.reason}),t}async storeToken(e){if("string"==typeof e){const t=await this._storage.get(rt);if(await this._storage.put(rt,e),!this._isUsingServerCookies){const t=tt.parse(e)?.expiration;w.default.set(st,e,{sameSite:"Strict",secure:!0,expires:t?new Date(1e3*t):void 0})}t!==e&&this.emit("token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{const e=await this._storage.get(rt);await this._storage.del(rt),w.default.remove(st),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storeRefreshToken(e){"string"==typeof e?(await this._storage.put(at,e),this._isUsingServerCookies||(w.default.set(ct,"t",{sameSite:"Strict",secure:!0,expires:30}),w.default.set(it,e,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(at),w.default.remove(it),w.default.remove(ct),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async storeIdentityToken(e){if("string"==typeof e){const t=await this._storage.get(nt);if(await this._storage.put(nt,e),!this._isUsingServerCookies){const t=tt.parse(e)?.expiration;w.default.set(ot,e,{sameSite:"Strict",secure:!0,expires:t?new Date(1e3*t):void 0})}t!==e&&this.emit("identity_token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{const e=await this._storage.get(nt);await this._storage.del(nt),w.default.remove(ot),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async clearForkedToken(){await this._storage.del(lt)}}const pt=e=>{const t=new AbortController;return setTimeout((()=>t.abort()),e),t.signal},yt="privy:caid";class ut{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.26.3";_fetch;nativeAppIdentifier;callbacks;_cache=new Map;session;constructor(e){this._storage=e.storage,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,"undefined"==typeof document&&(this.nativeAppIdentifier=e.nativeAppIdentifier),this.session=new ht({storage:this._storage,isUsingServerCookies:!1}),this._fetch=v.default(fetch,{retries:3,retryDelay:500})}get isReady(){return Boolean(this._config)}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){this.isReady||(this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.callbacks?.setIsReady?.(!0),this.createAnalyticsEvent("sdk_initialize",{}))}async fetch(t,{body:r,params:s,headers:a,options:i={onRequest:this._beforeRequest.bind(this)}}){const n=`${this.baseUrl}${e.getPathWithParams(t.path,s)}`,o=new Request(n,{method:t.method,body:JSON.stringify(r),headers:a}),c=await i.onRequest(o),l=await this._fetch(o,c),d=await l.json();if(l.status>299)throw new k(d);return d}async _beforeRequestWithoutInitialize(e){const t=await this.session.getToken(),r=new Headers(e.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-client",this._sdkVersion),r.set("Authorization",`Bearer ${t}`),r.set("Content-Type","application/json"),r.set("Accept","application/json");const s=await this._getOrGenerateClientAnalyticsId();return s&&r.set("privy-ca-id",s),this.nativeAppIdentifier&&r.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:pt(2e4),headers:r,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(e.AppConfig,{params:{app_id:this.appId},options:{onRequest:this._beforeRequestWithoutInitialize.bind(this)}})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{const e=await this._storage.get(yt);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){console.error("Unable to load clientId",e)}try{this._analyticsId=d.v4()}catch(e){console.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(yt,this._analyticsId)}catch(e){console.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(yt)}catch(e){console.error("Unable to delete clientId",e)}}async createAnalyticsEvent(t,r){try{await this.fetch(e.AnalyticsEvent,{body:{event_name:t,client_id:await this._getOrGenerateClientAnalyticsId(),payload:r},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}catch(e){}}async refreshSession(){const e=await this.session.getRefreshToken()??void 0,t=e??"key",r=this._cache.get(t);if(r)return await r;const s=this._refreshSession(e);this._cache.set(t,s);try{return await s}catch(e){throw e}finally{this._cache.delete(t)}}async _refreshSession(t){const r=await this.session.getToken();if(!this.session.hasRefreshCredentials(r,t??null))throw await this._initialize(),new Error("missing_or_invalid_token");try{const{session_update_action:r,...s}=await this.fetch(e.RefreshSession,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}});return this.callbacks?.setUser?.(s.user),"set"===r&&await Promise.all([this.session.storeToken(s.token),this.session.storeRefreshToken(s.refresh_token),this.session.storeIdentityToken(s.identity_token)]),"clear"===r&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===r&&s.token&&(await this.session.storeToken(s.token),s.identity_token&&await this.session.storeIdentityToken(s.identity_token)),s}catch(e){throw(e instanceof k&&e.code===h.PrivyErrorCode.MISSING_OR_INVALID_TOKEN||e instanceof Error&&"missing_or_invalid_token"===e.message)&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),e}}async getAccessToken(){const[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t))try{return await this.refreshSession(),await this.session.getToken()}catch(e){return null}return e}async getIdentityToken(){return await this.session.getIdentityToken()}}class mt{_privyInternal;constructor(e){this._privyInternal=e}async init(t){return this._privyInternal.fetch(e.RecoveryOAuthInitICloud,{body:{client_type:t}})}async getICloudConfiguration(t){return this._privyInternal.fetch(e.RecoveryConfigurationICloud,{body:{client_type:t}})}}class _t{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t){const r=P(),s=T(),a=await S({codeVerifier:r,digest:this._crypto?.digest});return await Promise.all([this._storage.put(x,r),this._storage.put(E,s)]),this._privyInternal.fetch(e.RecoveryOAuthInit,{body:{redirect_to:t,code_challenge:a,state_code:s}})}async authorize(t,r){const[s,a]=await Promise.all([this._storage.get(x),this._storage.get(E)]);if(a!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"recovery_oauth",storedStateCode:a??"",returnedStateCode:r??""}),new I({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});const i=await this._privyInternal.fetch(e.RecoveryOAuthAuthenticate,{body:{authorization_code:t,state_code:a,code_verifier:s}});return await Promise.all([this._storage.del(x),this._storage.del(E)]),i}}class vt{_privyInternal;auth;icloudAuth;constructor(e,t,r){this._privyInternal=e,this.auth=new _t(this._privyInternal,t,r),this.icloudAuth=new mt(this._privyInternal)}async getRecoveryKeyMaterial(t,r){return this._privyInternal.fetch(e.RecoveryKeyMaterial,{body:{chain_type:r},params:{address:t}})}}class wt{_privyInternal;constructor(e){this._privyInternal=e}async get(){try{const{user:e}=await this._privyInternal.refreshSession();return{user:e}}catch(e){throw e}}}const gt=["metamask","phantom","brave_wallet","rainbow","coinbase_wallet","metamask","trust","safe","rainbow","uniswap","zerion","argent","spot","omni","cryptocom","blockchain","safepal","bitkeep","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","privy","unknown"];exports.ALL_WALLET_CLIENT_TYPES=gt,exports.DEFAULT_SUPPORTED_CHAINS=de,exports.DEFAULT_SUPPORTED_CHAIN_IDS=he,exports.EmbeddedProviderError=we,exports.InMemoryCache=class{_cache={};get(e){return this._cache[e]}put(e,t){void 0!==t?this._cache[e]=t:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}},exports.LocalStorage=class{async get(e){const t=localStorage.getItem(e);return null===t?void 0:JSON.parse(t)}put(e,t){void 0!==t?localStorage.setItem(e,JSON.stringify(t)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map((([e])=>e))}},exports.PrivyApiError=k,exports.PrivyClientError=I,exports.PrivyConnectorError=ve,exports.PrivyProviderRpcError=be,exports.ProviderErrors=ge,exports.QuantityToBigNumber=Ie,exports.SUPPORTED_CONNECTOR_TYPES=["injected","wallet_connect","wallet_connect_v2","coinbase_wallet","embedded"],exports.calculateTotalGasEstimate=async function(e,t){if(!e.gasLimit)throw new be("gasLimit was not successfully set for transaction.");const r=Ie(e.gasLimit);let s=i.BigNumber.from(0);if(2==e.type){if(!e.maxFeePerGas)throw new be("maxFeePerGas was not successfully set for transaction of type 2.");s=Ie(e.maxFeePerGas)}else{if(!e.gasPrice)throw new be("gasPrice was not successfully set for transaction of type 0 or 1.");s=Ie(e.gasPrice)}let a=r.mul(s),c=i.BigNumber.from(0);if(e.chainId&&Ue(e.chainId))try{c=await async function(e,t){if(!e.chainId||e.chainId&&!Ue(e.chainId))return i.BigNumber.from(0);let r=i.BigNumber.from(0);try{const s=new n.Contract(Re,Ae,t),a=xe(e),i=o.serialize(a);r=await s.getL1Fee(i)}catch(e){}return r}(e,t),a=a.add(c)}catch(e){}return{totalGasEstimate:a,l1ExecutionFeeEstimate:c}},exports.chainDefs=le,exports.convertBigNumberish=Ee,exports.default=class{auth;user;embeddedWallet;recovery;_privyInternal;constructor({clientId:e,...t}){this._privyInternal=new ut({...t,appClientId:e}),this.user=new wt(this._privyInternal),this.auth=new F(this._privyInternal,t.storage,t.crypto),this.embeddedWallet=new et(this._privyInternal,t.embeddedWalletMessagePoster,t.supportedChains),this.recovery=new vt(this._privyInternal,t.storage,t.crypto)}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}getAccessToken(){return this._privyInternal.getAccessToken()}getIdentityToken(){return this._privyInternal.getIdentityToken()}},exports.errorIndicatesRecoveryIsNeeded=fe,exports.getUserEmbeddedSolanaWallet=e=>{if(!e)return null;const t=e.linked_accounts.find((e=>"wallet"===e.type&&"privy"===e.wallet_client_type&&"embedded"===e.connector_type&&"solana"===e.chain_type));return t||null},exports.getUserEmbeddedWallet=e=>{if(!e)return null;const t=e.linked_accounts.find((e=>"wallet"===e.type&&"privy"===e.wallet_client_type&&"embedded"===e.connector_type&&"ethereum"===e.chain_type));return t||null},exports.populateTransactionRequest=We,exports.throwIfInvalidRecoveryUpgradePath=ze,exports.toEthersUnsignedTransaction=xe,exports.toObjectKeys=(e,t=!0)=>e.reduce(((e,r)=>({...e,[r]:t})),{});
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@privy-io/js-sdk-core",
|
|
3
|
-
"version": "0.26.
|
|
3
|
+
"version": "0.26.3",
|
|
4
4
|
"description": "Vanilla JS client for the Privy Auth API",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"keywords": [
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
"@ethersproject/transactions": "^5.7.0",
|
|
67
67
|
"@ethersproject/units": "^5.7.0",
|
|
68
68
|
"@privy-io/api-base": "^1.2.2",
|
|
69
|
-
"@privy-io/public-api": "2.
|
|
69
|
+
"@privy-io/public-api": "2.9.0",
|
|
70
70
|
"eventemitter3": "^5.0.1",
|
|
71
71
|
"fetch-retry": "^5.0.6",
|
|
72
72
|
"jose": "^4.15.5",
|