@privy-io/react-auth 1.14.0-beta.1 → 1.14.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{useEffect as Li,useState as fe}from"react";import jt from"axios";import Ei from"axios";var z=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},_e=class extends z{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},c=class extends z{constructor(o,r){super(o,r);this.type="client_error"}};var U=class extends z{constructor(o,r){super(o,r);this.type="connector_error"}},S=t=>{if(t instanceof z)return t;if(!Ei.isAxiosError(t))return V(t);if(!t.response)return new _e("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new _e(e||"ApiError",t.response.status,o||r,t)},V=t=>t instanceof z?t:t instanceof Error?new c(t.message,t):new c(`Internal error: ${t}`);var Lo="1.14.0-beta.1";var Ao="https://api.privy.io/v0",Eo=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",Ve="4df5e2316331463a9130964bd6078dfa",ko=1e4,Pe=1400,zt=Lo;var Se="privy:token",rt="privy:refresh_token",it="privy:connectors",_o="walletconnect";var nt=class{constructor(e,o,r){this.appId=e,this.sdkVersion=zt,this.client=o,this.defaults=r}async get(e,o){try{return await jt.get(e,await this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw S(r)}}async post(e,o,r){try{return await jt.post(e,o,await this.buildConfig(r))}catch(i){throw S(i)}}async delete(e,o){try{return await jt.delete(e,await this.buildConfig(o))}catch(r){throw S(r)}}async buildConfig(e){if(e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,!e.headers.authorization){let o=await this.client.getAccessToken();o!==null&&(e.headers.authorization=`Bearer ${o}`)}return{...this.defaults,...e}}};import*as Po from"jose";var Y=class{static parse(e){try{return new Y(e)}catch{return null}}constructor(e){this.value=e,this._decoded=Po.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){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}};var se=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Zt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}},$t=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}};function _i(){return typeof window<"u"&&window.localStorage?new $t:new Zt}var R=_i();import{ErrorCode as Pi}from"@ethersproject/logger";var Te=class extends U{constructor(){super("Wallet timeout");this.type="wallet_error"}},ae=t=>{if(t instanceof U)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new We(t);return t.code===Pi.ACTION_REJECTED&&(e.details=we.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new We(t):new U("Unknown connector error",t)},Kt=class extends z{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},We=class extends Kt{constructor(o){var n,s,p;let r=o;super(r.message,r.code,r.data);let i=Object.values(we).find(m=>m.eipCode===r.code);this.details=i||we.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(s=r.message)!=null&&s.includes("wallet_requestPermissions")?this.details=we.E32002_CONNECTION_ALREADY_PENDING:this.details=we.E32002_REQUEST_ALREADY_PENDING:(p=r.message)!=null&&p.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=we.E32002_WALLET_LOCKED))}},Si={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0}},Ti={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},Wi={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}},we={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...Wi,...Ti},st={...Si,...we};var Ii=12e4,qt=(t=new Te,e=Ii)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),K=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new U(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),qt()]).catch(o=>{throw ae(o)})}},ye=class extends K{constructor(o){super(o)}},at=class extends K{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};import{getAddress as Ni}from"@ethersproject/address";import{getAddress as Ri}from"@ethersproject/address";import{Web3Provider as Mi}from"@ethersproject/providers";var Q=class{constructor(e,o,r){this.createSiweMessage=(e,o,r,i,n,s,p)=>`${r} wants you to sign in with your Ethereum account:
1
+ import{useEffect as Li,useState as fe}from"react";import jt from"axios";import Ei from"axios";var z=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},_e=class extends z{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},c=class extends z{constructor(o,r){super(o,r);this.type="client_error"}};var U=class extends z{constructor(o,r){super(o,r);this.type="connector_error"}},S=t=>{if(t instanceof z)return t;if(!Ei.isAxiosError(t))return V(t);if(!t.response)return new _e("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new _e(e||"ApiError",t.response.status,o||r,t)},V=t=>t instanceof z?t:t instanceof Error?new c(t.message,t):new c(`Internal error: ${t}`);var Lo="1.14.0-beta.2";var Ao="https://api.privy.io/v0",Eo=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",Ve="4df5e2316331463a9130964bd6078dfa",ko=1e4,Pe=1400,zt=Lo;var Se="privy:token",rt="privy:refresh_token",it="privy:connectors",_o="walletconnect";var nt=class{constructor(e,o,r){this.appId=e,this.sdkVersion=zt,this.client=o,this.defaults=r}async get(e,o){try{return await jt.get(e,await this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw S(r)}}async post(e,o,r){try{return await jt.post(e,o,await this.buildConfig(r))}catch(i){throw S(i)}}async delete(e,o){try{return await jt.delete(e,await this.buildConfig(o))}catch(r){throw S(r)}}async buildConfig(e){if(e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,!e.headers.authorization){let o=await this.client.getAccessToken();o!==null&&(e.headers.authorization=`Bearer ${o}`)}return{...this.defaults,...e}}};import*as Po from"jose";var Y=class{static parse(e){try{return new Y(e)}catch{return null}}constructor(e){this.value=e,this._decoded=Po.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){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}};var se=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Zt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}},$t=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}};function _i(){return typeof window<"u"&&window.localStorage?new $t:new Zt}var R=_i();import{ErrorCode as Pi}from"@ethersproject/logger";var Te=class extends U{constructor(){super("Wallet timeout");this.type="wallet_error"}},ae=t=>{if(t instanceof U)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new We(t);return t.code===Pi.ACTION_REJECTED&&(e.details=we.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new We(t):new U("Unknown connector error",t)},Kt=class extends z{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},We=class extends Kt{constructor(o){var n,s,p;let r=o;super(r.message,r.code,r.data);let i=Object.values(we).find(m=>m.eipCode===r.code);this.details=i||we.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(s=r.message)!=null&&s.includes("wallet_requestPermissions")?this.details=we.E32002_CONNECTION_ALREADY_PENDING:this.details=we.E32002_REQUEST_ALREADY_PENDING:(p=r.message)!=null&&p.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=we.E32002_WALLET_LOCKED))}},Si={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0}},Ti={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},Wi={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}},we={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...Wi,...Ti},st={...Si,...we};var Ii=12e4,qt=(t=new Te,e=Ii)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),K=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new U(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),qt()]).catch(o=>{throw ae(o)})}},ye=class extends K{constructor(o){super(o)}},at=class extends K{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};import{getAddress as Ni}from"@ethersproject/address";import{getAddress as Ri}from"@ethersproject/address";import{Web3Provider as Mi}from"@ethersproject/providers";var Q=class{constructor(e,o,r){this.createSiweMessage=(e,o,r,i,n,s,p)=>`${r} wants you to sign in with your Ethereum account:
2
2
  ${o}
3
3
 
4
4
  ${p}
@@ -9,7 +9,7 @@ Chain ID: ${e}
9
9
  Nonce: ${s}
10
10
  Issued At: ${n}
11
11
  Resources:
12
- - https://privy.io`;this.provider=o,this.walletType=e,this.address=r,this.chain=null,this.connected=!1}async fetchAddress(){if(!this.address){let e=await this.provider.request({method:"eth_accounts"});Array.isArray(e)&&e.length>0&&(this.address=Ri(e[0]))}return this.address}async fetchChainId(){if(!this.chain){let e=await this.provider.request({method:"eth_chainId"}),o=Number(e);this.chain=String(o)}return this.chain}async getConnectedWallet(){let e=this.walletType;if(!e||!await this.isConnected())return null;let o=await this.fetchAddress(),r=await this.fetchChainId();return{address:o,chainId:r,chainType:"ethereum",walletType:e}}async sign(e){return new Mi(new ye(this.provider)).getSigner().signMessage(e)}prepareMessage(e,o,r){let i=window.location.host,n=window.location.origin,s="By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",p=new Date().toISOString();return this.createSiweMessage(e,o,i,n,p,r,s)}};import{isMobile as Oi}from"react-device-detect";var lt=class extends Q{constructor(e,o){super("metamask",e,o)}async connect(e){var o;return this.provider.setProvider(window.ethereum),(o=window.ethereum.providers)==null||o.forEach(async r=>{r.isMetaMask&&this.provider.setProvider(r)}),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="";Oi||await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=Ni(o[0])),!e||e==="")throw new U("Unable to retrieve address");this.connected=!0,this.address=e}catch(e){throw ae(e)}}};import{getAddress as Ui}from"@ethersproject/address";import Fi from"@coinbase/wallet-sdk";var Di=()=>{let t=`https://mainnet.infura.io/v3/${Ve}`,e=1;return new Fi({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},dt=class extends Q{constructor(e,o){super("coinbase_wallet",e,o)}async connect(e){return this.provider.setProvider(Di()),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="",o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=Ui(o[0])),!e||e==="")throw new U("Unable to retrieve address");this.connected=!0}catch(e){throw ae(e)}}};import So from"@walletconnect/web3-provider";var Jt=class extends Q{constructor(o,r,i){super("wallet_connect",r,i);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(i)}async connect(o){return this.provider.setProvider(this._provider),(!await this.isConnected()||o.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return this.provider.walletProvider.connected}async promptConnection(){try{let o="";this.provider.setProvider(this._provider);let r=await Promise.race([this._provider.enable(),qt()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new U("Unable to retrieve address");this.connected=!0}catch(o){throw ae(o)}}},ct=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},R.getKeys().forEach(e=>{if(e.startsWith("walletconnect")){let o=new So({infuraId:Ve,storageId:e});o.enable(),this._storageIdToProvider[e]=o;for(let r of o.accounts)this._addressToStorageId[r]=e}})}build(e,o){return new Jt(this,e,o)}async destroy(){Object.values(this._storageIdToProvider).forEach(async e=>{await e.disconnect()})}getProviderForAddress(e){let o=_o,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;e===null?o=r():o=this._addressToStorageId[e]||r();let i=new So({infuraId:Ve,storageId:o});return this._storageIdToProvider[o]=i,i}indexProvider(e){this._storageIdToProvider[e.storageId]=e;for(let o of e.accounts)this._addressToStorageId[o]=e.storageId}};var Yt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},pt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},To=()=>{var e;let t=R.get(it);return t?(e=t.find(o=>o.active))==null?void 0:e.address:null},Be=class{constructor(){this.getEthereumProvider=()=>{var e;return((e=this.activeWalletConnector)==null?void 0:e.provider)||new K};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new ct,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}).then(()=>this.initialized=!0),this.initialized=!0)}initializeLinkedWallets(e){e.linkedAccounts.forEach(()=>{})}load(){(R.get(it)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)}),this.save()}save(){let e=this.walletConnectors.map(o=>{var r;return{address:o.address,walletType:o.walletType,active:o.address===((r=this.activeWalletConnector)==null?void 0:r.address)}});R.put(it,e)}destroy(){this.walletConnectors=[],this.initialized=!1,this.activeWalletConnector=void 0}addWalletConnector(e){this.walletConnectors.find(r=>r.address===e.address&&r.walletType===e.walletType)||this.walletConnectors.push(e)}removeWallet(e){var r;if(this.walletConnectors=this.walletConnectors.filter(i=>i.address!==e),e===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let i=this.walletConnectors[this.walletConnectors.length-1];this.setActiveWallet(i.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){return this.activeWalletConnector?await this.activeWalletConnector.connect({showPrompt:!1})?this.activeWalletConnector.sign(e):null:(console.error("Cannot sign, no wallet is active. Is a wallet connected?"),null)}setActiveWallet(e){let o=this.walletConnectors.find(r=>r.address===e);return o?(this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(e,o){switch(e){case"metamask":return new lt(new K,o);case"coinbase_wallet":return new dt(new K,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new K,o)}}};function le(t){return new Date(t*1e3)}function Gi(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:le(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:le(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:le(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:le(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:le(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:le(e.verified_at)};case"github_oauth":return{subject:e.subject,username:e.username,name:e.name,email:e.email,type:e.type,verifiedAt:le(e.verified_at)};default:throw new c("Unrecognized account type")}})}function Ce(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function He(t){let e=To();if(!e)return t.wallet&&console.warn("[Privy] User has linked wallets but no active wallet"),t;let o=t.linkedAccounts.find(i=>i.type==="wallet"&&i.address===e),r=Object.assign({},t);return r.wallet=o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},r}function X(t){if(!t)return null;let e=Gi(t.linked_accounts),o=Ce(e,"wallet"),r=Ce(e,"email"),i=Ce(e,"phone"),n=Ce(e,"google_oauth"),s=Ce(e,"twitter_oauth"),p=Ce(e,"discord_oauth"),m=Ce(e,"github_oauth"),u={id:t.id,createdAt:le(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:p&&{subject:p.subject,username:p.username,email:p.email},github:m&&{subject:m.subject,username:m.username,name:m.name,email:m.email}};return He(u)}var Wo=()=>"/api/v1/sessions",Io=()=>"/api/v1/sessions/logout",Ro=()=>"/api/v1/sessions/fork",Mo=()=>"/api/v1/siwe/init",No=()=>"/api/v1/siwe/authenticate",Oo=()=>"/api/v1/siwe/link",Uo=()=>"/api/v1/passwordless/init",Fo=()=>"/api/v1/passwordless/authenticate",Do=()=>"/api/v1/passwordless/link",Go=()=>"/api/v1/passwordless_sms/init",Vo=()=>"/api/v1/passwordless_sms/authenticate",Bo=()=>"/api/v1/passwordless_sms/link",Ho=()=>"/api/v1/oauth/init",zo=()=>"/api/v1/oauth/authenticate",jo=()=>"/api/v1/oauth/link",Zo=()=>"/api/v1/siwe/unlink",$o=()=>"/api/v1/passwordless/unlink",Ko=()=>"/api/v1/passwordless_sms/unlink",qo=()=>"/api/v1/oauth/unlink";var Vi=30,ut=class{constructor(){this.authenticateOnce=new se(async e=>this._authenticate(e)),this.linkOnce=new se(async e=>this._link(e)),this.refreshOnce=new se(this._refresh.bind(this)),this.destroyOnce=new se(this._destroy.bind(this)),this.forkSessionOnce=new se(this._forkSession.bind(this))}get token(){try{let e=R.get(Se);return typeof e=="string"?new Y(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=R.get(rt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=Y.parse(this.token);return e!==null&&!e.isExpired(Vi)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:X(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),V(o)}}async _link(e){try{let o=await e.link();return X(o)}catch(o){throw console.warn("Error linking account"),V(o)}}async _refresh(){if(!this.api)throw new c("Session has no API instance");if(!this.client)throw new c("Session has no PrivyClient instance");let e=await this.client.getAccessToken({disableAutoRefresh:!0}),o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Wo(),{refresh_token:o},{headers:{authorization:`Bearer ${this.token}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),X(r.data.user)}catch(r){if(r instanceof _e&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw V(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Io(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new c("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(Ro(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw V(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?R.put(Se,e):R.del(Se)}storeRefreshToken(e){typeof e=="string"?R.put(rt,e):R.del(rt)}};var Qt,ze=class{constructor(e){let o=e.apiURL||Ao,r=e.timeout||ko;this.appId=e.appId,this.connectors=new Be,Qt||(Qt=new ut),this.session=Qt,this.api=new nt(e.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new c("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new c("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.connectors.destroy(),this.authFlow=void 0}startAuthFlow(e){e.api=this.api,this.authFlow=e}async unlinkEmail(e){try{let o=await this.api.post($o(),{address:e});return X(o.data)}catch(o){throw V(o)}}async unlinkPhone(e){try{let o=await this.api.post(Ko(),{phoneNumber:e});return X(o.data)}catch(o){throw V(o)}}async unlinkWallet(e){try{let o=await this.api.post(Zo(),{address:e});return X(o.data)}catch(o){throw V(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(qo(),{provider:e,subject:o});return X(r.data)}catch(r){throw V(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){var o;return this.session.hasActiveToken()?((o=Y.parse(this.session.token))==null?void 0:o.audience)!==this.appId?(await this.logout(),null):this.session.token:!(e!=null&&e.disableAutoRefresh)&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getAppSettings(){try{let e=await this.api.get(`/api/v1/apps/${this.appId}`);return{id:e.data.id,name:e.data.name,verificationKey:e.data.verification_key,logoUrl:e.data.logo_url||void 0,theme:e.data.theme,accentColor:e.data.accent_color||void 0,showWalletLoginFirst:e.data.show_wallet_login_first,allowlistConfig:{errorTitle:e.data.allowlist_config.error_title,errorDetail:e.data.allowlist_config.error_detail,errorCtaText:e.data.allowlist_config.cta_text,errorCtaLink:e.data.allowlist_config.cta_link},walletAuth:e.data.wallet_auth,emailAuth:e.data.email_auth,smsAuth:e.data.sms_auth,googleOAuth:e.data.google_oauth,twitterOAuth:e.data.twitter_oauth,discordOAuth:e.data.discord_oauth,githubOAuth:e.data.github_oauth,termsAndConditionsUrl:e.data.terms_and_conditions_url,privacyPolicyUrl:e.data.privacy_policy_url,createdAt:new Date(e.data.created_at*1e3),updatedAt:new Date(e.data.updated_at*1e3)}}catch(e){throw V(e)}}setActiveWallet(e,o){if(!o.linkedAccounts.map(n=>n.type==="wallet"?n.address:null).includes(e))throw new c("Cannot set an unlinked address as active.");if(!this.connectors.setActiveWallet(e))throw new c("Error setting the active wallet.");return He(o)}async forkSession(){return await this.session.forkSession()}};import{Web3Provider as ea}from"@ethersproject/providers";import{createContext as Bi,useContext as Hi}from"react";var f=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var Xt=Bi({ready:!1,authenticated:!1,user:null,walletConnectors:null,login:f,linkEmail:f,linkPhone:f,linkWallet:f,linkGoogle:f,linkTwitter:f,linkDiscord:f,linkGithub:f,logout:f,getAccessToken:f,getEthereumProvider:f,getEthersProvider:f,getWeb3jsProvider:f,unlinkEmail:f,unlinkPhone:f,unlinkWallet:f,unlinkGoogle:f,unlinkTwitter:f,unlinkDiscord:f,unlinkGithub:f,setActiveWallet:f,forkSession:f}),M=()=>Hi(Xt);var je=class{constructor(e,o){this.meta={walletType:o},this.connectors=e,this.walletConnector=this.connectors.createWalletConnector(o,null)}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(No(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),{user:r.data.user,token:r.data.token,refresh_token:r.data.refresh_token,is_new_user:r.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(Oo(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),r.data}catch(e){throw S(e)}}async promptConnectAndSign(e){let o=await this.walletConnector.connect({showPrompt:!0}),r=o.address,i=o.chainId,n=await e.post(Mo(),{address:r}),s=this.walletConnector.prepareMessage(i,r,n.data.nonce),p=await this.walletConnector.sign(s);return{message:s,signature:p}}};var Ze=class{constructor(e){this.meta={email:e}}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new c("Email and email code must be set prior to calling authenticate.");try{let e=Fo(),o=await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new c("Email and email code must be set prior to calling authenticate.");try{let e=Do();return(await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode})).data}catch(e){throw S(e)}}async sendCodeEmail(e){if(!this.api)throw new c("Auth flow has no API instance");if(e&&(this.meta.email=e),!this.meta.email)throw new c("Email must be set when initialzing authentication.");try{let o=Uo();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw S(o)}}};var $e=class{constructor(e){this.meta={phoneNumber:e}}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new c("phone number and sms code must be set prior to calling authenticate.");try{let e=Vo(),o=await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new c("phone number and sms code must be set prior to calling authenticate.");try{let e=Bo();return(await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})).data}catch(e){throw S(e)}}async sendSmsCode(e){if(!this.api)throw new c("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),!this.meta.phoneNumber)throw new c("phone nNumber must be set when initialzing authentication.");try{let o=Go();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw S(o)}}};var Ie=class{constructor(e,o,r){this.meta={provider:e},this.meta.authorizationCode=o,this.meta.stateCode=r}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new c("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new c("User denied confirmation during OAuth flow");try{let e=zo(),o=await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new c("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new c("User denied confirmation during OAuth flow");try{let e=jo();return(await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode})).data}catch(e){throw S(e)}}async getAuthorizationUrl(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.provider)throw new c("Provider must be set when initialzing OAuth authentication.");try{let e=Ho();return(await this.api.post(e,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(e){throw S(e)}}};import"wicg-inert";import Ks from"react-dom";import vo from"styled-components";import{createContext as ji,useContext as Zi,useEffect as Yo,useState as Qo}from"react";import{jsx as zi}from"react/jsx-runtime";function Jo(t){return zi("link",{rel:"prefetch",href:t.src})}import{jsx as $i,jsxs as Ki}from"react/jsx-runtime";var Xo=ji({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:"LANDING",lastScreen:"LANDING",navigate:f,navigateBack:f}),er=t=>{let e=t.appSettings,o=t.authenticated,r=t.visible,[i,n]=Qo("LANDING"),[s,p]=Qo("LANDING");Yo(()=>{o||n("LANDING")},[o]),Yo(()=>{r||(p("LANDING"),n("LANDING"))},[r]);let m={ready:!!(e!=null&&e.id),app:e,options:t.options,currentScreen:i,lastScreen:s,navigate:u=>{p(i),n(u)},navigateBack:()=>{n(s)}};return Ki(Xo.Provider,{value:m,children:[e&&e.logoUrl&&$i(Jo,{src:e.logoUrl}),t.children]})},g=()=>Zi(Xo);import{useEffect as Hn,useState as zn}from"react";import Ye from"styled-components";import Yi from"styled-components";import{jsx as tr}from"react/jsx-runtime";var or=({style:t,...e})=>tr("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:tr("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});import{jsx as rr}from"react/jsx-runtime";var ir=({style:t,...e})=>rr("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:rr("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});import{createContext as qi,useContext as Ji}from"react";var eo=qi({isLinking:!1,getAuthMeta:f,getAuthFlow:f,closePrivyModal:f,initLoginWithWallet:f,loginWithWallet:f,loginWithCode:f,initLoginWithEmail:f,initLoginWithSms:f,resendEmailCode:f,resendSmsCode:f,initLoginWithOAuth:f,loginWithOAuth:f}),_=()=>Ji(eo);import{jsx as te,jsxs as on}from"react/jsx-runtime";var Qi=()=>te("div",{}),Xi=({backFn:t})=>te("div",{children:te(ir,{onClick:t})}),en=t=>te("div",{children:te("div",{children:te(or,{onClick:t.onClose})})});var L=({backFn:t,onClose:e})=>{let{closePrivyModal:o}=_();return on(tn,{children:[t?te(Xi,{backFn:t}):te(Qi,{}),te(en,{onClose:e||o})]})},tn=Yi.div`
12
+ - https://privy.io`;this.provider=o,this.walletType=e,this.address=r,this.chain=null,this.connected=!1}async fetchAddress(){if(!this.address){let e=await this.provider.request({method:"eth_accounts"});Array.isArray(e)&&e.length>0&&(this.address=Ri(e[0]))}return this.address}async fetchChainId(){if(!this.chain){let e=await this.provider.request({method:"eth_chainId"}),o=Number(e);this.chain=String(o)}return this.chain}async getConnectedWallet(){let e=this.walletType;if(!e||!await this.isConnected())return null;let o=await this.fetchAddress(),r=await this.fetchChainId();return{address:o,chainId:r,chainType:"ethereum",walletType:e}}async sign(e){return new Mi(new ye(this.provider)).getSigner().signMessage(e)}prepareMessage(e,o,r){let i=window.location.host,n=window.location.origin,s="By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",p=new Date().toISOString();return this.createSiweMessage(e,o,i,n,p,r,s)}};import{isMobile as Oi}from"react-device-detect";var lt=class extends Q{constructor(e,o){super("metamask",e,o)}async connect(e){var o;return this.provider.setProvider(window.ethereum),(o=window.ethereum.providers)==null||o.forEach(async r=>{r.isMetaMask&&this.provider.setProvider(r)}),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="";Oi||await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=Ni(o[0])),!e||e==="")throw new U("Unable to retrieve address");this.connected=!0,this.address=e}catch(e){throw ae(e)}}};import{getAddress as Ui}from"@ethersproject/address";import Fi from"@coinbase/wallet-sdk";var Di=()=>{let t=`https://mainnet.infura.io/v3/${Ve}`,e=1;return new Fi({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},dt=class extends Q{constructor(e,o){super("coinbase_wallet",e,o)}async connect(e){return this.provider.setProvider(Di()),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="",o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=Ui(o[0])),!e||e==="")throw new U("Unable to retrieve address");this.connected=!0}catch(e){throw ae(e)}}};import So from"@walletconnect/web3-provider";var Jt=class extends Q{constructor(o,r,i){super("wallet_connect",r,i);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(i)}async connect(o){return this.provider.setProvider(this._provider),(!await this.isConnected()||o.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return this.provider.walletProvider.connected}async promptConnection(){try{let o="";this.provider.setProvider(this._provider);let r=await Promise.race([this._provider.enable(),qt()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new U("Unable to retrieve address");this.connected=!0}catch(o){throw ae(o)}}},ct=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},R.getKeys().forEach(e=>{if(e.startsWith("walletconnect")){let o=new So({infuraId:Ve,storageId:e});o.enable(),this._storageIdToProvider[e]=o;for(let r of o.accounts)this._addressToStorageId[r]=e}})}build(e,o){return new Jt(this,e,o)}async destroy(){Object.values(this._storageIdToProvider).forEach(async e=>{await e.disconnect()})}getProviderForAddress(e){let o=_o,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;e===null?o=r():o=this._addressToStorageId[e]||r();let i=new So({infuraId:Ve,storageId:o});return this._storageIdToProvider[o]=i,i}indexProvider(e){this._storageIdToProvider[e.storageId]=e;for(let o of e.accounts)this._addressToStorageId[o]=e.storageId}};var Yt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},pt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},To=()=>{var e;let t=R.get(it);return t?(e=t.find(o=>o.active))==null?void 0:e.address:null},Be=class{constructor(){this.getEthereumProvider=()=>{var e;return((e=this.activeWalletConnector)==null?void 0:e.provider)||new K};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new ct,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}).then(()=>this.initialized=!0),this.initialized=!0)}initializeLinkedWallets(e){e.linkedAccounts.forEach(()=>{})}load(){(R.get(it)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)}),this.save()}save(){let e=this.walletConnectors.map(o=>{var r;return{address:o.address,walletType:o.walletType,active:o.address===((r=this.activeWalletConnector)==null?void 0:r.address)}});R.put(it,e)}destroy(){this.walletConnectors=[],this.initialized=!1,this.activeWalletConnector=void 0}addWalletConnector(e){this.walletConnectors.find(r=>r.address===e.address&&r.walletType===e.walletType)||this.walletConnectors.push(e)}removeWallet(e){var r;if(this.walletConnectors=this.walletConnectors.filter(i=>i.address!==e),e===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let i=this.walletConnectors[this.walletConnectors.length-1];this.setActiveWallet(i.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){return this.activeWalletConnector?await this.activeWalletConnector.connect({showPrompt:!1})?this.activeWalletConnector.sign(e):null:(console.error("Cannot sign, no wallet is active. Is a wallet connected?"),null)}setActiveWallet(e){let o=this.walletConnectors.find(r=>r.address===e);return o?(this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(e,o){switch(e){case"metamask":return new lt(new K,o);case"coinbase_wallet":return new dt(new K,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new K,o)}}};function le(t){return new Date(t*1e3)}function Gi(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:le(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:le(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:le(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:le(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:le(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:le(e.verified_at)};case"github_oauth":return{subject:e.subject,username:e.username,name:e.name,email:e.email,type:e.type,verifiedAt:le(e.verified_at)};default:throw new c("Unrecognized account type")}})}function Ce(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function He(t){let e=To();if(!e)return t.wallet&&console.warn("[Privy] User has linked wallets but no active wallet"),t;let o=t.linkedAccounts.find(i=>i.type==="wallet"&&i.address===e),r=Object.assign({},t);return r.wallet=o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},r}function X(t){if(!t)return null;let e=Gi(t.linked_accounts),o=Ce(e,"wallet"),r=Ce(e,"email"),i=Ce(e,"phone"),n=Ce(e,"google_oauth"),s=Ce(e,"twitter_oauth"),p=Ce(e,"discord_oauth"),m=Ce(e,"github_oauth"),u={id:t.id,createdAt:le(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:p&&{subject:p.subject,username:p.username,email:p.email},github:m&&{subject:m.subject,username:m.username,name:m.name,email:m.email}};return He(u)}var Wo=()=>"/api/v1/sessions",Io=()=>"/api/v1/sessions/logout",Ro=()=>"/api/v1/sessions/fork",Mo=()=>"/api/v1/siwe/init",No=()=>"/api/v1/siwe/authenticate",Oo=()=>"/api/v1/siwe/link",Uo=()=>"/api/v1/passwordless/init",Fo=()=>"/api/v1/passwordless/authenticate",Do=()=>"/api/v1/passwordless/link",Go=()=>"/api/v1/passwordless_sms/init",Vo=()=>"/api/v1/passwordless_sms/authenticate",Bo=()=>"/api/v1/passwordless_sms/link",Ho=()=>"/api/v1/oauth/init",zo=()=>"/api/v1/oauth/authenticate",jo=()=>"/api/v1/oauth/link",Zo=()=>"/api/v1/siwe/unlink",$o=()=>"/api/v1/passwordless/unlink",Ko=()=>"/api/v1/passwordless_sms/unlink",qo=()=>"/api/v1/oauth/unlink";var Vi=30,ut=class{constructor(){this.authenticateOnce=new se(async e=>this._authenticate(e)),this.linkOnce=new se(async e=>this._link(e)),this.refreshOnce=new se(this._refresh.bind(this)),this.destroyOnce=new se(this._destroy.bind(this)),this.forkSessionOnce=new se(this._forkSession.bind(this))}get token(){try{let e=R.get(Se);return typeof e=="string"?new Y(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=R.get(rt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=Y.parse(this.token);return e!==null&&!e.isExpired(Vi)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:X(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),V(o)}}async _link(e){try{let o=await e.link();return X(o)}catch(o){throw console.warn("Error linking account"),V(o)}}async _refresh(){if(!this.api)throw new c("Session has no API instance");if(!this.client)throw new c("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Wo(),{refresh_token:o},{headers:{authorization:`Bearer ${e}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),X(r.data.user)}catch(r){if(r instanceof _e&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw V(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Io(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new c("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(Ro(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw V(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?R.put(Se,e):R.del(Se)}storeRefreshToken(e){typeof e=="string"?R.put(rt,e):R.del(rt)}};var Qt,ze=class{constructor(e){let o=e.apiURL||Ao,r=e.timeout||ko;this.appId=e.appId,this.connectors=new Be,Qt||(Qt=new ut),this.session=Qt,this.api=new nt(e.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new c("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new c("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.connectors.destroy(),this.authFlow=void 0}startAuthFlow(e){e.api=this.api,this.authFlow=e}async unlinkEmail(e){try{let o=await this.api.post($o(),{address:e});return X(o.data)}catch(o){throw V(o)}}async unlinkPhone(e){try{let o=await this.api.post(Ko(),{phoneNumber:e});return X(o.data)}catch(o){throw V(o)}}async unlinkWallet(e){try{let o=await this.api.post(Zo(),{address:e});return X(o.data)}catch(o){throw V(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(qo(),{provider:e,subject:o});return X(r.data)}catch(r){throw V(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){var o;return this.session.hasActiveToken()?((o=Y.parse(this.session.token))==null?void 0:o.audience)!==this.appId?(await this.logout(),null):this.session.token:!(e!=null&&e.disableAutoRefresh)&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getAppSettings(){try{let e=await this.api.get(`/api/v1/apps/${this.appId}`);return{id:e.data.id,name:e.data.name,verificationKey:e.data.verification_key,logoUrl:e.data.logo_url||void 0,theme:e.data.theme,accentColor:e.data.accent_color||void 0,showWalletLoginFirst:e.data.show_wallet_login_first,allowlistConfig:{errorTitle:e.data.allowlist_config.error_title,errorDetail:e.data.allowlist_config.error_detail,errorCtaText:e.data.allowlist_config.cta_text,errorCtaLink:e.data.allowlist_config.cta_link},walletAuth:e.data.wallet_auth,emailAuth:e.data.email_auth,smsAuth:e.data.sms_auth,googleOAuth:e.data.google_oauth,twitterOAuth:e.data.twitter_oauth,discordOAuth:e.data.discord_oauth,githubOAuth:e.data.github_oauth,termsAndConditionsUrl:e.data.terms_and_conditions_url,privacyPolicyUrl:e.data.privacy_policy_url,createdAt:new Date(e.data.created_at*1e3),updatedAt:new Date(e.data.updated_at*1e3)}}catch(e){throw V(e)}}setActiveWallet(e,o){if(!o.linkedAccounts.map(n=>n.type==="wallet"?n.address:null).includes(e))throw new c("Cannot set an unlinked address as active.");if(!this.connectors.setActiveWallet(e))throw new c("Error setting the active wallet.");return He(o)}async forkSession(){return await this.session.forkSession()}};import{Web3Provider as ea}from"@ethersproject/providers";import{createContext as Bi,useContext as Hi}from"react";var f=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var Xt=Bi({ready:!1,authenticated:!1,user:null,walletConnectors:null,login:f,linkEmail:f,linkPhone:f,linkWallet:f,linkGoogle:f,linkTwitter:f,linkDiscord:f,linkGithub:f,logout:f,getAccessToken:f,getEthereumProvider:f,getEthersProvider:f,getWeb3jsProvider:f,unlinkEmail:f,unlinkPhone:f,unlinkWallet:f,unlinkGoogle:f,unlinkTwitter:f,unlinkDiscord:f,unlinkGithub:f,setActiveWallet:f,forkSession:f}),M=()=>Hi(Xt);var je=class{constructor(e,o){this.meta={walletType:o},this.connectors=e,this.walletConnector=this.connectors.createWalletConnector(o,null)}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(No(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),{user:r.data.user,token:r.data.token,refresh_token:r.data.refresh_token,is_new_user:r.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(Oo(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),r.data}catch(e){throw S(e)}}async promptConnectAndSign(e){let o=await this.walletConnector.connect({showPrompt:!0}),r=o.address,i=o.chainId,n=await e.post(Mo(),{address:r}),s=this.walletConnector.prepareMessage(i,r,n.data.nonce),p=await this.walletConnector.sign(s);return{message:s,signature:p}}};var Ze=class{constructor(e){this.meta={email:e}}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new c("Email and email code must be set prior to calling authenticate.");try{let e=Fo(),o=await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new c("Email and email code must be set prior to calling authenticate.");try{let e=Do();return(await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode})).data}catch(e){throw S(e)}}async sendCodeEmail(e){if(!this.api)throw new c("Auth flow has no API instance");if(e&&(this.meta.email=e),!this.meta.email)throw new c("Email must be set when initialzing authentication.");try{let o=Uo();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw S(o)}}};var $e=class{constructor(e){this.meta={phoneNumber:e}}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new c("phone number and sms code must be set prior to calling authenticate.");try{let e=Vo(),o=await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new c("phone number and sms code must be set prior to calling authenticate.");try{let e=Bo();return(await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})).data}catch(e){throw S(e)}}async sendSmsCode(e){if(!this.api)throw new c("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),!this.meta.phoneNumber)throw new c("phone nNumber must be set when initialzing authentication.");try{let o=Go();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw S(o)}}};var Ie=class{constructor(e,o,r){this.meta={provider:e},this.meta.authorizationCode=o,this.meta.stateCode=r}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new c("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new c("User denied confirmation during OAuth flow");try{let e=zo(),o=await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw S(e)}}async link(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new c("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new c("User denied confirmation during OAuth flow");try{let e=jo();return(await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode})).data}catch(e){throw S(e)}}async getAuthorizationUrl(){if(!this.api)throw new c("Auth flow has no API instance");if(!this.meta.provider)throw new c("Provider must be set when initialzing OAuth authentication.");try{let e=Ho();return(await this.api.post(e,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(e){throw S(e)}}};import"wicg-inert";import Ks from"react-dom";import vo from"styled-components";import{createContext as ji,useContext as Zi,useEffect as Yo,useState as Qo}from"react";import{jsx as zi}from"react/jsx-runtime";function Jo(t){return zi("link",{rel:"prefetch",href:t.src})}import{jsx as $i,jsxs as Ki}from"react/jsx-runtime";var Xo=ji({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:"LANDING",lastScreen:"LANDING",navigate:f,navigateBack:f}),er=t=>{let e=t.appSettings,o=t.authenticated,r=t.visible,[i,n]=Qo("LANDING"),[s,p]=Qo("LANDING");Yo(()=>{o||n("LANDING")},[o]),Yo(()=>{r||(p("LANDING"),n("LANDING"))},[r]);let m={ready:!!(e!=null&&e.id),app:e,options:t.options,currentScreen:i,lastScreen:s,navigate:u=>{p(i),n(u)},navigateBack:()=>{n(s)}};return Ki(Xo.Provider,{value:m,children:[e&&e.logoUrl&&$i(Jo,{src:e.logoUrl}),t.children]})},g=()=>Zi(Xo);import{useEffect as Hn,useState as zn}from"react";import Ye from"styled-components";import Yi from"styled-components";import{jsx as tr}from"react/jsx-runtime";var or=({style:t,...e})=>tr("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:tr("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});import{jsx as rr}from"react/jsx-runtime";var ir=({style:t,...e})=>rr("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:rr("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});import{createContext as qi,useContext as Ji}from"react";var eo=qi({isLinking:!1,getAuthMeta:f,getAuthFlow:f,closePrivyModal:f,initLoginWithWallet:f,loginWithWallet:f,loginWithCode:f,initLoginWithEmail:f,initLoginWithSms:f,resendEmailCode:f,resendSmsCode:f,initLoginWithOAuth:f,loginWithOAuth:f}),_=()=>Ji(eo);import{jsx as te,jsxs as on}from"react/jsx-runtime";var Qi=()=>te("div",{}),Xi=({backFn:t})=>te("div",{children:te(ir,{onClick:t})}),en=t=>te("div",{children:te("div",{children:te(or,{onClick:t.onClose})})});var L=({backFn:t,onClose:e})=>{let{closePrivyModal:o}=_();return on(tn,{children:[t?te(Xi,{backFn:t}):te(Qi,{}),te(en,{onClose:e||o})]})},tn=Yi.div`
13
13
  height: 30px;
14
14
  display: flex;
15
15
  align-items: center;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Mi=Object.create;var mt=Object.defineProperty;var Ni=Object.getOwnPropertyDescriptor;var Oi=Object.getOwnPropertyNames;var Ui=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty;var Di=(t,e)=>{for(var o in e)mt(t,o,{get:e[o],enumerable:!0})},Oo=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oi(e))!Fi.call(t,i)&&i!==o&&mt(t,i,{get:()=>e[i],enumerable:!(r=Ni(e,i))||r.enumerable});return t};var v=(t,e,o)=>(o=t!=null?Mi(Ui(t)):{},Oo(e||!t||!t.__esModule?mt(o,"default",{value:t,enumerable:!0}):o,t)),Gi=t=>Oo(mt({},"__esModule",{value:!0}),t);var hs={};Di(hs,{AsExternalProvider:()=>xe,ConnectorManager:()=>je,PrivyClient:()=>Ze,PrivyProvider:()=>Ii,PrivyProxyProvider:()=>te,VERSION:()=>ft,WalletConnector:()=>le,getAccessToken:()=>Wi,usePrivy:()=>N});module.exports=Gi(hs);var Q=require("react");var yt=v(require("axios"));var Uo=v(require("axios")),ee=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},Ge=class extends ee{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},p=class extends ee{constructor(o,r){super(o,r);this.type="client_error"}};var j=class extends ee{constructor(o,r){super(o,r);this.type="connector_error"}},M=t=>{if(t instanceof ee)return t;if(!Uo.default.isAxiosError(t))return K(t);if(!t.response)return new Ge("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new Ge(e||"ApiError",t.response.status,o||r,t)},K=t=>t instanceof ee?t:t instanceof Error?new p(t.message,t):new p(`Internal error: ${t}`);var Fo="1.14.0-beta.1";var Do="https://api.privy.io/v0",Go=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",et="4df5e2316331463a9130964bd6078dfa",Vo=1e4,Ve=1400,ft=Fo;var Be="privy:token",gt="privy:refresh_token",wt="privy:connectors",Bo="walletconnect";var Ct=class{constructor(e,o,r){this.appId=e,this.sdkVersion=ft,this.client=o,this.defaults=r}async get(e,o){try{return await yt.default.get(e,await this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw M(r)}}async post(e,o,r){try{return await yt.default.post(e,o,await this.buildConfig(r))}catch(i){throw M(i)}}async delete(e,o){try{return await yt.default.delete(e,await this.buildConfig(o))}catch(r){throw M(r)}}async buildConfig(e){if(e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,!e.headers.authorization){let o=await this.client.getAccessToken();o!==null&&(e.headers.authorization=`Bearer ${o}`)}return{...this.defaults,...e}}};var Ho=v(require("jose")),he=class{static parse(e){try{return new he(e)}catch{return null}}constructor(e){this.value=e,this._decoded=Ho.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){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}};var ve=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Xt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}},eo=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}};function Bi(){return typeof window<"u"&&window.localStorage?new eo:new Xt}var V=Bi();var zo=require("@ethersproject/logger");var He=class extends j{constructor(){super("Wallet timeout");this.type="wallet_error"}},be=t=>{if(t instanceof j)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new ze(t);return t.code===zo.ErrorCode.ACTION_REJECTED&&(e.details=Ie.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new ze(t):new j("Unknown connector error",t)},to=class extends ee{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},ze=class extends to{constructor(o){var n,a,u;let r=o;super(r.message,r.code,r.data);let i=Object.values(Ie).find(f=>f.eipCode===r.code);this.details=i||Ie.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(a=r.message)!=null&&a.includes("wallet_requestPermissions")?this.details=Ie.E32002_CONNECTION_ALREADY_PENDING:this.details=Ie.E32002_REQUEST_ALREADY_PENDING:(u=r.message)!=null&&u.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=Ie.E32002_WALLET_LOCKED))}},Hi={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0}},zi={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},ji={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}},Ie={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...ji,...zi},vt={...Hi,...Ie};var Zi=12e4,oo=(t=new He,e=Zi)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),te=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new j(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),oo()]).catch(o=>{throw be(o)})}},xe=class extends te{constructor(o){super(o)}},bt=class extends te{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};var $o=require("@ethersproject/address");var jo=require("@ethersproject/address");var Zo=require("@ethersproject/providers"),le=class{constructor(e,o,r){this.createSiweMessage=(e,o,r,i,n,a,u)=>`${r} wants you to sign in with your Ethereum account:
1
+ "use strict";var Mi=Object.create;var mt=Object.defineProperty;var Ni=Object.getOwnPropertyDescriptor;var Oi=Object.getOwnPropertyNames;var Ui=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty;var Di=(t,e)=>{for(var o in e)mt(t,o,{get:e[o],enumerable:!0})},Oo=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oi(e))!Fi.call(t,i)&&i!==o&&mt(t,i,{get:()=>e[i],enumerable:!(r=Ni(e,i))||r.enumerable});return t};var v=(t,e,o)=>(o=t!=null?Mi(Ui(t)):{},Oo(e||!t||!t.__esModule?mt(o,"default",{value:t,enumerable:!0}):o,t)),Gi=t=>Oo(mt({},"__esModule",{value:!0}),t);var hs={};Di(hs,{AsExternalProvider:()=>xe,ConnectorManager:()=>je,PrivyClient:()=>Ze,PrivyProvider:()=>Ii,PrivyProxyProvider:()=>te,VERSION:()=>ft,WalletConnector:()=>le,getAccessToken:()=>Wi,usePrivy:()=>N});module.exports=Gi(hs);var Q=require("react");var yt=v(require("axios"));var Uo=v(require("axios")),ee=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},Ge=class extends ee{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},p=class extends ee{constructor(o,r){super(o,r);this.type="client_error"}};var j=class extends ee{constructor(o,r){super(o,r);this.type="connector_error"}},M=t=>{if(t instanceof ee)return t;if(!Uo.default.isAxiosError(t))return K(t);if(!t.response)return new Ge("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new Ge(e||"ApiError",t.response.status,o||r,t)},K=t=>t instanceof ee?t:t instanceof Error?new p(t.message,t):new p(`Internal error: ${t}`);var Fo="1.14.0-beta.2";var Do="https://api.privy.io/v0",Go=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",et="4df5e2316331463a9130964bd6078dfa",Vo=1e4,Ve=1400,ft=Fo;var Be="privy:token",gt="privy:refresh_token",wt="privy:connectors",Bo="walletconnect";var Ct=class{constructor(e,o,r){this.appId=e,this.sdkVersion=ft,this.client=o,this.defaults=r}async get(e,o){try{return await yt.default.get(e,await this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw M(r)}}async post(e,o,r){try{return await yt.default.post(e,o,await this.buildConfig(r))}catch(i){throw M(i)}}async delete(e,o){try{return await yt.default.delete(e,await this.buildConfig(o))}catch(r){throw M(r)}}async buildConfig(e){if(e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,!e.headers.authorization){let o=await this.client.getAccessToken();o!==null&&(e.headers.authorization=`Bearer ${o}`)}return{...this.defaults,...e}}};var Ho=v(require("jose")),he=class{static parse(e){try{return new he(e)}catch{return null}}constructor(e){this.value=e,this._decoded=Ho.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){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}};var ve=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Xt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}},eo=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}};function Bi(){return typeof window<"u"&&window.localStorage?new eo:new Xt}var V=Bi();var zo=require("@ethersproject/logger");var He=class extends j{constructor(){super("Wallet timeout");this.type="wallet_error"}},be=t=>{if(t instanceof j)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new ze(t);return t.code===zo.ErrorCode.ACTION_REJECTED&&(e.details=Ie.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new ze(t):new j("Unknown connector error",t)},to=class extends ee{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},ze=class extends to{constructor(o){var n,a,u;let r=o;super(r.message,r.code,r.data);let i=Object.values(Ie).find(f=>f.eipCode===r.code);this.details=i||Ie.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(a=r.message)!=null&&a.includes("wallet_requestPermissions")?this.details=Ie.E32002_CONNECTION_ALREADY_PENDING:this.details=Ie.E32002_REQUEST_ALREADY_PENDING:(u=r.message)!=null&&u.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=Ie.E32002_WALLET_LOCKED))}},Hi={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0}},zi={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},ji={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}},Ie={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...ji,...zi},vt={...Hi,...Ie};var Zi=12e4,oo=(t=new He,e=Zi)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),te=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new j(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),oo()]).catch(o=>{throw be(o)})}},xe=class extends te{constructor(o){super(o)}},bt=class extends te{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};var $o=require("@ethersproject/address");var jo=require("@ethersproject/address");var Zo=require("@ethersproject/providers"),le=class{constructor(e,o,r){this.createSiweMessage=(e,o,r,i,n,a,u)=>`${r} wants you to sign in with your Ethereum account:
2
2
  ${o}
3
3
 
4
4
  ${u}
@@ -9,7 +9,7 @@ Chain ID: ${e}
9
9
  Nonce: ${a}
10
10
  Issued At: ${n}
11
11
  Resources:
12
- - https://privy.io`;this.provider=o,this.walletType=e,this.address=r,this.chain=null,this.connected=!1}async fetchAddress(){if(!this.address){let e=await this.provider.request({method:"eth_accounts"});Array.isArray(e)&&e.length>0&&(this.address=(0,jo.getAddress)(e[0]))}return this.address}async fetchChainId(){if(!this.chain){let e=await this.provider.request({method:"eth_chainId"}),o=Number(e);this.chain=String(o)}return this.chain}async getConnectedWallet(){let e=this.walletType;if(!e||!await this.isConnected())return null;let o=await this.fetchAddress(),r=await this.fetchChainId();return{address:o,chainId:r,chainType:"ethereum",walletType:e}}async sign(e){return new Zo.Web3Provider(new xe(this.provider)).getSigner().signMessage(e)}prepareMessage(e,o,r){let i=window.location.host,n=window.location.origin,a="By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",u=new Date().toISOString();return this.createSiweMessage(e,o,i,n,u,r,a)}};var Ko=require("react-device-detect"),xt=class extends le{constructor(e,o){super("metamask",e,o)}async connect(e){var o;return this.provider.setProvider(window.ethereum),(o=window.ethereum.providers)==null||o.forEach(async r=>{r.isMetaMask&&this.provider.setProvider(r)}),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="";Ko.isMobile||await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=(0,$o.getAddress)(o[0])),!e||e==="")throw new j("Unable to retrieve address");this.connected=!0,this.address=e}catch(e){throw be(e)}}};var qo=require("@ethersproject/address");var Jo=v(require("@coinbase/wallet-sdk"));var $i=()=>{let t=`https://mainnet.infura.io/v3/${et}`,e=1;return new Jo.default({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},Lt=class extends le{constructor(e,o){super("coinbase_wallet",e,o)}async connect(e){return this.provider.setProvider($i()),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="",o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=(0,qo.getAddress)(o[0])),!e||e==="")throw new j("Unable to retrieve address");this.connected=!0}catch(e){throw be(e)}}};var ro=v(require("@walletconnect/web3-provider"));var io=class extends le{constructor(o,r,i){super("wallet_connect",r,i);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(i)}async connect(o){return this.provider.setProvider(this._provider),(!await this.isConnected()||o.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return this.provider.walletProvider.connected}async promptConnection(){try{let o="";this.provider.setProvider(this._provider);let r=await Promise.race([this._provider.enable(),oo()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new j("Unable to retrieve address");this.connected=!0}catch(o){throw be(o)}}},At=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},V.getKeys().forEach(e=>{if(e.startsWith("walletconnect")){let o=new ro.default({infuraId:et,storageId:e});o.enable(),this._storageIdToProvider[e]=o;for(let r of o.accounts)this._addressToStorageId[r]=e}})}build(e,o){return new io(this,e,o)}async destroy(){Object.values(this._storageIdToProvider).forEach(async e=>{await e.disconnect()})}getProviderForAddress(e){let o=Bo,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;e===null?o=r():o=this._addressToStorageId[e]||r();let i=new ro.default({infuraId:et,storageId:o});return this._storageIdToProvider[o]=i,i}indexProvider(e){this._storageIdToProvider[e.storageId]=e;for(let o of e.accounts)this._addressToStorageId[o]=e.storageId}};var no=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},Et=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},Yo=()=>{var e;let t=V.get(wt);return t?(e=t.find(o=>o.active))==null?void 0:e.address:null},je=class{constructor(){this.getEthereumProvider=()=>{var e;return((e=this.activeWalletConnector)==null?void 0:e.provider)||new te};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new At,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}).then(()=>this.initialized=!0),this.initialized=!0)}initializeLinkedWallets(e){e.linkedAccounts.forEach(()=>{})}load(){(V.get(wt)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)}),this.save()}save(){let e=this.walletConnectors.map(o=>{var r;return{address:o.address,walletType:o.walletType,active:o.address===((r=this.activeWalletConnector)==null?void 0:r.address)}});V.put(wt,e)}destroy(){this.walletConnectors=[],this.initialized=!1,this.activeWalletConnector=void 0}addWalletConnector(e){this.walletConnectors.find(r=>r.address===e.address&&r.walletType===e.walletType)||this.walletConnectors.push(e)}removeWallet(e){var r;if(this.walletConnectors=this.walletConnectors.filter(i=>i.address!==e),e===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let i=this.walletConnectors[this.walletConnectors.length-1];this.setActiveWallet(i.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){return this.activeWalletConnector?await this.activeWalletConnector.connect({showPrompt:!1})?this.activeWalletConnector.sign(e):null:(console.error("Cannot sign, no wallet is active. Is a wallet connected?"),null)}setActiveWallet(e){let o=this.walletConnectors.find(r=>r.address===e);return o?(this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(e,o){switch(e){case"metamask":return new xt(new te,o);case"coinbase_wallet":return new Lt(new te,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new te,o)}}};function Le(t){return new Date(t*1e3)}function Ki(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:Le(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:Le(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:Le(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:Le(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:Le(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:Le(e.verified_at)};case"github_oauth":return{subject:e.subject,username:e.username,name:e.name,email:e.email,type:e.type,verifiedAt:Le(e.verified_at)};default:throw new p("Unrecognized account type")}})}function Re(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function tt(t){let e=Yo();if(!e)return t.wallet&&console.warn("[Privy] User has linked wallets but no active wallet"),t;let o=t.linkedAccounts.find(i=>i.type==="wallet"&&i.address===e),r=Object.assign({},t);return r.wallet=o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},r}function me(t){if(!t)return null;let e=Ki(t.linked_accounts),o=Re(e,"wallet"),r=Re(e,"email"),i=Re(e,"phone"),n=Re(e,"google_oauth"),a=Re(e,"twitter_oauth"),u=Re(e,"discord_oauth"),f=Re(e,"github_oauth"),m={id:t.id,createdAt:Le(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:a&&{subject:a.subject,username:a.username,name:a.name},discord:u&&{subject:u.subject,username:u.username,email:u.email},github:f&&{subject:f.subject,username:f.username,name:f.name,email:f.email}};return tt(m)}var Qo=()=>"/api/v1/sessions",Xo=()=>"/api/v1/sessions/logout",er=()=>"/api/v1/sessions/fork",tr=()=>"/api/v1/siwe/init",or=()=>"/api/v1/siwe/authenticate",rr=()=>"/api/v1/siwe/link",ir=()=>"/api/v1/passwordless/init",nr=()=>"/api/v1/passwordless/authenticate",sr=()=>"/api/v1/passwordless/link",ar=()=>"/api/v1/passwordless_sms/init",lr=()=>"/api/v1/passwordless_sms/authenticate",dr=()=>"/api/v1/passwordless_sms/link",cr=()=>"/api/v1/oauth/init",pr=()=>"/api/v1/oauth/authenticate",ur=()=>"/api/v1/oauth/link",hr=()=>"/api/v1/siwe/unlink",mr=()=>"/api/v1/passwordless/unlink",fr=()=>"/api/v1/passwordless_sms/unlink",gr=()=>"/api/v1/oauth/unlink";var qi=30,kt=class{constructor(){this.authenticateOnce=new ve(async e=>this._authenticate(e)),this.linkOnce=new ve(async e=>this._link(e)),this.refreshOnce=new ve(this._refresh.bind(this)),this.destroyOnce=new ve(this._destroy.bind(this)),this.forkSessionOnce=new ve(this._forkSession.bind(this))}get token(){try{let e=V.get(Be);return typeof e=="string"?new he(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=V.get(gt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=he.parse(this.token);return e!==null&&!e.isExpired(qi)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:me(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),K(o)}}async _link(e){try{let o=await e.link();return me(o)}catch(o){throw console.warn("Error linking account"),K(o)}}async _refresh(){if(!this.api)throw new p("Session has no API instance");if(!this.client)throw new p("Session has no PrivyClient instance");let e=await this.client.getAccessToken({disableAutoRefresh:!0}),o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Qo(),{refresh_token:o},{headers:{authorization:`Bearer ${this.token}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),me(r.data.user)}catch(r){if(r instanceof Ge&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw K(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Xo(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new p("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(er(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw K(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?V.put(Be,e):V.del(Be)}storeRefreshToken(e){typeof e=="string"?V.put(gt,e):V.del(gt)}};var so,Ze=class{constructor(e){let o=e.apiURL||Do,r=e.timeout||Vo;this.appId=e.appId,this.connectors=new je,so||(so=new kt),this.session=so,this.api=new Ct(e.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new p("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new p("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.connectors.destroy(),this.authFlow=void 0}startAuthFlow(e){e.api=this.api,this.authFlow=e}async unlinkEmail(e){try{let o=await this.api.post(mr(),{address:e});return me(o.data)}catch(o){throw K(o)}}async unlinkPhone(e){try{let o=await this.api.post(fr(),{phoneNumber:e});return me(o.data)}catch(o){throw K(o)}}async unlinkWallet(e){try{let o=await this.api.post(hr(),{address:e});return me(o.data)}catch(o){throw K(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(gr(),{provider:e,subject:o});return me(r.data)}catch(r){throw K(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){var o;return this.session.hasActiveToken()?((o=he.parse(this.session.token))==null?void 0:o.audience)!==this.appId?(await this.logout(),null):this.session.token:!(e!=null&&e.disableAutoRefresh)&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getAppSettings(){try{let e=await this.api.get(`/api/v1/apps/${this.appId}`);return{id:e.data.id,name:e.data.name,verificationKey:e.data.verification_key,logoUrl:e.data.logo_url||void 0,theme:e.data.theme,accentColor:e.data.accent_color||void 0,showWalletLoginFirst:e.data.show_wallet_login_first,allowlistConfig:{errorTitle:e.data.allowlist_config.error_title,errorDetail:e.data.allowlist_config.error_detail,errorCtaText:e.data.allowlist_config.cta_text,errorCtaLink:e.data.allowlist_config.cta_link},walletAuth:e.data.wallet_auth,emailAuth:e.data.email_auth,smsAuth:e.data.sms_auth,googleOAuth:e.data.google_oauth,twitterOAuth:e.data.twitter_oauth,discordOAuth:e.data.discord_oauth,githubOAuth:e.data.github_oauth,termsAndConditionsUrl:e.data.terms_and_conditions_url,privacyPolicyUrl:e.data.privacy_policy_url,createdAt:new Date(e.data.created_at*1e3),updatedAt:new Date(e.data.updated_at*1e3)}}catch(e){throw K(e)}}setActiveWallet(e,o){if(!o.linkedAccounts.map(n=>n.type==="wallet"?n.address:null).includes(e))throw new p("Cannot set an unlinked address as active.");if(!this.connectors.setActiveWallet(e))throw new p("Error setting the active wallet.");return tt(o)}async forkSession(){return await this.session.forkSession()}};var Ti=require("@ethersproject/providers");var _t=require("react");var w=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var ao=(0,_t.createContext)({ready:!1,authenticated:!1,user:null,walletConnectors:null,login:w,linkEmail:w,linkPhone:w,linkWallet:w,linkGoogle:w,linkTwitter:w,linkDiscord:w,linkGithub:w,logout:w,getAccessToken:w,getEthereumProvider:w,getEthersProvider:w,getWeb3jsProvider:w,unlinkEmail:w,unlinkPhone:w,unlinkWallet:w,unlinkGoogle:w,unlinkTwitter:w,unlinkDiscord:w,unlinkGithub:w,setActiveWallet:w,forkSession:w}),N=()=>(0,_t.useContext)(ao);var ot=class{constructor(e,o){this.meta={walletType:o},this.connectors=e,this.walletConnector=this.connectors.createWalletConnector(o,null)}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(or(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),{user:r.data.user,token:r.data.token,refresh_token:r.data.refresh_token,is_new_user:r.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(rr(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),r.data}catch(e){throw M(e)}}async promptConnectAndSign(e){let o=await this.walletConnector.connect({showPrompt:!0}),r=o.address,i=o.chainId,n=await e.post(tr(),{address:r}),a=this.walletConnector.prepareMessage(i,r,n.data.nonce),u=await this.walletConnector.sign(a);return{message:a,signature:u}}};var rt=class{constructor(e){this.meta={email:e}}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new p("Email and email code must be set prior to calling authenticate.");try{let e=nr(),o=await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new p("Email and email code must be set prior to calling authenticate.");try{let e=sr();return(await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode})).data}catch(e){throw M(e)}}async sendCodeEmail(e){if(!this.api)throw new p("Auth flow has no API instance");if(e&&(this.meta.email=e),!this.meta.email)throw new p("Email must be set when initialzing authentication.");try{let o=ir();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw M(o)}}};var it=class{constructor(e){this.meta={phoneNumber:e}}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new p("phone number and sms code must be set prior to calling authenticate.");try{let e=lr(),o=await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new p("phone number and sms code must be set prior to calling authenticate.");try{let e=dr();return(await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})).data}catch(e){throw M(e)}}async sendSmsCode(e){if(!this.api)throw new p("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),!this.meta.phoneNumber)throw new p("phone nNumber must be set when initialzing authentication.");try{let o=ar();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw M(o)}}};var $e=class{constructor(e,o,r){this.meta={provider:e},this.meta.authorizationCode=o,this.meta.stateCode=r}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new p("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new p("User denied confirmation during OAuth flow");try{let e=pr(),o=await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new p("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new p("User denied confirmation during OAuth flow");try{let e=ur();return(await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode})).data}catch(e){throw M(e)}}async getAuthorizationUrl(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.provider)throw new p("Provider must be set when initialzing OAuth authentication.");try{let e=cr();return(await this.api.post(e,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(e){throw M(e)}}};var uc=require("wicg-inert"),_i=v(require("react-dom")),qt=v(require("styled-components"));var de=require("react");var yr=require("react/jsx-runtime");function wr(t){return(0,yr.jsx)("link",{rel:"prefetch",href:t.src})}var Pt=require("react/jsx-runtime"),Cr=(0,de.createContext)({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:"LANDING",lastScreen:"LANDING",navigate:w,navigateBack:w}),vr=t=>{let e=t.appSettings,o=t.authenticated,r=t.visible,[i,n]=(0,de.useState)("LANDING"),[a,u]=(0,de.useState)("LANDING");(0,de.useEffect)(()=>{o||n("LANDING")},[o]),(0,de.useEffect)(()=>{r||(u("LANDING"),n("LANDING"))},[r]);let f={ready:!!(e!=null&&e.id),app:e,options:t.options,currentScreen:i,lastScreen:a,navigate:m=>{u(i),n(m)},navigateBack:()=>{n(a)}};return(0,Pt.jsxs)(Cr.Provider,{value:f,children:[e&&e.logoUrl&&(0,Pt.jsx)(wr,{src:e.logoUrl}),t.children]})},y=()=>(0,de.useContext)(Cr);var zt=require("react"),Ye=v(require("styled-components"));var Lr=v(require("styled-components"));var lo=require("react/jsx-runtime"),br=({style:t,...e})=>(0,lo.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:(0,lo.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});var co=require("react/jsx-runtime"),xr=({style:t,...e})=>(0,co.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:(0,co.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});var St=require("react");var po=(0,St.createContext)({isLinking:!1,getAuthMeta:w,getAuthFlow:w,closePrivyModal:w,initLoginWithWallet:w,loginWithWallet:w,loginWithCode:w,initLoginWithEmail:w,initLoginWithSms:w,resendEmailCode:w,resendSmsCode:w,initLoginWithOAuth:w,loginWithOAuth:w}),W=()=>(0,St.useContext)(po);var q=require("react/jsx-runtime"),Ji=()=>(0,q.jsx)("div",{}),Yi=({backFn:t})=>(0,q.jsx)("div",{children:(0,q.jsx)(xr,{onClick:t})}),Qi=t=>(0,q.jsx)("div",{children:(0,q.jsx)("div",{children:(0,q.jsx)(br,{onClick:t.onClose})})});var E=({backFn:t,onClose:e})=>{let{closePrivyModal:o}=W();return(0,q.jsxs)(Xi,{children:[t?(0,q.jsx)(Yi,{backFn:t}):(0,q.jsx)(Ji,{}),(0,q.jsx)(Qi,{onClose:e||o})]})},Xi=Lr.default.div`
12
+ - https://privy.io`;this.provider=o,this.walletType=e,this.address=r,this.chain=null,this.connected=!1}async fetchAddress(){if(!this.address){let e=await this.provider.request({method:"eth_accounts"});Array.isArray(e)&&e.length>0&&(this.address=(0,jo.getAddress)(e[0]))}return this.address}async fetchChainId(){if(!this.chain){let e=await this.provider.request({method:"eth_chainId"}),o=Number(e);this.chain=String(o)}return this.chain}async getConnectedWallet(){let e=this.walletType;if(!e||!await this.isConnected())return null;let o=await this.fetchAddress(),r=await this.fetchChainId();return{address:o,chainId:r,chainType:"ethereum",walletType:e}}async sign(e){return new Zo.Web3Provider(new xe(this.provider)).getSigner().signMessage(e)}prepareMessage(e,o,r){let i=window.location.host,n=window.location.origin,a="By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",u=new Date().toISOString();return this.createSiweMessage(e,o,i,n,u,r,a)}};var Ko=require("react-device-detect"),xt=class extends le{constructor(e,o){super("metamask",e,o)}async connect(e){var o;return this.provider.setProvider(window.ethereum),(o=window.ethereum.providers)==null||o.forEach(async r=>{r.isMetaMask&&this.provider.setProvider(r)}),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="";Ko.isMobile||await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=(0,$o.getAddress)(o[0])),!e||e==="")throw new j("Unable to retrieve address");this.connected=!0,this.address=e}catch(e){throw be(e)}}};var qo=require("@ethersproject/address");var Jo=v(require("@coinbase/wallet-sdk"));var $i=()=>{let t=`https://mainnet.infura.io/v3/${et}`,e=1;return new Jo.default({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},Lt=class extends le{constructor(e,o){super("coinbase_wallet",e,o)}async connect(e){return this.provider.setProvider($i()),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let e="",o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=(0,qo.getAddress)(o[0])),!e||e==="")throw new j("Unable to retrieve address");this.connected=!0}catch(e){throw be(e)}}};var ro=v(require("@walletconnect/web3-provider"));var io=class extends le{constructor(o,r,i){super("wallet_connect",r,i);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(i)}async connect(o){return this.provider.setProvider(this._provider),(!await this.isConnected()||o.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return this.provider.walletProvider.connected}async promptConnection(){try{let o="";this.provider.setProvider(this._provider);let r=await Promise.race([this._provider.enable(),oo()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new j("Unable to retrieve address");this.connected=!0}catch(o){throw be(o)}}},At=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},V.getKeys().forEach(e=>{if(e.startsWith("walletconnect")){let o=new ro.default({infuraId:et,storageId:e});o.enable(),this._storageIdToProvider[e]=o;for(let r of o.accounts)this._addressToStorageId[r]=e}})}build(e,o){return new io(this,e,o)}async destroy(){Object.values(this._storageIdToProvider).forEach(async e=>{await e.disconnect()})}getProviderForAddress(e){let o=Bo,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;e===null?o=r():o=this._addressToStorageId[e]||r();let i=new ro.default({infuraId:et,storageId:o});return this._storageIdToProvider[o]=i,i}indexProvider(e){this._storageIdToProvider[e.storageId]=e;for(let o of e.accounts)this._addressToStorageId[o]=e.storageId}};var no=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},Et=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},Yo=()=>{var e;let t=V.get(wt);return t?(e=t.find(o=>o.active))==null?void 0:e.address:null},je=class{constructor(){this.getEthereumProvider=()=>{var e;return((e=this.activeWalletConnector)==null?void 0:e.provider)||new te};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new At,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}).then(()=>this.initialized=!0),this.initialized=!0)}initializeLinkedWallets(e){e.linkedAccounts.forEach(()=>{})}load(){(V.get(wt)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)}),this.save()}save(){let e=this.walletConnectors.map(o=>{var r;return{address:o.address,walletType:o.walletType,active:o.address===((r=this.activeWalletConnector)==null?void 0:r.address)}});V.put(wt,e)}destroy(){this.walletConnectors=[],this.initialized=!1,this.activeWalletConnector=void 0}addWalletConnector(e){this.walletConnectors.find(r=>r.address===e.address&&r.walletType===e.walletType)||this.walletConnectors.push(e)}removeWallet(e){var r;if(this.walletConnectors=this.walletConnectors.filter(i=>i.address!==e),e===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let i=this.walletConnectors[this.walletConnectors.length-1];this.setActiveWallet(i.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){return this.activeWalletConnector?await this.activeWalletConnector.connect({showPrompt:!1})?this.activeWalletConnector.sign(e):null:(console.error("Cannot sign, no wallet is active. Is a wallet connected?"),null)}setActiveWallet(e){let o=this.walletConnectors.find(r=>r.address===e);return o?(this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(e,o){switch(e){case"metamask":return new xt(new te,o);case"coinbase_wallet":return new Lt(new te,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new te,o)}}};function Le(t){return new Date(t*1e3)}function Ki(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:Le(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:Le(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:Le(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:Le(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:Le(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:Le(e.verified_at)};case"github_oauth":return{subject:e.subject,username:e.username,name:e.name,email:e.email,type:e.type,verifiedAt:Le(e.verified_at)};default:throw new p("Unrecognized account type")}})}function Re(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function tt(t){let e=Yo();if(!e)return t.wallet&&console.warn("[Privy] User has linked wallets but no active wallet"),t;let o=t.linkedAccounts.find(i=>i.type==="wallet"&&i.address===e),r=Object.assign({},t);return r.wallet=o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},r}function me(t){if(!t)return null;let e=Ki(t.linked_accounts),o=Re(e,"wallet"),r=Re(e,"email"),i=Re(e,"phone"),n=Re(e,"google_oauth"),a=Re(e,"twitter_oauth"),u=Re(e,"discord_oauth"),f=Re(e,"github_oauth"),m={id:t.id,createdAt:Le(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:a&&{subject:a.subject,username:a.username,name:a.name},discord:u&&{subject:u.subject,username:u.username,email:u.email},github:f&&{subject:f.subject,username:f.username,name:f.name,email:f.email}};return tt(m)}var Qo=()=>"/api/v1/sessions",Xo=()=>"/api/v1/sessions/logout",er=()=>"/api/v1/sessions/fork",tr=()=>"/api/v1/siwe/init",or=()=>"/api/v1/siwe/authenticate",rr=()=>"/api/v1/siwe/link",ir=()=>"/api/v1/passwordless/init",nr=()=>"/api/v1/passwordless/authenticate",sr=()=>"/api/v1/passwordless/link",ar=()=>"/api/v1/passwordless_sms/init",lr=()=>"/api/v1/passwordless_sms/authenticate",dr=()=>"/api/v1/passwordless_sms/link",cr=()=>"/api/v1/oauth/init",pr=()=>"/api/v1/oauth/authenticate",ur=()=>"/api/v1/oauth/link",hr=()=>"/api/v1/siwe/unlink",mr=()=>"/api/v1/passwordless/unlink",fr=()=>"/api/v1/passwordless_sms/unlink",gr=()=>"/api/v1/oauth/unlink";var qi=30,kt=class{constructor(){this.authenticateOnce=new ve(async e=>this._authenticate(e)),this.linkOnce=new ve(async e=>this._link(e)),this.refreshOnce=new ve(this._refresh.bind(this)),this.destroyOnce=new ve(this._destroy.bind(this)),this.forkSessionOnce=new ve(this._forkSession.bind(this))}get token(){try{let e=V.get(Be);return typeof e=="string"?new he(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=V.get(gt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=he.parse(this.token);return e!==null&&!e.isExpired(qi)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:me(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),K(o)}}async _link(e){try{let o=await e.link();return me(o)}catch(o){throw console.warn("Error linking account"),K(o)}}async _refresh(){if(!this.api)throw new p("Session has no API instance");if(!this.client)throw new p("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Qo(),{refresh_token:o},{headers:{authorization:`Bearer ${e}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),me(r.data.user)}catch(r){if(r instanceof Ge&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw K(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Xo(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new p("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(er(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw K(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?V.put(Be,e):V.del(Be)}storeRefreshToken(e){typeof e=="string"?V.put(gt,e):V.del(gt)}};var so,Ze=class{constructor(e){let o=e.apiURL||Do,r=e.timeout||Vo;this.appId=e.appId,this.connectors=new je,so||(so=new kt),this.session=so,this.api=new Ct(e.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new p("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new p("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.connectors.destroy(),this.authFlow=void 0}startAuthFlow(e){e.api=this.api,this.authFlow=e}async unlinkEmail(e){try{let o=await this.api.post(mr(),{address:e});return me(o.data)}catch(o){throw K(o)}}async unlinkPhone(e){try{let o=await this.api.post(fr(),{phoneNumber:e});return me(o.data)}catch(o){throw K(o)}}async unlinkWallet(e){try{let o=await this.api.post(hr(),{address:e});return me(o.data)}catch(o){throw K(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(gr(),{provider:e,subject:o});return me(r.data)}catch(r){throw K(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){var o;return this.session.hasActiveToken()?((o=he.parse(this.session.token))==null?void 0:o.audience)!==this.appId?(await this.logout(),null):this.session.token:!(e!=null&&e.disableAutoRefresh)&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getAppSettings(){try{let e=await this.api.get(`/api/v1/apps/${this.appId}`);return{id:e.data.id,name:e.data.name,verificationKey:e.data.verification_key,logoUrl:e.data.logo_url||void 0,theme:e.data.theme,accentColor:e.data.accent_color||void 0,showWalletLoginFirst:e.data.show_wallet_login_first,allowlistConfig:{errorTitle:e.data.allowlist_config.error_title,errorDetail:e.data.allowlist_config.error_detail,errorCtaText:e.data.allowlist_config.cta_text,errorCtaLink:e.data.allowlist_config.cta_link},walletAuth:e.data.wallet_auth,emailAuth:e.data.email_auth,smsAuth:e.data.sms_auth,googleOAuth:e.data.google_oauth,twitterOAuth:e.data.twitter_oauth,discordOAuth:e.data.discord_oauth,githubOAuth:e.data.github_oauth,termsAndConditionsUrl:e.data.terms_and_conditions_url,privacyPolicyUrl:e.data.privacy_policy_url,createdAt:new Date(e.data.created_at*1e3),updatedAt:new Date(e.data.updated_at*1e3)}}catch(e){throw K(e)}}setActiveWallet(e,o){if(!o.linkedAccounts.map(n=>n.type==="wallet"?n.address:null).includes(e))throw new p("Cannot set an unlinked address as active.");if(!this.connectors.setActiveWallet(e))throw new p("Error setting the active wallet.");return tt(o)}async forkSession(){return await this.session.forkSession()}};var Ti=require("@ethersproject/providers");var _t=require("react");var w=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var ao=(0,_t.createContext)({ready:!1,authenticated:!1,user:null,walletConnectors:null,login:w,linkEmail:w,linkPhone:w,linkWallet:w,linkGoogle:w,linkTwitter:w,linkDiscord:w,linkGithub:w,logout:w,getAccessToken:w,getEthereumProvider:w,getEthersProvider:w,getWeb3jsProvider:w,unlinkEmail:w,unlinkPhone:w,unlinkWallet:w,unlinkGoogle:w,unlinkTwitter:w,unlinkDiscord:w,unlinkGithub:w,setActiveWallet:w,forkSession:w}),N=()=>(0,_t.useContext)(ao);var ot=class{constructor(e,o){this.meta={walletType:o},this.connectors=e,this.walletConnector=this.connectors.createWalletConnector(o,null)}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(or(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),{user:r.data.user,token:r.data.token,refresh_token:r.data.refresh_token,is_new_user:r.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(rr(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),this.connectors.setActiveWallet(this.walletConnector.address)||console.warn("Failed to set active wallet"),r.data}catch(e){throw M(e)}}async promptConnectAndSign(e){let o=await this.walletConnector.connect({showPrompt:!0}),r=o.address,i=o.chainId,n=await e.post(tr(),{address:r}),a=this.walletConnector.prepareMessage(i,r,n.data.nonce),u=await this.walletConnector.sign(a);return{message:a,signature:u}}};var rt=class{constructor(e){this.meta={email:e}}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new p("Email and email code must be set prior to calling authenticate.");try{let e=nr(),o=await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new p("Email and email code must be set prior to calling authenticate.");try{let e=sr();return(await this.api.post(e,{email:this.meta.email,code:this.meta.emailCode})).data}catch(e){throw M(e)}}async sendCodeEmail(e){if(!this.api)throw new p("Auth flow has no API instance");if(e&&(this.meta.email=e),!this.meta.email)throw new p("Email must be set when initialzing authentication.");try{let o=ir();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw M(o)}}};var it=class{constructor(e){this.meta={phoneNumber:e}}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new p("phone number and sms code must be set prior to calling authenticate.");try{let e=lr(),o=await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new p("phone number and sms code must be set prior to calling authenticate.");try{let e=dr();return(await this.api.post(e,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})).data}catch(e){throw M(e)}}async sendSmsCode(e){if(!this.api)throw new p("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),!this.meta.phoneNumber)throw new p("phone nNumber must be set when initialzing authentication.");try{let o=ar();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw M(o)}}};var $e=class{constructor(e,o,r){this.meta={provider:e},this.meta.authorizationCode=o,this.meta.stateCode=r}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new p("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new p("User denied confirmation during OAuth flow");try{let e=pr(),o=await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode});return{user:o.data.user,token:o.data.token,refresh_token:o.data.refresh_token,is_new_user:o.data.is_new_user}}catch(e){throw M(e)}}async link(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new p("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new p("User denied confirmation during OAuth flow");try{let e=ur();return(await this.api.post(e,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode})).data}catch(e){throw M(e)}}async getAuthorizationUrl(){if(!this.api)throw new p("Auth flow has no API instance");if(!this.meta.provider)throw new p("Provider must be set when initialzing OAuth authentication.");try{let e=cr();return(await this.api.post(e,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(e){throw M(e)}}};var uc=require("wicg-inert"),_i=v(require("react-dom")),qt=v(require("styled-components"));var de=require("react");var yr=require("react/jsx-runtime");function wr(t){return(0,yr.jsx)("link",{rel:"prefetch",href:t.src})}var Pt=require("react/jsx-runtime"),Cr=(0,de.createContext)({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:"LANDING",lastScreen:"LANDING",navigate:w,navigateBack:w}),vr=t=>{let e=t.appSettings,o=t.authenticated,r=t.visible,[i,n]=(0,de.useState)("LANDING"),[a,u]=(0,de.useState)("LANDING");(0,de.useEffect)(()=>{o||n("LANDING")},[o]),(0,de.useEffect)(()=>{r||(u("LANDING"),n("LANDING"))},[r]);let f={ready:!!(e!=null&&e.id),app:e,options:t.options,currentScreen:i,lastScreen:a,navigate:m=>{u(i),n(m)},navigateBack:()=>{n(a)}};return(0,Pt.jsxs)(Cr.Provider,{value:f,children:[e&&e.logoUrl&&(0,Pt.jsx)(wr,{src:e.logoUrl}),t.children]})},y=()=>(0,de.useContext)(Cr);var zt=require("react"),Ye=v(require("styled-components"));var Lr=v(require("styled-components"));var lo=require("react/jsx-runtime"),br=({style:t,...e})=>(0,lo.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:(0,lo.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});var co=require("react/jsx-runtime"),xr=({style:t,...e})=>(0,co.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...t},...e,children:(0,co.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});var St=require("react");var po=(0,St.createContext)({isLinking:!1,getAuthMeta:w,getAuthFlow:w,closePrivyModal:w,initLoginWithWallet:w,loginWithWallet:w,loginWithCode:w,initLoginWithEmail:w,initLoginWithSms:w,resendEmailCode:w,resendSmsCode:w,initLoginWithOAuth:w,loginWithOAuth:w}),W=()=>(0,St.useContext)(po);var q=require("react/jsx-runtime"),Ji=()=>(0,q.jsx)("div",{}),Yi=({backFn:t})=>(0,q.jsx)("div",{children:(0,q.jsx)(xr,{onClick:t})}),Qi=t=>(0,q.jsx)("div",{children:(0,q.jsx)("div",{children:(0,q.jsx)(br,{onClick:t.onClose})})});var E=({backFn:t,onClose:e})=>{let{closePrivyModal:o}=W();return(0,q.jsxs)(Xi,{children:[t?(0,q.jsx)(Yi,{backFn:t}):(0,q.jsx)(Ji,{}),(0,q.jsx)(Qi,{onClose:e||o})]})},Xi=Lr.default.div`
13
13
  height: 30px;
14
14
  display: flex;
15
15
  align-items: center;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@privy-io/react-auth",
3
- "version": "1.14.0-beta.1",
3
+ "version": "1.14.0-beta.2",
4
4
  "description": "React client for the Privy Auth API",
5
5
  "keywords": [
6
6
  "authentication",