@privy-io/js-sdk-core 0.28.1 → 0.28.2-beta-20240920184838

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1 +1 @@
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 u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function y(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=y(t),_=u(r),v=u(l),w=u(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 this._privyInternal.session.updateWithTokensResponse(r),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,s){const a=await this._privyInternal.fetch(e.PasswordlessAuthenticate,{body:{email:t,code:r,mode:s}});return await this._privyInternal.session.updateWithTokensResponse(a),this._privyInternal.callbacks?.setUser?.(a.user),a}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,mode:i}){const n=await this._privyInternal.fetch(e.FarcasterAuthenticate,{body:{channel_token:t,message:r,signature:s,fid:a,mode:i}});return await this._privyInternal.session.updateWithTokensResponse(n),this._privyInternal.callbacks?.setUser?.(n.user),n}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 E{_privyInternal;constructor(e){this._privyInternal=e}async create(){const t=await this._privyInternal.session.getOrCreateGuestCredential(),r=await this._privyInternal.fetch(e.GuestAuthenticate,{body:{guest_credential:t}});return await this._privyInternal.session.updateWithTokensResponse(r),this._privyInternal.callbacks?.setUser?.(r.user),r}}class I extends Error{error;code;constructor({error:e,code:t}){super(e),this.error=e,this.code=t}}class k extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}}const x="privy:state_code",P="privy:code_verifier";function T(){return t.base64url.encode((e=36,crypto.getRandomValues(new Uint8Array(e))));var e}function S(){return T()}async function C({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 R{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t,r){const s=T(),a=S(),i=await C({codeVerifier:s,digest:this._crypto?.digest});return await Promise.all([this._storage.put(P,s),this._storage.put(x,a)]),this._privyInternal.fetch(e.OAuthInit,{body:{redirect_to:r,provider:t,code_challenge:i,state_code:a}})}async loginWithCode(t,r,s,a,i){const[n,o]=await Promise.all([this._storage.get(P),this._storage.get(x)]);if(o!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:o??"",returnedStateCode:r??""}),new k({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});const c=await this._privyInternal.fetch(e.OAuthAuthenticate,{body:{authorization_code:t,code_type:a,state_code:o,code_verifier:n,mode:i}});return await this._privyInternal.session.updateWithTokensResponse(c),this._privyInternal.callbacks?.setUser?.(c.user),await Promise.all([this._storage.del(P),this._storage.del(x)]),c}async linkWithCode(t,r,s,a){const[i,n]=await Promise.all([this._storage.get(P),this._storage.get(x)]);if(n!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:n??"",returnedStateCode:r??""}),new k({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(P),this._storage.del(x)]),o.user}async unlink(t,r){await this._privyInternal.fetch(e.OAuthUnlink,{body:{provider:t,subject:r}});return(await this._privyInternal.refreshSession()).user}}class A{_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 this._privyInternal.session.updateWithTokensResponse(a),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 U{_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,s){const a=await this._privyInternal.fetch(e.PasswordlessSmsAuthenticate,{body:{phoneNumber:t,code:r,mode:s}});return await this._privyInternal.session.updateWithTokensResponse(a),this._privyInternal.callbacks?.setUser?.(a.user),a}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 O{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async unlinkWallet(t){try{await this._privyInternal.fetch(e.SiweUnlink,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}catch(e){throw 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,a){const i=r||this._wallet,n=s||this._preparedMessage;if(!i)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!n)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:n,chainId:i.chainId,walletClientType:i.walletClientType,connectorType:i.connectorType,mode:a}});return await this._privyInternal.session.updateWithTokensResponse(r),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;guest;constructor(e,t,r){this._privyInternal=e,this.customProvider=new g(this._privyInternal),this.phone=new U(this._privyInternal),this.email=new f(this._privyInternal),this.oauth=new R(this._privyInternal,t,r),this.guest=new E(this._privyInternal),this.siwe=new O(this._privyInternal),this.passkey=new A(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 N={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"}}},L={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},G={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},D={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"}}},q={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"}}},W={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},z={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},H={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},$={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"}}},B={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"}}},K={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},V={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"}}},Y={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},Q={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},Z={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"}}},X={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"}}},ee={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},te={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},re={id:137,name:"Polygon Mainnet",network:"polygon",nativeCurrency:{name:"POL",symbol:"POL",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"}}},se={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},ae={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/"}}},ie={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"}}},ne={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},oe={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"}}},ce={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},le={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},de={mainnet:Z,goerli:J,sepolia:ne,arbitrum:N,arbitrumGoerli:L,arbitrumSepolia:G,optimism:X,optimismGoerli:ee,optimismSepolia:te,polygon:re,polygonMumbai:se,celo:z,celoAlfajores:H,filecoin:$,filecoinCalibration:B,base:M,baseGoerli:W,baseSepolia:j,linea:Y,lineaTestnet:Q,avalanche:D,avalancheFuji:q,holesky:V,redstone:ae,garnetHolesky:K,redstoneHolesky:ie,zora:oe,zoraSepolia:ce,zoraTestnet:le},he=[Z,J,ne,N,L,G,X,ee,te,re,se,z,H,$,B,M,W,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},Y,Q,D,q,V,ae,K,ie,oe,ce,le],pe=new Set(he.map((e=>e.id))),ue=["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 me 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 _e extends me{type="provider_error";code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}class ve extends Error{type;constructor(e,t){super(t),this.type=e}}class we extends me{type="connector_error";constructor(e,t,r){super(e,t,r)}}class ge extends Error{code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}const fe={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 be(e){return function(e){const t=e.type;return"string"==typeof t&&ue.includes(t)}(e)&&"wallet_not_on_device"===e.type}class Ee extends _e{details;constructor(e){const t=e;super(t.message,t.code,t.data);const r=Object.values(fe).find((e=>e.eipCode===t.code));this.details=r||fe.UNKNOWN_ERROR,-32002===t.code&&(t.message?.includes("already pending for origin")?t.message?.includes("wallet_requestPermissions")?this.details=fe.E32002_CONNECTION_ALREADY_PENDING:this.details=fe.E32002_REQUEST_ALREADY_PENDING:t.message?.includes("Already processing")&&t.message.includes("eth_requestAccounts")&&(this.details=fe.E32002_WALLET_LOCKED))}}const Ie=["eth_sign","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation"],ke=e=>i.BigNumber.from(e);function xe(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 Pe(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=ke(e.nonce).toNumber()),void 0!==e.gasLimit&&(t.gasLimit=ke(e.gasLimit)),void 0!==e.gasPrice&&(t.gasPrice=ke(e.gasPrice)),void 0!==e.value&&(t.value=ke(e.value)),void 0!==e.maxFeePerGas&&(t.maxFeePerGas=ke(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=ke(e.maxPriorityFeePerGas)),t}const Te=e=>[N.id,L.id,G.id].includes(e),Se=e=>[56,97].includes(e),Ce=81457,Re=168587773,Ae="0x420000000000000000000000000000000000000F",Ue=["function getL1Fee(bytes memory _data) external view returns (uint256)"],Oe=e=>[M.id,W.id,j.id,X.id,ee.id,te.id,oe.id,le.id,ce.id,Ce,Re].includes(e);const Fe={id:80002,name:"Polygon Amoy",network:"polygon-amoy",nativeCurrency:{name:"POL",symbol:"POL",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},Ne=v.default(fetch,{retries:3,retryDelay:500}),Le=e=>[re.id,se.id,Fe.id].includes(e),Ge=e=>({maxPriorityFee:c.parseUnits(e.maxPriorityFee.toFixed(9),"gwei").toHexString(),maxFee:c.parseUnits(e.maxFee.toFixed(9),"gwei").toHexString()}),De=async e=>{let t="";switch(e){case re.id:t="https://gasstation.polygon.technology/v2";break;case se.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 Ne(t),s=await r.json();if(r.status>399)throw s;return{safeLow:Ge((a=s).safeLow),standard:Ge(a.standard),fast:Ge(a.fast)};var a};async function qe(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 we(`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 we(`No RPC url found for ${e}`);return o};function We(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&&We(e);return t||r||s}async function ze(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 qe(t,r)),"string"==typeof t.type&&We(t.type)&&(t.type=Number(t.type)),[23294,23295].includes(t.chainId)&&(t.type=0),t=Le(t.chainId)?await async function(e){if(!Le(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 De(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):Te(t.chainId)?await(async(e,t)=>{if(!Te(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=xe(t),e.maxPriorityFeePerGas=xe(i.BigNumber.from(0))}}catch(e){throw new Error(`Failed to set gas price for Arbitrum transaction: ${e}.`)}return e})(t,r):Oe(t.chainId)?await(async(e,t)=>{if(!Oe(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=xe(s)}}catch(e){throw new Error(`Failed to set gas price for OP stack transaction: ${e}.`)}return e})(t,r):Se(t.chainId)?await(async(e,t)=>{if(!Se(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 He({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 $e 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,Ie.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 ze(this._address,t,this._jsonRpcProvider)}async handleSendTransaction(e){const t=this.ensureChainId(e),r=await ze(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 ge(`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 ge(`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 k({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 Be{_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 k({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 Ke(e){return void 0!==e.error}const Je=(Ve=0,()=>"id-"+Ve++);var Ve;const Ye=(e,t)=>"bigint"==typeof t?t.toString():t,Qe=e=>new Promise((t=>{setTimeout(t,e)})),Ze=(e,{ms:t,msg:r})=>Promise.race([e,new Promise(((e,s)=>{setTimeout((()=>{s(new Error(r))}),t??15e3)}))]),Xe=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 et{ready;cache;_embeddedWalletMessagePoster;constructor(e){this.ready=!1,this.cache=new Map,this._embeddedWalletMessagePoster=e}ping(e=15e3){return Ze(this.invoke("privy:iframe:ready",{},this._embeddedWalletMessagePoster),{msg:"Ping reached timeout",ms:e})}create(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connect(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recover(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}setRecovery(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:set-recovery",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: setRecovery",ms:6e4})}rpc(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:rpc",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: rpc"})}createSolana(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connectSolana(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recoverSolana(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}solanaRpc(e){return Ze(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=Xe.dequeue(e.event,e.id);return Ke(e)?t.reject(new ve(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":const r=Xe.dequeue(e.event,e.id);return Ke(e)?r.reject(new ve(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:connect":const s=Xe.dequeue(e.event,e.id);return Ke(e)?s.reject(new ve(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:recover":const a=Xe.dequeue(e.event,e.id);return Ke(e)?a.reject(new ve(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:rpc":const i=Xe.dequeue(e.event,e.id);return Ke(e)?i.reject(new ve(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:set-recovery":const n=Xe.dequeue(e.event,e.id);return Ke(e)?n.reject(new ve(e.error.type,e.error.message)):n.resolve(e.data);case"privy:solana-wallet:create":const o=Xe.dequeue(e.event,e.id);return Ke(e)?o.reject(new ve(e.error.type,e.error.message)):o.resolve(e.data);case"privy:solana-wallet:connect":const c=Xe.dequeue(e.event,e.id);return Ke(e)?c.reject(new ve(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:recover":const l=Xe.dequeue(e.event,e.id);return Ke(e)?l.reject(new ve(e.error.type,e.error.message)):l.resolve(e.data);case"privy:solana-wallet:rpc":const d=Xe.dequeue(e.event,e.id);return Ke(e)?d.reject(new ve(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 Qe(150)}))}invoke(e,t,r){const s=((e,t)=>`${e}${JSON.stringify(t,Ye)}`)(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();Xe.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 tt{_privyInternal;_proxy;_chains=Array.from(he);constructor(e,t,r){this._privyInternal=e,t&&(this._proxy=new et(t)),r&&(this._chains=r)}setMessagePoster(e){this._proxy=new et(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 $e({address:o,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}}async createSolana(e){if(!this._proxy)throw new k({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_creation_error"});const t=await this._privyInternal.getAccessToken();if(!t)throw new k({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 k({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 k({error:"Failed to create wallet",code:"embedded_wallet_creation_error"});return this._privyInternal.callbacks?.setUser&&await this._privyInternal.refreshSession(),new Be({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 be(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 $e({address:a,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}async getSolanaProvider(e){if(!this._proxy)throw new k({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_webview_not_loaded"});const t=await this._loadSolana(e);return new Be({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");He({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 $e({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(be(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(be(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 rt{static parse(e){try{return new rt(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 st="privy:token",at="privy-token",it="privy:refresh_token",nt="privy-refresh-token",ot="privy:id-token",ct="privy-id-token",lt="privy-session",dt="privy:session_transfer_token",ht=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","forked_token_cleared","token_stored","refresh_token_stored","identity_token_stored","oauth_tokens_granted"];class pt extends _.default{static events=ht;_storage;_isUsingServerCookies=!1;GUEST_CREDENTIAL_STORAGE_KEY;constructor(e){super(),this._storage=e.storage,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`}set isUsingServerCookies(e){this._isUsingServerCookies=e}async getToken(){const e=await this._storage.get(st);try{return"string"==typeof e?new rt(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(it);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(ot);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(dt);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(lt);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=rt.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){const t=await Promise.all([this._storage.del(st),this._storage.del(it),this._storage.del(ot),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),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(st);if(await this._storage.put(st,e),!this._isUsingServerCookies){const t=rt.parse(e)?.expiration;w.default.set(at,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(st);await this._storage.del(st),w.default.remove(at),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storeRefreshToken(e){"string"==typeof e?(await this._storage.put(it,e),this._isUsingServerCookies||(w.default.set(lt,"t",{sameSite:"Strict",secure:!0,expires:30}),w.default.set(nt,e,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(it),w.default.remove(nt),w.default.remove(lt),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async updateWithTokensResponse(e){await Promise.all([this.storeToken(e.token),this.storeRefreshToken(e.refresh_token),this.storeIdentityToken(e.identity_token),this.processOAuthTokens(e.oauth_tokens)])}async processOAuthTokens(e){e&&this.emit("oauth_tokens_granted",e)}async storeIdentityToken(e){if("string"==typeof e){const t=await this._storage.get(ot);if(await this._storage.put(ot,e),!this._isUsingServerCookies){const t=rt.parse(e)?.expiration;w.default.set(ct,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(ot);await this._storage.del(ot),w.default.remove(ct),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async getOrCreateGuestCredential(){const e=this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&"string"==typeof e)return e;const r=t.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,r),r}async clearForkedToken(){await this._storage.del(dt)}}const ut=e=>{const t=new AbortController;return setTimeout((()=>t.abort()),e),t.signal},yt="privy:caid";class mt{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.28.1";_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 pt({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),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 I(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:ut(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 r=await this.fetch(e.RefreshSession,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=r.session_update_action;return this.callbacks?.setUser?.(r.user),"set"===s&&await this.session.updateWithTokensResponse(r),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&r.token&&(await this.session.storeToken(r.token),r.identity_token&&await this.session.storeIdentityToken(r.identity_token)),r}catch(e){throw(e instanceof I&&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 _t{_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 vt{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t){const r=T(),s=S(),a=await C({codeVerifier:r,digest:this._crypto?.digest});return await Promise.all([this._storage.put(P,r),this._storage.put(x,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(P),this._storage.get(x)]);if(a!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"recovery_oauth",storedStateCode:a??"",returnedStateCode:r??""}),new k({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(P),this._storage.del(x)]),i}}class wt{_privyInternal;auth;icloudAuth;constructor(e,t,r){this._privyInternal=e,this.auth=new vt(this._privyInternal,t,r),this.icloudAuth=new _t(this._privyInternal)}async getRecoveryKeyMaterial(t,r){return this._privyInternal.fetch(e.RecoveryKeyMaterial,{body:{chain_type:r},params:{address:t}})}}class gt{_privyInternal;constructor(e){this._privyInternal=e}async get(){try{const{user:e}=await this._privyInternal.refreshSession();return{user:e}}catch(e){throw e}}}const ft=["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=ft,exports.DEFAULT_SUPPORTED_CHAINS=he,exports.DEFAULT_SUPPORTED_CHAIN_IDS=pe,exports.EmbeddedProviderError=ge,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=I,exports.PrivyClientError=k,exports.PrivyConnectorError=we,exports.PrivyProviderRpcError=Ee,exports.ProviderErrors=fe,exports.QuantityToBigNumber=ke,exports.SUPPORTED_CONNECTOR_TYPES=["injected","wallet_connect","wallet_connect_v2","coinbase_wallet","embedded"],exports.calculateTotalGasEstimate=async function(e,t){if(!e.gasLimit)throw new Ee("gasLimit was not successfully set for transaction.");const r=ke(e.gasLimit);let s=i.BigNumber.from(0);if(2==e.type){if(!e.maxFeePerGas)throw new Ee("maxFeePerGas was not successfully set for transaction of type 2.");s=ke(e.maxFeePerGas)}else{if(!e.gasPrice)throw new Ee("gasPrice was not successfully set for transaction of type 0 or 1.");s=ke(e.gasPrice)}let a=r.mul(s),c=i.BigNumber.from(0);if(e.chainId&&Oe(e.chainId))try{c=await async function(e,t){if(!e.chainId||e.chainId&&!Oe(e.chainId))return i.BigNumber.from(0);let r=i.BigNumber.from(0);try{const s=new n.Contract(Ae,Ue,t),a=Pe(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=de,exports.convertBigNumberish=xe,exports.default=class{auth;user;embeddedWallet;recovery;_privyInternal;constructor({clientId:e,...t}){this._privyInternal=new mt({...t,appClientId:e}),this.user=new gt(this._privyInternal),this.auth=new F(this._privyInternal,t.storage,t.crypto),this.embeddedWallet=new tt(this._privyInternal,t.embeddedWalletMessagePoster,t.supportedChains),this.recovery=new wt(this._privyInternal,t.storage,t.crypto)}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}addOAuthTokensListener(e){return this._privyInternal.session.on("oauth_tokens_granted",e),{unsubscribe:()=>{this._privyInternal.session.removeListener("oauth_tokens_granted",e)}}}getAccessToken(){return this._privyInternal.getAccessToken()}getIdentityToken(){return this._privyInternal.getIdentityToken()}},exports.errorIndicatesRecoveryIsNeeded=be,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=ze,exports.throwIfInvalidRecoveryUpgradePath=He,exports.toEthersUnsignedTransaction=Pe,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 u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function y(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=y(t),_=u(r),v=u(l),w=u(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 this._privyInternal.session.updateWithTokensResponse(r),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,s){const a=await this._privyInternal.fetch(e.PasswordlessAuthenticate,{body:{email:t,code:r,mode:s}});return await this._privyInternal.session.updateWithTokensResponse(a),this._privyInternal.callbacks?.setUser?.(a.user),a}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,mode:i}){const n=await this._privyInternal.fetch(e.FarcasterAuthenticate,{body:{channel_token:t,message:r,signature:s,fid:a,mode:i}});return await this._privyInternal.session.updateWithTokensResponse(n),this._privyInternal.callbacks?.setUser?.(n.user),n}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 E{_privyInternal;constructor(e){this._privyInternal=e}async create(){const t=await this._privyInternal.session.getOrCreateGuestCredential(),r=await this._privyInternal.fetch(e.GuestAuthenticate,{body:{guest_credential:t}});return await this._privyInternal.session.updateWithTokensResponse(r),this._privyInternal.callbacks?.setUser?.(r.user),r}}class I extends Error{error;code;constructor({error:e,code:t}){super(e),this.error=e,this.code=t}}class k extends Error{error;code;constructor({error:e,code:t}){super(e),this.code=t,this.error=e}}const x="privy:state_code",P="privy:code_verifier";function T(){return t.base64url.encode((e=36,crypto.getRandomValues(new Uint8Array(e))));var e}function S(){return T()}async function C({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 R{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t,r){const s=T(),a=S(),i=await C({codeVerifier:s,digest:this._crypto?.digest});return await Promise.all([this._storage.put(P,s),this._storage.put(x,a)]),this._privyInternal.fetch(e.OAuthInit,{body:{redirect_to:r,provider:t,code_challenge:i,state_code:a}})}async loginWithCode(t,r,s,a,i){const[n,o]=await Promise.all([this._storage.get(P),this._storage.get(x)]);if(o!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:o??"",returnedStateCode:r??""}),new k({code:"pkce_state_code_mismatch",error:"Unexpected auth flow. This may be a phishing attempt."});const c=await this._privyInternal.fetch(e.OAuthAuthenticate,{body:{authorization_code:t,code_type:a,state_code:o,code_verifier:n,mode:i}});return await this._privyInternal.session.updateWithTokensResponse(c),this._privyInternal.callbacks?.setUser?.(c.user),await Promise.all([this._storage.del(P),this._storage.del(x)]),c}async linkWithCode(t,r,s,a){const[i,n]=await Promise.all([this._storage.get(P),this._storage.get(x)]);if(n!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"oauth",provider:s,storedStateCode:n??"",returnedStateCode:r??""}),new k({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(P),this._storage.del(x)]),o.user}async unlink(t,r){await this._privyInternal.fetch(e.OAuthUnlink,{body:{provider:t,subject:r}});return(await this._privyInternal.refreshSession()).user}}class A{_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 this._privyInternal.session.updateWithTokensResponse(a),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 U{_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,s){const a=await this._privyInternal.fetch(e.PasswordlessSmsAuthenticate,{body:{phoneNumber:t,code:r,mode:s}});return await this._privyInternal.session.updateWithTokensResponse(a),this._privyInternal.callbacks?.setUser?.(a.user),a}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 O{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async unlinkWallet(t){try{await this._privyInternal.fetch(e.SiweUnlink,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}catch(e){throw 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,a){const i=r||this._wallet,n=s||this._preparedMessage;if(!i)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!n)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:n,chainId:i.chainId,walletClientType:i.walletClientType,connectorType:i.connectorType,mode:a}});return await this._privyInternal.session.updateWithTokensResponse(r),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;guest;constructor(e,t,r){this._privyInternal=e,this.customProvider=new g(this._privyInternal),this.phone=new U(this._privyInternal),this.email=new f(this._privyInternal),this.oauth=new R(this._privyInternal,t,r),this.guest=new E(this._privyInternal),this.siwe=new O(this._privyInternal),this.passkey=new A(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 N={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"}}},L={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},G={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},D={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"}}},q={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"}}},W={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},z={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},H={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},$={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"}}},B={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"}}},K={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},V={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"}}},Y={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},Q={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},Z={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"}}},X={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"}}},ee={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},te={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},re={id:137,name:"Polygon Mainnet",network:"polygon",nativeCurrency:{name:"POL",symbol:"POL",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"}}},se={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},ae={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/"}}},ie={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"}}},ne={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},oe={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"}}},ce={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},le={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},de={mainnet:Z,goerli:J,sepolia:ne,arbitrum:N,arbitrumGoerli:L,arbitrumSepolia:G,optimism:X,optimismGoerli:ee,optimismSepolia:te,polygon:re,polygonMumbai:se,celo:z,celoAlfajores:H,filecoin:$,filecoinCalibration:B,base:M,baseGoerli:W,baseSepolia:j,linea:Y,lineaTestnet:Q,avalanche:D,avalancheFuji:q,holesky:V,redstone:ae,garnetHolesky:K,redstoneHolesky:ie,zora:oe,zoraSepolia:ce,zoraTestnet:le},he=[Z,J,ne,N,L,G,X,ee,te,re,se,z,H,$,B,M,W,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},Y,Q,D,q,V,ae,K,ie,oe,ce,le],pe=new Set(he.map((e=>e.id))),ue=["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 me 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 _e extends me{type="provider_error";code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}class ve extends Error{type;constructor(e,t){super(t),this.type=e}}class we extends me{type="connector_error";constructor(e,t,r){super(e,t,r)}}class ge extends Error{code;data;constructor(e,t,r){super(e),this.code=t,this.data=r}}const fe={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 be(e){return function(e){const t=e.type;return"string"==typeof t&&ue.includes(t)}(e)&&"wallet_not_on_device"===e.type}class Ee extends _e{details;constructor(e){const t=e;super(t.message,t.code,t.data);const r=Object.values(fe).find((e=>e.eipCode===t.code));this.details=r||fe.UNKNOWN_ERROR,-32002===t.code&&(t.message?.includes("already pending for origin")?t.message?.includes("wallet_requestPermissions")?this.details=fe.E32002_CONNECTION_ALREADY_PENDING:this.details=fe.E32002_REQUEST_ALREADY_PENDING:t.message?.includes("Already processing")&&t.message.includes("eth_requestAccounts")&&(this.details=fe.E32002_WALLET_LOCKED))}}const Ie=["eth_sign","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation"],ke=e=>i.BigNumber.from(e);function xe(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 Pe(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=ke(e.nonce).toNumber()),void 0!==e.gasLimit&&(t.gasLimit=ke(e.gasLimit)),void 0!==e.gasPrice&&(t.gasPrice=ke(e.gasPrice)),void 0!==e.value&&(t.value=ke(e.value)),void 0!==e.maxFeePerGas&&(t.maxFeePerGas=ke(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=ke(e.maxPriorityFeePerGas)),t}const Te=e=>[N.id,L.id,G.id].includes(e),Se=e=>[56,97].includes(e),Ce=81457,Re=168587773,Ae="0x420000000000000000000000000000000000000F",Ue=["function getL1Fee(bytes memory _data) external view returns (uint256)"],Oe=e=>[M.id,W.id,j.id,X.id,ee.id,te.id,oe.id,le.id,ce.id,Ce,Re].includes(e);const Fe={id:80002,name:"Polygon Amoy",network:"polygon-amoy",nativeCurrency:{name:"POL",symbol:"POL",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},Ne=v.default(fetch,{retries:3,retryDelay:500}),Le=e=>[re.id,se.id,Fe.id].includes(e),Ge=e=>({maxPriorityFee:c.parseUnits(e.maxPriorityFee.toFixed(9),"gwei").toHexString(),maxFee:c.parseUnits(e.maxFee.toFixed(9),"gwei").toHexString()}),De=async e=>{let t="";switch(e){case re.id:t="https://gasstation.polygon.technology/v2";break;case se.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 Ne(t),s=await r.json();if(r.status>399)throw s;return{safeLow:Ge((a=s).safeLow),standard:Ge(a.standard),fast:Ge(a.fast)};var a};async function qe(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 we(`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 we(`No RPC url found for ${e}`);return o};function We(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&&We(e);return t||r||s}async function ze(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 qe(t,r)),"string"==typeof t.type&&We(t.type)&&(t.type=Number(t.type)),[23294,23295].includes(t.chainId)&&(t.type=0),t=Le(t.chainId)?await async function(e){if(!Le(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 De(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):Te(t.chainId)?await(async(e,t)=>{if(!Te(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=xe(t),e.maxPriorityFeePerGas=xe(i.BigNumber.from(0))}}catch(e){throw new Error(`Failed to set gas price for Arbitrum transaction: ${e}.`)}return e})(t,r):Oe(t.chainId)?await(async(e,t)=>{if(!Oe(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=xe(s)}}catch(e){throw new Error(`Failed to set gas price for OP stack transaction: ${e}.`)}return e})(t,r):Se(t.chainId)?await(async(e,t)=>{if(!Se(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 He({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 $e 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,Ie.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 ze(this._address,t,this._jsonRpcProvider)}async handleSendTransaction(e){const t=this.ensureChainId(e),r=await ze(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 ge(`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 ge(`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 k({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 Be{_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 k({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 Ke(e){return void 0!==e.error}const Je=(Ve=0,()=>"id-"+Ve++);var Ve;const Ye=(e,t)=>"bigint"==typeof t?t.toString():t,Qe=e=>new Promise((t=>{setTimeout(t,e)})),Ze=(e,{ms:t,msg:r})=>Promise.race([e,new Promise(((e,s)=>{setTimeout((()=>{s(new Error(r))}),t??15e3)}))]),Xe=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 et{ready;cache;_embeddedWalletMessagePoster;constructor(e){this.ready=!1,this.cache=new Map,this._embeddedWalletMessagePoster=e}ping(e=15e3){return Ze(this.invoke("privy:iframe:ready",{},this._embeddedWalletMessagePoster),{msg:"Ping reached timeout",ms:e})}create(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connect(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recover(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}setRecovery(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:set-recovery",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: setRecovery",ms:6e4})}rpc(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:wallet:rpc",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: rpc"})}createSolana(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:create",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: create"})}connectSolana(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:connect",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: connect"})}recoverSolana(e){return Ze(this.waitForReady().then((()=>this.invoke("privy:solana-wallet:recover",e,this._embeddedWalletMessagePoster))),{msg:"Operation reached timeout: recover",ms:6e4})}solanaRpc(e){return Ze(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=Xe.dequeue(e.event,e.id);return Ke(e)?t.reject(new ve(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":const r=Xe.dequeue(e.event,e.id);return Ke(e)?r.reject(new ve(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallet:connect":const s=Xe.dequeue(e.event,e.id);return Ke(e)?s.reject(new ve(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:recover":const a=Xe.dequeue(e.event,e.id);return Ke(e)?a.reject(new ve(e.error.type,e.error.message)):a.resolve(e.data);case"privy:wallet:rpc":const i=Xe.dequeue(e.event,e.id);return Ke(e)?i.reject(new ve(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:set-recovery":const n=Xe.dequeue(e.event,e.id);return Ke(e)?n.reject(new ve(e.error.type,e.error.message)):n.resolve(e.data);case"privy:solana-wallet:create":const o=Xe.dequeue(e.event,e.id);return Ke(e)?o.reject(new ve(e.error.type,e.error.message)):o.resolve(e.data);case"privy:solana-wallet:connect":const c=Xe.dequeue(e.event,e.id);return Ke(e)?c.reject(new ve(e.error.type,e.error.message)):c.resolve(e.data);case"privy:solana-wallet:recover":const l=Xe.dequeue(e.event,e.id);return Ke(e)?l.reject(new ve(e.error.type,e.error.message)):l.resolve(e.data);case"privy:solana-wallet:rpc":const d=Xe.dequeue(e.event,e.id);return Ke(e)?d.reject(new ve(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 Qe(150)}))}invoke(e,t,r){const s=((e,t)=>`${e}${JSON.stringify(t,Ye)}`)(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();Xe.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 tt{_privyInternal;_proxy;_chains=Array.from(he);constructor(e,t,r){this._privyInternal=e,t&&(this._proxy=new et(t)),r&&(this._chains=r)}setMessagePoster(e){this._proxy=new et(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 $e({address:o,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}}async createSolana(e){if(!this._proxy)throw new k({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_creation_error"});const t=await this._privyInternal.getAccessToken();if(!t)throw new k({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 k({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 k({error:"Failed to create wallet",code:"embedded_wallet_creation_error"});return this._privyInternal.callbacks?.setUser&&await this._privyInternal.refreshSession(),new Be({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 be(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 $e({address:a,privyInternal:this._privyInternal,chains:this._chains,walletProxy:this._proxy})}async getSolanaProvider(e){if(!this._proxy)throw new k({error:"Embedded wallet proxy not initialized",code:"embedded_wallet_webview_not_loaded"});const t=await this._loadSolana(e);return new Be({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");He({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 $e({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(be(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(be(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 rt{static parse(e){try{return new rt(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 st="privy:token",at="privy-token",it="privy:refresh_token",nt="privy-refresh-token",ot="privy:id-token",ct="privy-id-token",lt="privy-session",dt="privy:session_transfer_token",ht=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","forked_token_cleared","token_stored","refresh_token_stored","identity_token_stored","oauth_tokens_granted"];class pt extends _.default{static events=ht;_storage;_isUsingServerCookies=!1;GUEST_CREDENTIAL_STORAGE_KEY;constructor(e){super(),this._storage=e.storage,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`}set isUsingServerCookies(e){this._isUsingServerCookies=e}async getToken(){const e=await this._storage.get(st);try{return"string"==typeof e?new rt(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(it);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(ot);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(dt);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(lt);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=rt.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){const t=await Promise.all([this._storage.del(st),this._storage.del(it),this._storage.del(ot),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),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(st);if(await this._storage.put(st,e),!this._isUsingServerCookies){const t=rt.parse(e)?.expiration;w.default.set(at,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(st);await this._storage.del(st),w.default.remove(at),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storeRefreshToken(e){"string"==typeof e?(await this._storage.put(it,e),this._isUsingServerCookies||(w.default.set(lt,"t",{sameSite:"Strict",secure:!0,expires:30}),w.default.set(nt,e,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(it),w.default.remove(nt),w.default.remove(lt),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async updateWithTokensResponse(e){await Promise.all([this.storeToken(e.token),this.storeRefreshToken(e.refresh_token),this.storeIdentityToken(e.identity_token),this.processOAuthTokens(e.oauth_tokens)])}async processOAuthTokens(e){e&&this.emit("oauth_tokens_granted",e)}async storeIdentityToken(e){if("string"==typeof e){const t=await this._storage.get(ot);if(await this._storage.put(ot,e),!this._isUsingServerCookies){const t=rt.parse(e)?.expiration;w.default.set(ct,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(ot);await this._storage.del(ot),w.default.remove(ct),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async getOrCreateGuestCredential(){const e=this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&"string"==typeof e)return e;const r=t.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,r),r}async clearForkedToken(){await this._storage.del(dt)}}const ut=e=>{const t=new AbortController;return setTimeout((()=>t.abort()),e),t.signal},yt="privy:caid";class mt{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.28.2-beta-20240920184838";_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 pt({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),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 I(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:ut(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 r=await this.fetch(e.RefreshSession,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=r.session_update_action;return this.callbacks?.setUser?.(r.user),"set"===s&&await this.session.updateWithTokensResponse(r),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&r.token&&(await this.session.storeToken(r.token),r.identity_token&&await this.session.storeIdentityToken(r.identity_token)),r}catch(e){throw(e instanceof I&&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 _t{_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 vt{_privyInternal;_storage;_crypto;constructor(e,t,r){this._privyInternal=e,this._storage=t,this._crypto=r}async generateURL(t){const r=T(),s=S(),a=await C({codeVerifier:r,digest:this._crypto?.digest});return await Promise.all([this._storage.put(P,r),this._storage.put(x,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(P),this._storage.get(x)]);if(a!==r)throw this._privyInternal.createAnalyticsEvent("possible_phishing_attempt",{flow:"recovery_oauth",storedStateCode:a??"",returnedStateCode:r??""}),new k({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(P),this._storage.del(x)]),i}}class wt{_privyInternal;auth;icloudAuth;constructor(e,t,r){this._privyInternal=e,this.auth=new vt(this._privyInternal,t,r),this.icloudAuth=new _t(this._privyInternal)}async getRecoveryKeyMaterial(t,r){return this._privyInternal.fetch(e.RecoveryKeyMaterial,{body:{chain_type:r},params:{address:t}})}}class gt{_privyInternal;constructor(e){this._privyInternal=e}async get(){try{const{user:e}=await this._privyInternal.refreshSession();return{user:e}}catch(e){throw e}}}const ft=["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=ft,exports.DEFAULT_SUPPORTED_CHAINS=he,exports.DEFAULT_SUPPORTED_CHAIN_IDS=pe,exports.EmbeddedProviderError=ge,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=I,exports.PrivyClientError=k,exports.PrivyConnectorError=we,exports.PrivyProviderRpcError=Ee,exports.ProviderErrors=fe,exports.QuantityToBigNumber=ke,exports.SUPPORTED_CONNECTOR_TYPES=["injected","wallet_connect","wallet_connect_v2","coinbase_wallet","embedded"],exports.calculateTotalGasEstimate=async function(e,t){if(!e.gasLimit)throw new Ee("gasLimit was not successfully set for transaction.");const r=ke(e.gasLimit);let s=i.BigNumber.from(0);if(2==e.type){if(!e.maxFeePerGas)throw new Ee("maxFeePerGas was not successfully set for transaction of type 2.");s=ke(e.maxFeePerGas)}else{if(!e.gasPrice)throw new Ee("gasPrice was not successfully set for transaction of type 0 or 1.");s=ke(e.gasPrice)}let a=r.mul(s),c=i.BigNumber.from(0);if(e.chainId&&Oe(e.chainId))try{c=await async function(e,t){if(!e.chainId||e.chainId&&!Oe(e.chainId))return i.BigNumber.from(0);let r=i.BigNumber.from(0);try{const s=new n.Contract(Ae,Ue,t),a=Pe(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=de,exports.convertBigNumberish=xe,exports.default=class{auth;user;embeddedWallet;recovery;_privyInternal;constructor({clientId:e,...t}){this._privyInternal=new mt({...t,appClientId:e}),this.user=new gt(this._privyInternal),this.auth=new F(this._privyInternal,t.storage,t.crypto),this.embeddedWallet=new tt(this._privyInternal,t.embeddedWalletMessagePoster,t.supportedChains),this.recovery=new wt(this._privyInternal,t.storage,t.crypto)}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}addOAuthTokensListener(e){return this._privyInternal.session.on("oauth_tokens_granted",e),{unsubscribe:()=>{this._privyInternal.session.removeListener("oauth_tokens_granted",e)}}}getAccessToken(){return this._privyInternal.getAccessToken()}getIdentityToken(){return this._privyInternal.getIdentityToken()}},exports.errorIndicatesRecoveryIsNeeded=be,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=ze,exports.throwIfInvalidRecoveryUpgradePath=He,exports.toEthersUnsignedTransaction=Pe,exports.toObjectKeys=(e,t=!0)=>e.reduce(((e,r)=>({...e,[r]:t})),{});
@@ -1 +1 @@
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 r}from"@privy-io/public-api";import{PrivyApiError as o}from"./Error.mjs";import{Session as h}from"./Session.mjs";import c from"./toAbortSignalTimeout.mjs";import"eventemitter3";import"jose";import"js-cookie";import"./Token.mjs";const l="privy:caid";class d{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.28.1";_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,appId:e.appId}),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 r=`${this.baseUrl}${i(t.path,s)}`,h=new Request(r,{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 o(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 e=await this.fetch(r,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=e.session_update_action;return this.callbacks?.setUser?.(e.user),"set"===s&&await this.session.updateWithTokensResponse(e),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&e.token&&(await this.session.storeToken(e.token),e.identity_token&&await this.session.storeIdentityToken(e.identity_token)),e}catch(t){throw(t instanceof o&&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};
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 a,AnalyticsEvent as n,RefreshSession as r}from"@privy-io/public-api";import{PrivyApiError as o}from"./Error.mjs";import{Session as h}from"./Session.mjs";import c from"./toAbortSignalTimeout.mjs";import"eventemitter3";import"jose";import"js-cookie";import"./Token.mjs";const l="privy:caid";class d{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.28.2-beta-20240920184838";_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,appId:e.appId}),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:a,options:n={onRequest:this._beforeRequest.bind(this)}}){const r=`${this.baseUrl}${i(t.path,s)}`,h=new Request(r,{method:t.method,body:JSON.stringify(e),headers:a}),c=await n.onRequest(h),l=await this._fetch(h,c),d=await l.json();if(l.status>299)throw new o(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(a,{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(n,{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 e=await this.fetch(r,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=e.session_update_action;return this.callbacks?.setUser?.(e.user),"set"===s&&await this.session.updateWithTokensResponse(e),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&e.token&&(await this.session.storeToken(e.token),e.identity_token&&await this.session.storeIdentityToken(e.identity_token)),e}catch(t){throw(t instanceof o&&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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@privy-io/js-sdk-core",
3
- "version": "0.28.1",
3
+ "version": "0.28.2-beta-20240920184838",
4
4
  "description": "Vanilla JS client for the Privy Auth API",
5
5
  "keywords": [
6
6
  "authentication",
@@ -57,8 +57,8 @@
57
57
  "@ethersproject/providers": "^5.7.2",
58
58
  "@ethersproject/transactions": "^5.7.0",
59
59
  "@ethersproject/units": "^5.7.0",
60
- "@privy-io/api-base": "^1.3.0",
61
- "@privy-io/public-api": "2.10.0",
60
+ "@privy-io/api-base": "1.3.1-beta-20240920184838",
61
+ "@privy-io/public-api": "2.10.1-beta-20240920184838",
62
62
  "eventemitter3": "^5.0.1",
63
63
  "fetch-retry": "^5.0.6",
64
64
  "jose": "^4.15.5",