@privy-io/react-auth 1.16.0 → 1.16.1-beta.1

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 Rn,useState as J}from"react";import So from"axios";import Nn from"axios";var 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}]`:""}`}},ze=class extends ee{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},g=class extends ee{constructor(o,r){super(o,r);this.type="client_error"}};var O=class extends ee{constructor(o,r){super(o,r);this.type="connector_error"}},M=t=>{if(t instanceof ee)return t;if(!Nn.isAxiosError(t))return X(t);if(!t.response)return new ze("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new ze(e||"ApiError",t.response.status,o||r,t)},X=t=>t instanceof ee?t:t instanceof Error?new g(t.message,t):new g(`Internal error: ${t}`);var yr="1.16.0";var wr="https://api.privy.io/v0",_o=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",mt="4df5e2316331463a9130964bd6078dfa",vr=1e4,ae=1400,ko=yr;var $e="privy:token",Ut="privy:refresh_token",Dt="privy:connectors",Cr="walletconnect";var Ft=class{constructor(e,o,r){this.appId=e,this.sdkVersion=ko,this.client=o,this.defaults=r}async get(e,o){try{return await So.get(e,await this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw M(r)}}async post(e,o,r){try{return await So.post(e,o,await this.buildConfig(r))}catch(i){throw M(i)}}async delete(e,o){try{return await So.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}}};import*as br from"jose";var he=class{static parse(e){try{return new he(e)}catch{return null}}constructor(e){this.value=e,this._decoded=br.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 Ee=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 Po=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)}},To=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 Un(){return typeof window<"u"&&window.localStorage?new To:new Po}var V=Un();import{ErrorCode as Dn}from"@ethersproject/logger";var je=class extends O{constructor(){super("Wallet timeout");this.type="wallet_error"}},Le=t=>{if(t instanceof O)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new Ze(t);return t.code===Dn.ACTION_REJECTED&&(e.details=Ie.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new Ze(t):new O("Unknown connector error",t)},Wo=class extends ee{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},Ze=class extends Wo{constructor(o){var n,s,a;let r=o;super(r.message,r.code,r.data);let i=Object.values(Ie).find(d=>d.eipCode===r.code);this.details=i||Ie.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=Ie.E32002_CONNECTION_ALREADY_PENDING:this.details=Ie.E32002_REQUEST_ALREADY_PENDING:(a=r.message)!=null&&a.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=Ie.E32002_WALLET_LOCKED))}},Fn={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}},Gn={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}},Bn={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},...Bn,...Gn},qe={...Fn,...Ie};var Vn=12e4,Io=(t=new je,e=Vn)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),le=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})}async request(e){if(!this.walletProvider)throw new O(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),Io()]).catch(o=>{throw Le(o)})}},Re=class extends le{constructor(o){super(o)}},Gt=class extends le{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 kr}from"@ethersproject/address";import{Web3Provider as jn}from"@ethersproject/providers";import{getAddress as Hn}from"@ethersproject/address";import{Web3Provider as zn}from"@ethersproject/providers";var me=class{constructor(e,o,r){this.createSiweMessage=(e,o,r,i,n,s,a)=>`${r} wants you to sign in with your Ethereum account:
1
+ import{useEffect as Rn,useState as J}from"react";import So from"axios";import Nn from"axios";var 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}]`:""}`}},ze=class extends ee{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},g=class extends ee{constructor(o,r){super(o,r);this.type="client_error"}};var O=class extends ee{constructor(o,r){super(o,r);this.type="connector_error"}},M=t=>{if(t instanceof ee)return t;if(!Nn.isAxiosError(t))return X(t);if(!t.response)return new ze("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new ze(e||"ApiError",t.response.status,o||r,t)},X=t=>t instanceof ee?t:t instanceof Error?new g(t.message,t):new g(`Internal error: ${t}`);var yr="1.16.1-beta.1";var wr="https://api.privy.io/v0",_o=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",mt="4df5e2316331463a9130964bd6078dfa",vr=1e4,ae=1400,ko=yr;var $e="privy:token",Ut="privy:refresh_token",Dt="privy:connectors",Cr="walletconnect";var Ft=class{constructor(e,o,r){this.appId=e,this.sdkVersion=ko,this.client=o,this.defaults=r}async get(e,o){try{return await So.get(e,await this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw M(r)}}async post(e,o,r){try{return await So.post(e,o,await this.buildConfig(r))}catch(i){throw M(i)}}async delete(e,o){try{return await So.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}}};import*as br from"jose";var he=class{static parse(e){try{return new he(e)}catch{return null}}constructor(e){this.value=e,this._decoded=br.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 Ee=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 Po=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)}},To=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 Un(){return typeof window<"u"&&window.localStorage?new To:new Po}var V=Un();import{ErrorCode as Dn}from"@ethersproject/logger";var je=class extends O{constructor(){super("Wallet timeout");this.type="wallet_error"}},Le=t=>{if(t instanceof O)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new Ze(t);return t.code===Dn.ACTION_REJECTED&&(e.details=Ie.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new Ze(t):new O("Unknown connector error",t)},Wo=class extends ee{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},Ze=class extends Wo{constructor(o){var n,s,a;let r=o;super(r.message,r.code,r.data);let i=Object.values(Ie).find(d=>d.eipCode===r.code);this.details=i||Ie.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=Ie.E32002_CONNECTION_ALREADY_PENDING:this.details=Ie.E32002_REQUEST_ALREADY_PENDING:(a=r.message)!=null&&a.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=Ie.E32002_WALLET_LOCKED))}},Fn={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}},Gn={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}},Bn={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},...Bn,...Gn},qe={...Fn,...Ie};var Vn=12e4,Io=(t=new je,e=Vn)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),le=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})}async request(e){if(!this.walletProvider)throw new O(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),Io()]).catch(o=>{throw Le(o)})}},Re=class extends le{constructor(o){super(o)}},Gt=class extends le{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 kr}from"@ethersproject/address";import{Web3Provider as jn}from"@ethersproject/providers";import{getAddress as Hn}from"@ethersproject/address";import{Web3Provider as zn}from"@ethersproject/providers";var me=class{constructor(e,o,r){this.createSiweMessage=(e,o,r,i,n,s,a)=>`${r} wants you to sign in with your Ethereum account:
2
2
  ${o}
3
3
 
4
4
  ${a}
@@ -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=Hn(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(){if(!this.walletType||!await this.isConnected())return null;let o=await this.fetchAddress(),r=await this.fetchChainId();return{address:o,chainId:r,chainType:"ethereum",walletClient:"unknown"}}async setActive(){return!0}async sign(e){return new zn(new Re(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.",a=new Date().toISOString();return this.createSiweMessage(e,o,i,n,a,r,s)}};import{isPossiblePhoneNumber as $n}from"libphonenumber-js/min";var xr=t=>!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Er=t=>$n(String(t),"US"),Bt=t=>{var e=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(e,function(r,i,n,s){return i+i+n+n+s+s});var o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return{r:parseInt((o==null?void 0:o[1])||"00",16),g:parseInt((o==null?void 0:o[2])||"00",16),b:parseInt((o==null?void 0:o[3])||"00",16)}},Lr=(t,e)=>{var o=t.slice(0);let r=[];for(;o.length;)r.push(o.splice(0,e));return r},Me=(t,e=3,o=4)=>{if(!t)return"";let r=2,i=3;if(e+o+r+i>=t.length)return t;let n=t.slice(0,r+e),s=t.slice(t.length-o,t.length);return`${n}...${s}`},Ro=t=>new Promise(e=>setTimeout(e,t)),Ar=(t,e={})=>{let o=e.delayMs||40,r=e.maxAttempts||1e3;return new Promise(async(i,n)=>{let s=!1,a=0;for(;!s&&a<r;)t().then(()=>{s=!0,i()},(...d)=>{s=!0,n(...d)}),a+=1,await Ro(o);s||n(new Error("Exceeded max attempts before resolving function"))})},_r=(...t)=>{let o=t.length-1;return t.map((i,n)=>(n===0&&(i.startsWith("//")||i.endsWith("://"))?i=i.replace(new RegExp("/$"),""):n!==o&&(i=i.replace(new RegExp("/+$"),"")),n!==0&&(i=i.replace(new RegExp("^/+"),"")),i)).join("/")};import{isMobile as Zn}from"react-device-detect";var Vt=class extends me{constructor(e,o){var r;super("metamask",e,o),this.provider.setProvider(window.ethereum),(r=window.ethereum.providers)==null||r.forEach(async i=>{i.isMetaMask&&this.provider.setProvider(i)}),this.subscribeListeners()}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}async isConnected(){let e=await this.connectedMetamaskAddress();return this.address===e}async connectedMetamaskAddress(){let o=await new jn(this.provider).listAccounts();return o.length===0?null:kr(o[0])}disconnect(){console.warn("Metamask does not support programmetic disconnect.")}async promptConnection(){try{let e="";if(!Zn&&(await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.address&&await this.isConnected()))throw new O("Selected the wrong wallet in MetaMask");let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=kr(o[0])),!e||e==="")throw new O("Unable to retrieve address");this.connected=!0,this.address=e}catch(e){throw Le(e)}}async setActive(){if(await this.connectedMetamaskAddress()===this.address)return this.connected=!0,!0;for(;!this.connected;)await Ro(200);return!0}subscribeListeners(){this.provider.on("accountsChanged",e=>{var o;if(e.length>0){let r=e[0];this.connected=((o=this.address)==null?void 0:o.toLowerCase())===(r==null?void 0:r.toLowerCase())}}),this.provider.on("disconnect",()=>{this.connected=!1})}};import{getAddress as qn}from"@ethersproject/address";import Kn from"@coinbase/wallet-sdk";var Jn=t=>{let e=`https://mainnet.infura.io/v3/${mt}`,o=1;return t.makeWeb3Provider(e,o)},Ht,zt=class extends me{constructor(e,o){super("coinbase_wallet",e,o),Ht||(Ht=new Kn({appName:"Privy",darkMode:!1,headlessMode:!1}))}async connect(e){return this.provider.setProvider(Jn(Ht)),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}disconnect(){Ht.disconnect()}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=qn(o[0])),!e||e==="")throw new O("Unable to retrieve address");this.connected=!0}catch(e){throw Le(e)}}};import Sr from"@walletconnect/web3-provider";var Mo=class extends me{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(),Io()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new O("Unable to retrieve address");this.connected=!0}catch(o){throw Le(o)}}disconnect(){}},$t=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},V.getKeys().forEach(e=>{if(e.startsWith("walletconnect")){let o=new Sr({infuraId:mt,storageId:e});o.enable(),this._storageIdToProvider[e]=o;for(let r of o.accounts)this._addressToStorageId[r]=e}})}build(e,o){return new Mo(this,e,o)}async disconnect(){Object.values(this._storageIdToProvider).forEach(async e=>{await e.disconnect()})}getProviderForAddress(e){let o=Cr,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;e===null?o=r():o=this._addressToStorageId[e]||r();let i=new Sr({infuraId:mt,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}};import{getAddress as Yn}from"@ethersproject/address";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},jt=()=>{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},Oo=t=>{let e=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses");return e?!!(t==null?void 0:t.linkedAccounts.filter(r=>r.type=="wallet"&&r.address===Yn(e)).length):!1},Pr=()=>{var e;let t=V.get(Dt);return t?(e=t.find(o=>o.active))==null?void 0:e.address:null},ft=class{constructor(){this.getEthereumProvider=()=>{var e;return((e=this.activeWalletConnector)==null?void 0:e.provider)||new le};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new $t,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}),this.initialized=!0)}initializeLinkedWallets(e){e.linkedAccounts.forEach(()=>{})}load(){(V.get(Dt)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)})}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(Dt,e)}addWalletConnector(e){this.walletConnectors.find(r=>r.address===e.address&&r.walletType===e.walletType)||this.walletConnectors.push(e)}getConnectorByAddress(e){return this.walletConnectors.find(o=>{var r;return((r=o.address)==null?void 0:r.toLowerCase())===e.toLowerCase()})}async 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];await this.setActiveWallet(i.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){if(!this.activeWalletConnector)throw new O("Cannot sign, no wallet is active. Is a wallet connected?");if(!await this.activeWalletConnector.connect({showPrompt:!1}))throw new O("Cannot sign - unable to connect to wallet.");return this.activeWalletConnector.sign(e)}async setActiveWallet(e){let o=this.walletConnectors.find(r=>r.address===e);return o?(await o.setActive(),this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(e,o){switch(e){case"metamask":return new Vt(new le,o);case"coinbase_wallet":return new zt(new le,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new le,o)}}};function Ae(t){return new Date(t*1e3)}function Xn(t){let e=[];for(let o of t){let r=o.type;switch(o.type){case"wallet":let i={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at),chainType:o.chain_type,walletClient:o.wallet_client};e.push(i);break;case"email":let n={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(n);break;case"phone":let s={number:o.phoneNumber,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(s);break;case"google_oauth":let a={subject:o.subject,email:o.email,name:o.name,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(a);break;case"twitter_oauth":let d={subject:o.subject,username:o.username,name:o.name,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(d);break;case"discord_oauth":let p={subject:o.subject,username:o.username,email:o.email,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(p);break;case"github_oauth":let E={subject:o.subject,username:o.username,name:o.name,email:o.email,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(E);break;default:console.warn(`Unrecognized account type: ${r}. Please consider upgrading the Privy SDK.`)}}return e}function Ne(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function gt(t){let e=Pr();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,walletClient:o.walletClient},r}var fe=t=>t==null?void 0:t.linkedAccounts.find(e=>e.type==="wallet"&&e.walletClient==="privy");function ge(t){if(!t)return null;let e=Xn(t.linked_accounts),o=Ne(e,"wallet"),r=Ne(e,"email"),i=Ne(e,"phone"),n=Ne(e,"google_oauth"),s=Ne(e,"twitter_oauth"),a=Ne(e,"discord_oauth"),d=Ne(e,"github_oauth"),p={id:t.id,createdAt:Ae(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,walletClient:o.walletClient},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:a&&{subject:a.subject,username:a.username,email:a.email},github:d&&{subject:d.subject,username:d.username,name:d.name,email:d.email}};return gt(p)}var Tr=()=>"/api/v1/sessions",Wr=()=>"/api/v1/sessions/logout",Ir=()=>"/api/v1/sessions/fork",Rr=()=>"/api/v1/siwe/init",Mr=()=>"/api/v1/siwe/authenticate",Nr=()=>"/api/v1/siwe/link",Or=()=>"/api/v1/passwordless/init",Ur=()=>"/api/v1/passwordless/authenticate",Dr=()=>"/api/v1/passwordless/link",Fr=()=>"/api/v1/passwordless_sms/init",Gr=()=>"/api/v1/passwordless_sms/authenticate",Br=()=>"/api/v1/passwordless_sms/link",Vr=()=>"/api/v1/oauth/init",Hr=()=>"/api/v1/oauth/authenticate",zr=()=>"/api/v1/oauth/link",$r=()=>"/api/v1/siwe/unlink",jr=()=>"/api/v1/passwordless/unlink",Zr=()=>"/api/v1/passwordless_sms/unlink",qr=()=>"/api/v1/oauth/unlink";var Qn=30,Zt=class{constructor(){this.authenticateOnce=new Ee(async e=>this._authenticate(e)),this.linkOnce=new Ee(async e=>this._link(e)),this.refreshOnce=new Ee(this._refresh.bind(this)),this.destroyOnce=new Ee(this._destroy.bind(this)),this.forkSessionOnce=new Ee(this._forkSession.bind(this))}get token(){try{let e=V.get($e);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(Ut);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(Qn)}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:ge(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),X(o)}}async _link(e){try{let o=await e.link();return ge(o)}catch(o){throw console.warn("Error linking account"),X(o)}}async _refresh(){if(!this.api)throw new g("Session has no API instance");if(!this.client)throw new g("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(Tr(),{refresh_token:o},{headers:{authorization:`Bearer ${e}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),ge(r.data.user)}catch(r){if(r instanceof ze&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw X(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Wr(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new g("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(Ir(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw X(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?V.put($e,e):V.del($e)}storeRefreshToken(e){typeof e=="string"?V.put(Ut,e):V.del(Ut)}};var Uo,yt=class{constructor(e){let o=e.apiURL||wr,r=e.timeout||vr;this.appId=e.appId,this.connectors=new ft,Uo||(Uo=new Zt),this.session=Uo,this.api=new Ft(e.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new g("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new g("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.authFlow=void 0}startAuthFlow(e){e.api=this.api,this.authFlow=e}async unlinkEmail(e){try{let o=await this.api.post(jr(),{address:e});return ge(o.data)}catch(o){throw X(o)}}async unlinkPhone(e){try{let o=await this.api.post(Zr(),{phoneNumber:e});return ge(o.data)}catch(o){throw X(o)}}async unlinkWallet(e){try{let o=await this.api.post($r(),{address:e});return this.connectors.removeWallet(e),ge(o.data)}catch(o){throw X(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(qr(),{provider:e,subject:o});return ge(r.data)}catch(r){throw X(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 X(e)}}async setActiveWallet(e,o){if(!o.linkedAccounts.map(n=>n.type==="wallet"?n.address:null).includes(e))throw new g("Cannot set an unlinked address as active.");if(!await this.connectors.setActiveWallet(e))throw new g("Error setting the active wallet.");return gt(o)}async forkSession(){return await this.session.forkSession()}};import{Web3Provider as i1}from"@ethersproject/providers";import{createContext as es,useContext as ts}from"react";var v=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var Do=es({ready:!1,authenticated:!1,user:null,walletConnectors:null,login:v,linkEmail:v,linkPhone:v,linkWallet:v,linkGoogle:v,linkTwitter:v,linkDiscord:v,linkGithub:v,logout:v,getAccessToken:v,getEthereumProvider:v,getEthersProvider:v,getWeb3jsProvider:v,unlinkEmail:v,unlinkPhone:v,unlinkWallet:v,unlinkGoogle:v,unlinkTwitter:v,unlinkDiscord:v,unlinkGithub:v,setActiveWallet:v,forkSession:v,createWallet:v,signMessage:v}),D=()=>ts(Do);var wt=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 g("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(Mr(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),await 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 g("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(Nr(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),await 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(Rr(),{address:r}),s=this.walletConnector.prepareMessage(i,r,n.data.nonce),a=await this.walletConnector.sign(s);return{message:s,signature:a}}};var vt=class{constructor(e){this.meta={email:e}}async authenticate(){if(!this.api)throw new g("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new g("Email and email code must be set prior to calling authenticate.");try{let e=Ur(),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 g("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new g("Email and email code must be set prior to calling authenticate.");try{let e=Dr();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 g("Auth flow has no API instance");if(e&&(this.meta.email=e),!this.meta.email)throw new g("Email must be set when initialzing authentication.");try{let o=Or();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw M(o)}}};var Ct=class{constructor(e){this.meta={phoneNumber:e}}async authenticate(){if(!this.api)throw new g("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new g("phone number and sms code must be set prior to calling authenticate.");try{let e=Gr(),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 g("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new g("phone number and sms code must be set prior to calling authenticate.");try{let e=Br();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 g("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),!this.meta.phoneNumber)throw new g("phone nNumber must be set when initialzing authentication.");try{let o=Fr();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw M(o)}}};var Ke=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 g("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new g("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new g("User denied confirmation during OAuth flow");try{let e=Hr(),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 g("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new g("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new g("User denied confirmation during OAuth flow");try{let e=zr();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 g("Auth flow has no API instance");if(!this.meta.provider)throw new g("Provider must be set when initialzing OAuth authentication.");try{let e=Vr();return(await this.api.post(e,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(e){throw M(e)}}};import{useRef as os,useEffect as rs}from"react";var qt=class{constructor(){this.callbacks={}}enqueue(e,o){this.callbacks[e]=o}dequeue(e,o){let r=this.callbacks[o];if(!r)throw new Error(`cannot dequeue ${e} event: no event found for id ${o}`);switch(delete this.callbacks[o],e){case"privy:iframe:ready":return r;case"privy:wallet:create":return r;case"privy:wallet:sign":return r;case"privy:wallet:recover":return r;default:throw new Error(`invalid wallet event type ${e}`)}}};import{jsx as as}from"react/jsx-runtime";var is=function(t){return()=>`id-${t++}`}(0);function ns(t){return typeof t.event=="string"&&/^privy:.+/.test(t.event)}function Kt(t){return t.error!==void 0}var bt=new qt;function Jt(t,e,o){let r=o.contentWindow;if(!r)throw new Error("iframe not initialized");return new Promise((i,n)=>{let s=is();bt.enqueue(s,{resolve:i,reject:n}),r.postMessage({id:s,event:t,data:e},"*")})}function ss(t){switch(t.event){case"privy:iframe:ready":let e=bt.dequeue(t.event,t.id);return Kt(t)?e.reject(new Error(t.error.message)):e.resolve(t.data);case"privy:wallet:create":let o=bt.dequeue(t.event,t.id);return Kt(t)?o.reject(new Error(t.error.message)):o.resolve(t.data);case"privy:wallet:sign":let r=bt.dequeue(t.event,t.id);return Kt(t)?r.reject(new Error(t.error.message)):r.resolve(t.data);case"privy:wallet:recover":let i=bt.dequeue(t.event,t.id);return Kt(t)?i.reject(new Error(t.error.message)):i.resolve(t.data)}}function Kr(t){let e=os(null);return rs(()=>{let o=e.current;if(!o)return;function r(a){a&&a.origin===t.origin&&ns(a.data)&&ss(a.data)}let i={create(a){return Jt("privy:wallet:create",a,o)},sign(a){return Jt("privy:wallet:sign",a,o)},recover(a){return Jt("privy:wallet:recover",a,o)}};window.addEventListener("message",r);let n=()=>t.onLoad(i),s=(...a)=>{console.error("privy iframe failed to load: ",...a),t.onLoadFailed()};return Ar(()=>Jt("privy:iframe:ready",{},o)).then(n,s),()=>window.removeEventListener("message",r)},[e.current]),as("iframe",{ref:e,width:"0",height:"0",style:{visibility:"hidden"},src:_r(t.origin,`/apps/${t.appId}/embedded-wallets`)})}import"wicg-inert";import Xl from"react-dom";import gr from"styled-components";import{createContext as cs,useContext as ds,useEffect as Fo,useState as Yr}from"react";import{jsx as ls}from"react/jsx-runtime";function Jr(t){return ls("link",{rel:"prefetch",href:t.src})}import{jsx as ps,jsxs as us}from"react/jsx-runtime";var ye="LANDING",Xr=cs({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:ye,lastScreen:ye,navigate:v,navigateBack:v}),Qr=t=>{let e=t.appSettings,o=t.authenticated,r=t.visible,[i,n]=Yr(t.initialScreen||ye),[s,a]=Yr(t.initialScreen||ye);Fo(()=>{o||n(ye)},[o]),Fo(()=>{r||(a(ye),n(ye))},[r]),Fo(()=>{t.initialScreen&&i===ye&&(n(t.initialScreen),a(t.initialScreen))},[t.initialScreen]);let d=t.initialScreen&&i===ye?t.initialScreen:i,p={ready:!!(e!=null&&e.id),app:e,options:t.options,data:t.data,currentScreen:d,lastScreen:s,navigate:E=>{a(i),n(E)},navigateBack:()=>{n(s)}};return us(Xr.Provider,{value:p,children:[e&&e.logoUrl&&ps(Jr,{src:e.logoUrl}),t.children]})},C=()=>ds(Xr);import{useState as na}from"react";import et from"styled-components";import fs from"styled-components";import{jsx as ei}from"react/jsx-runtime";var ti=({style:t,...e})=>ei("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:ei("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});import{jsx as oi}from"react/jsx-runtime";var ri=({style:t,...e})=>oi("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:oi("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});import{createContext as hs,useContext as ms}from"react";var Go=hs({isLinking:!1,linkingHint:null,activeStatus:null,getAuthMeta:v,getAuthFlow:v,closePrivyModal:v,initLoginWithWallet:v,loginWithWallet:v,loginWithCode:v,initLoginWithEmail:v,initLoginWithSms:v,resendEmailCode:v,resendSmsCode:v,initLoginWithOAuth:v,loginWithOAuth:v,refreshUser:v,walletProxy:null}),_=()=>ms(Go);import{jsx as we,jsxs as Cs}from"react/jsx-runtime";var gs=()=>we("div",{}),ys=({backFn:t})=>we("div",{children:we(ri,{onClick:t})}),ws=t=>we("div",{children:we("div",{children:we(ti,{onClick:t.onClose})})});var L=({backFn:t,onClose:e})=>{let{closePrivyModal:o}=_();return Cs(vs,{children:[t?we(ys,{backFn:t}):we(gs,{}),we(ws,{onClose:e||(()=>o())})]})},vs=fs.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=Hn(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(){if(!this.walletType||!await this.isConnected())return null;let o=await this.fetchAddress(),r=await this.fetchChainId();return{address:o,chainId:r,chainType:"ethereum",walletClient:"unknown"}}async setActive(){return!0}async sign(e){return new zn(new Re(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.",a=new Date().toISOString();return this.createSiweMessage(e,o,i,n,a,r,s)}};import{isPossiblePhoneNumber as $n}from"libphonenumber-js/min";var xr=t=>!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Er=t=>$n(String(t),"US"),Bt=t=>{var e=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(e,function(r,i,n,s){return i+i+n+n+s+s});var o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return{r:parseInt((o==null?void 0:o[1])||"00",16),g:parseInt((o==null?void 0:o[2])||"00",16),b:parseInt((o==null?void 0:o[3])||"00",16)}},Lr=(t,e)=>{var o=t.slice(0);let r=[];for(;o.length;)r.push(o.splice(0,e));return r},Me=(t,e=3,o=4)=>{if(!t)return"";let r=2,i=3;if(e+o+r+i>=t.length)return t;let n=t.slice(0,r+e),s=t.slice(t.length-o,t.length);return`${n}...${s}`},Ro=t=>new Promise(e=>setTimeout(e,t)),Ar=(t,e={})=>{let o=e.delayMs||40,r=e.maxAttempts||1e3;return new Promise(async(i,n)=>{let s=!1,a=0;for(;!s&&a<r;)t().then(()=>{s=!0,i()},(...d)=>{s=!0,n(...d)}),a+=1,await Ro(o);s||n(new Error("Exceeded max attempts before resolving function"))})},_r=(...t)=>{let o=t.length-1;return t.map((i,n)=>(n===0&&(i.startsWith("//")||i.endsWith("://"))?i=i.replace(new RegExp("/$"),""):n!==o&&(i=i.replace(new RegExp("/+$"),"")),n!==0&&(i=i.replace(new RegExp("^/+"),"")),i)).join("/")};import{isMobile as Zn}from"react-device-detect";var Vt=class extends me{constructor(e,o){var r;super("metamask",e,o),this.provider.setProvider(window.ethereum),(r=window.ethereum.providers)==null||r.forEach(async i=>{i.isMetaMask&&this.provider.setProvider(i)}),this.subscribeListeners()}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}async isConnected(){let e=await this.connectedMetamaskAddress();return this.address===e}async connectedMetamaskAddress(){let o=await new jn(this.provider).listAccounts();return o.length===0?null:kr(o[0])}disconnect(){console.warn("Metamask does not support programmetic disconnect.")}async promptConnection(){try{let e="";if(!Zn&&(await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.address&&await this.isConnected()))throw new O("Selected the wrong wallet in MetaMask");let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(e=kr(o[0])),!e||e==="")throw new O("Unable to retrieve address");this.connected=!0,this.address=e}catch(e){throw Le(e)}}async setActive(){if(await this.connectedMetamaskAddress()===this.address)return this.connected=!0,!0;for(;!this.connected;)await Ro(200);return!0}subscribeListeners(){this.provider.on("accountsChanged",e=>{var o;if(e.length>0){let r=e[0];this.connected=((o=this.address)==null?void 0:o.toLowerCase())===(r==null?void 0:r.toLowerCase())}}),this.provider.on("disconnect",()=>{this.connected=!1})}};import{getAddress as qn}from"@ethersproject/address";import Kn from"@coinbase/wallet-sdk";var Jn=t=>{let e=`https://mainnet.infura.io/v3/${mt}`,o=1;return t.makeWeb3Provider(e,o)},Ht,zt=class extends me{constructor(e,o){super("coinbase_wallet",e,o),Ht||(Ht=new Kn({appName:"Privy",darkMode:!1,headlessMode:!1}))}async connect(e){return this.provider.setProvider(Jn(Ht)),(!await this.isConnected()||e.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}disconnect(){Ht.disconnect()}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=qn(o[0])),!e||e==="")throw new O("Unable to retrieve address");this.connected=!0}catch(e){throw Le(e)}}};import Sr from"@walletconnect/web3-provider";var Mo=class extends me{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(),Io()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new O("Unable to retrieve address");this.connected=!0}catch(o){throw Le(o)}}disconnect(){}},$t=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},V.getKeys().forEach(e=>{if(e.startsWith("walletconnect")){let o=new Sr({infuraId:mt,storageId:e});o.enable(),this._storageIdToProvider[e]=o;for(let r of o.accounts)this._addressToStorageId[r]=e}})}build(e,o){return new Mo(this,e,o)}async disconnect(){Object.values(this._storageIdToProvider).forEach(async e=>{await e.disconnect()})}getProviderForAddress(e){let o=Cr,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;e===null?o=r():o=this._addressToStorageId[e]||r();let i=new Sr({infuraId:mt,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}};import{getAddress as Yn}from"@ethersproject/address";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},jt=()=>{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},Oo=t=>{let e=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses");return e?!!(t==null?void 0:t.linkedAccounts.filter(r=>r.type=="wallet"&&r.address===Yn(e)).length):!1},Pr=()=>{var e;let t=V.get(Dt);return t?(e=t.find(o=>o.active))==null?void 0:e.address:null},ft=class{constructor(){this.getEthereumProvider=()=>{var e;return((e=this.activeWalletConnector)==null?void 0:e.provider)||new le};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new $t,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}),this.initialized=!0)}initializeLinkedWallets(e){e.linkedAccounts.forEach(()=>{})}load(){(V.get(Dt)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)})}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(Dt,e)}addWalletConnector(e){this.walletConnectors.find(r=>r.address===e.address&&r.walletType===e.walletType)||this.walletConnectors.push(e)}getConnectorByAddress(e){return this.walletConnectors.find(o=>{var r;return((r=o.address)==null?void 0:r.toLowerCase())===e.toLowerCase()})}async 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];await this.setActiveWallet(i.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){if(!this.activeWalletConnector)throw new O("Cannot sign, no wallet is active. Is a wallet connected?");if(!await this.activeWalletConnector.connect({showPrompt:!1}))throw new O("Cannot sign - unable to connect to wallet.");return this.activeWalletConnector.sign(e)}async setActiveWallet(e){let o=this.walletConnectors.find(r=>r.address===e);return o?(await o.setActive(),this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(e,o){switch(e){case"metamask":return new Vt(new le,o);case"coinbase_wallet":return new zt(new le,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new le,o)}}};function Ae(t){return new Date(t*1e3)}function Xn(t){let e=[];for(let o of t){let r=o.type;switch(o.type){case"wallet":let i={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at),chainType:o.chain_type,walletClient:o.wallet_client};e.push(i);break;case"email":let n={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(n);break;case"phone":let s={number:o.phoneNumber,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(s);break;case"google_oauth":let a={subject:o.subject,email:o.email,name:o.name,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(a);break;case"twitter_oauth":let d={subject:o.subject,username:o.username,name:o.name,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(d);break;case"discord_oauth":let p={subject:o.subject,username:o.username,email:o.email,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(p);break;case"github_oauth":let E={subject:o.subject,username:o.username,name:o.name,email:o.email,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(E);break;default:console.warn(`Unrecognized account type: ${r}. Please consider upgrading the Privy SDK.`)}}return e}function Ne(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function gt(t){let e=Pr();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,walletClient:o.walletClient},r}var fe=t=>t==null?void 0:t.linkedAccounts.find(e=>e.type==="wallet"&&e.walletClient==="privy");function ge(t){if(!t)return null;let e=Xn(t.linked_accounts),o=Ne(e,"wallet"),r=Ne(e,"email"),i=Ne(e,"phone"),n=Ne(e,"google_oauth"),s=Ne(e,"twitter_oauth"),a=Ne(e,"discord_oauth"),d=Ne(e,"github_oauth"),p={id:t.id,createdAt:Ae(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,walletClient:o.walletClient},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:a&&{subject:a.subject,username:a.username,email:a.email},github:d&&{subject:d.subject,username:d.username,name:d.name,email:d.email}};return gt(p)}var Tr=()=>"/api/v1/sessions",Wr=()=>"/api/v1/sessions/logout",Ir=()=>"/api/v1/sessions/fork",Rr=()=>"/api/v1/siwe/init",Mr=()=>"/api/v1/siwe/authenticate",Nr=()=>"/api/v1/siwe/link",Or=()=>"/api/v1/passwordless/init",Ur=()=>"/api/v1/passwordless/authenticate",Dr=()=>"/api/v1/passwordless/link",Fr=()=>"/api/v1/passwordless_sms/init",Gr=()=>"/api/v1/passwordless_sms/authenticate",Br=()=>"/api/v1/passwordless_sms/link",Vr=()=>"/api/v1/oauth/init",Hr=()=>"/api/v1/oauth/authenticate",zr=()=>"/api/v1/oauth/link",$r=()=>"/api/v1/siwe/unlink",jr=()=>"/api/v1/passwordless/unlink",Zr=()=>"/api/v1/passwordless_sms/unlink",qr=()=>"/api/v1/oauth/unlink";var Qn=30,Zt=class{constructor(){this.authenticateOnce=new Ee(async e=>this._authenticate(e)),this.linkOnce=new Ee(async e=>this._link(e)),this.refreshOnce=new Ee(this._refresh.bind(this)),this.destroyOnce=new Ee(this._destroy.bind(this)),this.forkSessionOnce=new Ee(this._forkSession.bind(this))}get token(){try{let e=V.get($e);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(Ut);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(Qn)}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:ge(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),X(o)}}async _link(e){try{let o=await e.link();return ge(o)}catch(o){throw console.warn("Error linking account"),X(o)}}async _refresh(){if(!this.api)throw new g("Session has no API instance");if(!this.client)throw new g("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(Tr(),{refresh_token:o},{headers:{authorization:`Bearer ${e}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),ge(r.data.user)}catch(r){if(r instanceof ze&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw X(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Wr(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new g("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(Ir(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw X(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?V.put($e,e):V.del($e)}storeRefreshToken(e){typeof e=="string"?V.put(Ut,e):V.del(Ut)}};var Uo,yt=class{constructor(e){let o=e.apiURL||wr,r=e.timeout||vr;this.appId=e.appId,this.connectors=new ft,Uo||(Uo=new Zt),this.session=Uo,this.api=new Ft(e.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new g("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new g("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.authFlow=void 0}startAuthFlow(e){e.api=this.api,this.authFlow=e}async unlinkEmail(e){try{let o=await this.api.post(jr(),{address:e});return ge(o.data)}catch(o){throw X(o)}}async unlinkPhone(e){try{let o=await this.api.post(Zr(),{phoneNumber:e});return ge(o.data)}catch(o){throw X(o)}}async unlinkWallet(e){try{let o=await this.api.post($r(),{address:e});return this.connectors.removeWallet(e),ge(o.data)}catch(o){throw X(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(qr(),{provider:e,subject:o});return ge(r.data)}catch(r){throw X(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 X(e)}}async setActiveWallet(e,o){if(!o.linkedAccounts.map(n=>n.type==="wallet"?n.address:null).includes(e))throw new g("Cannot set an unlinked address as active.");if(!await this.connectors.setActiveWallet(e))throw new g("Error setting the active wallet.");return gt(o)}async forkSession(){return await this.session.forkSession()}};import{Web3Provider as a1}from"@ethersproject/providers";import{createContext as es,useContext as ts}from"react";var v=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var Do=es({ready:!1,authenticated:!1,user:null,walletConnectors:null,login:v,linkEmail:v,linkPhone:v,linkWallet:v,linkGoogle:v,linkTwitter:v,linkDiscord:v,linkGithub:v,logout:v,getAccessToken:v,getEthereumProvider:v,getEthersProvider:v,getWeb3jsProvider:v,unlinkEmail:v,unlinkPhone:v,unlinkWallet:v,unlinkGoogle:v,unlinkTwitter:v,unlinkDiscord:v,unlinkGithub:v,setActiveWallet:v,forkSession:v,createWallet:v,signMessage:v}),D=()=>ts(Do);var wt=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 g("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(Mr(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),await 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 g("Auth flow has no API instance");try{let{message:e,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(Nr(),{message:e,signature:o});return this.connectors.addWalletConnector(this.walletConnector),await 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(Rr(),{address:r}),s=this.walletConnector.prepareMessage(i,r,n.data.nonce),a=await this.walletConnector.sign(s);return{message:s,signature:a}}};var vt=class{constructor(e){this.meta={email:e}}async authenticate(){if(!this.api)throw new g("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new g("Email and email code must be set prior to calling authenticate.");try{let e=Ur(),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 g("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new g("Email and email code must be set prior to calling authenticate.");try{let e=Dr();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 g("Auth flow has no API instance");if(e&&(this.meta.email=e),!this.meta.email)throw new g("Email must be set when initialzing authentication.");try{let o=Or();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw M(o)}}};var Ct=class{constructor(e){this.meta={phoneNumber:e}}async authenticate(){if(!this.api)throw new g("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new g("phone number and sms code must be set prior to calling authenticate.");try{let e=Gr(),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 g("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new g("phone number and sms code must be set prior to calling authenticate.");try{let e=Br();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 g("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),!this.meta.phoneNumber)throw new g("phone nNumber must be set when initialzing authentication.");try{let o=Fr();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw M(o)}}};var Ke=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 g("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new g("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new g("User denied confirmation during OAuth flow");try{let e=Hr(),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 g("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new g("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new g("User denied confirmation during OAuth flow");try{let e=zr();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 g("Auth flow has no API instance");if(!this.meta.provider)throw new g("Provider must be set when initialzing OAuth authentication.");try{let e=Vr();return(await this.api.post(e,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(e){throw M(e)}}};import{useRef as os,useEffect as rs}from"react";var qt=class{constructor(){this.callbacks={}}enqueue(e,o){this.callbacks[e]=o}dequeue(e,o){let r=this.callbacks[o];if(!r)throw new Error(`cannot dequeue ${e} event: no event found for id ${o}`);switch(delete this.callbacks[o],e){case"privy:iframe:ready":return r;case"privy:wallet:create":return r;case"privy:wallet:sign":return r;case"privy:wallet:recover":return r;default:throw new Error(`invalid wallet event type ${e}`)}}};import{jsx as as}from"react/jsx-runtime";var is=function(t){return()=>`id-${t++}`}(0);function ns(t){return typeof t.event=="string"&&/^privy:.+/.test(t.event)}function Kt(t){return t.error!==void 0}var bt=new qt;function Jt(t,e,o){let r=o.contentWindow;if(!r)throw new Error("iframe not initialized");return new Promise((i,n)=>{let s=is();bt.enqueue(s,{resolve:i,reject:n}),r.postMessage({id:s,event:t,data:e},"*")})}function ss(t){switch(t.event){case"privy:iframe:ready":let e=bt.dequeue(t.event,t.id);return Kt(t)?e.reject(new Error(t.error.message)):e.resolve(t.data);case"privy:wallet:create":let o=bt.dequeue(t.event,t.id);return Kt(t)?o.reject(new Error(t.error.message)):o.resolve(t.data);case"privy:wallet:sign":let r=bt.dequeue(t.event,t.id);return Kt(t)?r.reject(new Error(t.error.message)):r.resolve(t.data);case"privy:wallet:recover":let i=bt.dequeue(t.event,t.id);return Kt(t)?i.reject(new Error(t.error.message)):i.resolve(t.data)}}function Kr(t){let e=os(null);return rs(()=>{let o=e.current;if(!o)return;function r(a){a&&a.origin===t.origin&&ns(a.data)&&ss(a.data)}let i={create(a){return Jt("privy:wallet:create",a,o)},sign(a){return Jt("privy:wallet:sign",a,o)},recover(a){return Jt("privy:wallet:recover",a,o)}};window.addEventListener("message",r);let n=()=>t.onLoad(i),s=(...a)=>{console.error("privy iframe failed to load: ",...a),t.onLoadFailed()};return Ar(()=>Jt("privy:iframe:ready",{},o)).then(n,s),()=>window.removeEventListener("message",r)},[e.current]),as("iframe",{ref:e,width:"0",height:"0",style:{visibility:"hidden"},src:_r(t.origin,`/apps/${t.appId}/embedded-wallets`)})}import"wicg-inert";import{useRef as Xl}from"react";import Ql from"react-dom";import gr from"styled-components";import{createContext as cs,useContext as ds,useEffect as Fo,useState as Yr}from"react";import{jsx as ls}from"react/jsx-runtime";function Jr(t){return ls("link",{rel:"prefetch",href:t.src})}import{jsx as ps,jsxs as us}from"react/jsx-runtime";var ye="LANDING",Xr=cs({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:ye,lastScreen:ye,navigate:v,navigateBack:v}),Qr=t=>{let e=t.appSettings,o=t.authenticated,r=t.visible,[i,n]=Yr(t.initialScreen||ye),[s,a]=Yr(t.initialScreen||ye);Fo(()=>{o||n(ye)},[o]),Fo(()=>{r||(a(ye),n(ye))},[r]),Fo(()=>{t.initialScreen&&i===ye&&(n(t.initialScreen),a(t.initialScreen))},[t.initialScreen]);let d=t.initialScreen&&i===ye?t.initialScreen:i,p={ready:!!(e!=null&&e.id),app:e,options:t.options,data:t.data,currentScreen:d,lastScreen:s,navigate:E=>{a(i),n(E)},navigateBack:()=>{n(s)}};return us(Xr.Provider,{value:p,children:[e&&e.logoUrl&&ps(Jr,{src:e.logoUrl}),t.children]})},C=()=>ds(Xr);import{useState as na}from"react";import et from"styled-components";import fs from"styled-components";import{jsx as ei}from"react/jsx-runtime";var ti=({style:t,...e})=>ei("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:ei("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});import{jsx as oi}from"react/jsx-runtime";var ri=({style:t,...e})=>oi("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:oi("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});import{createContext as hs,useContext as ms}from"react";var Go=hs({isLinking:!1,linkingHint:null,activeStatus:null,getAuthMeta:v,getAuthFlow:v,closePrivyModal:v,initLoginWithWallet:v,loginWithWallet:v,loginWithCode:v,initLoginWithEmail:v,initLoginWithSms:v,resendEmailCode:v,resendSmsCode:v,initLoginWithOAuth:v,loginWithOAuth:v,refreshUser:v,walletProxy:null}),_=()=>ms(Go);import{jsx as we,jsxs as Cs}from"react/jsx-runtime";var gs=()=>we("div",{}),ys=({backFn:t})=>we("div",{children:we(ri,{onClick:t})}),ws=t=>we("div",{children:we("div",{children:we(ti,{onClick:t.onClose})})});var L=({backFn:t,onClose:e})=>{let{closePrivyModal:o}=_();return Cs(vs,{children:[t?we(ys,{backFn:t}):we(gs,{}),we(ws,{onClose:e||(()=>o())})]})},vs=fs.div`
13
13
  height: 30px;
14
14
  display: flex;
15
15
  align-items: center;
@@ -872,7 +872,7 @@ Resources:
872
872
  align-items: center;
873
873
  gap: 8px;
874
874
  }
875
- `,h2=rr($i)`
875
+ `,g2=rr($i)`
876
876
  && {
877
877
  border: 1px solid var(--light-theme-bg-3);
878
878
  color: var(--light-theme-fg-1);
@@ -1614,7 +1614,7 @@ Resources:
1614
1614
  display: none;
1615
1615
  }
1616
1616
  }
1617
- `;import{useEffect as Ql}from"react";import{useEffect as bn,useState as xn}from"react";import Lo from"styled-components";import{Fragment as Fl,jsx as Be,jsxs as Eo}from"react/jsx-runtime";var En={google:{name:"Google",component:io},discord:{name:"Discord",component:to},github:{name:"Github",component:oo},twitter:{name:"Twitter",component:eo}},Ml=t=>t.charAt(0).toUpperCase()+t.slice(1),fr=()=>{let t=new URL(window.location.href);t.searchParams.delete("privy_oauth_code"),t.searchParams.delete("privy_oauth_provider"),t.searchParams.delete("privy_oauth_state"),window.history.pushState({},"",t)},Ln=()=>{var f;let[t,e]=xn(!1),[o,r]=xn(void 0),{getAuthMeta:i,initLoginWithOAuth:n,loginWithOAuth:s,closePrivyModal:a}=_(),{ready:d}=D(),p=((f=i())==null?void 0:f.provider)||"google",E=En[p].name,k=En[p].component;bn(()=>{!d||s().then(()=>{fr(),e(!0)}).catch(c=>{let S={retryable:!1,message:"Authentication failed."};c.message.includes("Another user has already linked this")?S.detail="This account has already been linked to another user.":c.message==="Invalid code during oauth flow."?(S.retryable=!0,S.detail="Something went wrong. Try again."):c.message==="User denied confirmation during OAuth flow"&&(S.detail=`Retry and check ${Ml(p)} to finish connecting your account.`,S.retryable=!0),fr(),r(S)})},[d]),bn(()=>{if(!t)return;let c=setTimeout(a,ae);return()=>clearTimeout(c)},[t]);let w=t?`Successfully connected with ${E}`:o?o.message:`Verifying connection to ${E}`,m="";return t?m="You\u2019re good to go!":o?m=o.detail:m="Just a few moments more",Eo(Fl,{children:[Be(L,{}),Eo(Nl,{children:[Be(Ul,{children:Eo("div",{children:[Be(Qe,{success:t,fail:!!o}),Be(k,{style:{width:"38px",height:"38px"},logoFill:"primary"})]})}),Eo(Ol,{children:[Be("h3",{children:w}),Be("p",{children:m})]}),Be(Dl,{onClick:()=>{fr(),n(p),r(void 0)},visible:!t&&(o==null?void 0:o.retryable),disabled:!t&&!(o!=null&&o.retryable),children:"Retry"})]})]})},Nl=Lo.div`
1617
+ `;import{useEffect as e1}from"react";import{useEffect as bn,useState as xn}from"react";import Lo from"styled-components";import{Fragment as Fl,jsx as Be,jsxs as Eo}from"react/jsx-runtime";var En={google:{name:"Google",component:io},discord:{name:"Discord",component:to},github:{name:"Github",component:oo},twitter:{name:"Twitter",component:eo}},Ml=t=>t.charAt(0).toUpperCase()+t.slice(1),fr=()=>{let t=new URL(window.location.href);t.searchParams.delete("privy_oauth_code"),t.searchParams.delete("privy_oauth_provider"),t.searchParams.delete("privy_oauth_state"),window.history.pushState({},"",t)},Ln=()=>{var f;let[t,e]=xn(!1),[o,r]=xn(void 0),{getAuthMeta:i,initLoginWithOAuth:n,loginWithOAuth:s,closePrivyModal:a}=_(),{ready:d}=D(),p=((f=i())==null?void 0:f.provider)||"google",E=En[p].name,k=En[p].component;bn(()=>{!d||s().then(()=>{fr(),e(!0)}).catch(c=>{let S={retryable:!1,message:"Authentication failed."};c.message.includes("Another user has already linked this")?S.detail="This account has already been linked to another user.":c.message==="Invalid code during oauth flow."?(S.retryable=!0,S.detail="Something went wrong. Try again."):c.message==="User denied confirmation during OAuth flow"&&(S.detail=`Retry and check ${Ml(p)} to finish connecting your account.`,S.retryable=!0),fr(),r(S)})},[d]),bn(()=>{if(!t)return;let c=setTimeout(a,ae);return()=>clearTimeout(c)},[t]);let w=t?`Successfully connected with ${E}`:o?o.message:`Verifying connection to ${E}`,m="";return t?m="You\u2019re good to go!":o?m=o.detail:m="Just a few moments more",Eo(Fl,{children:[Be(L,{}),Eo(Nl,{children:[Be(Ul,{children:Eo("div",{children:[Be(Qe,{success:t,fail:!!o}),Be(k,{style:{width:"38px",height:"38px"},logoFill:"primary"})]})}),Eo(Ol,{children:[Be("h3",{children:w}),Be("p",{children:m})]}),Be(Dl,{onClick:()=>{fr(),n(p),r(void 0)},visible:!t&&(o==null?void 0:o.retryable),disabled:!t&&!(o!=null&&o.retryable),children:"Retry"})]})]})},Nl=Lo.div`
1618
1618
  display: flex;
1619
1619
  flex-direction: column;
1620
1620
  align-items: center;
@@ -1701,7 +1701,7 @@ Resources:
1701
1701
  `,Jl=pt.div`
1702
1702
  display: flex;
1703
1703
  justify-content: center;
1704
- `;import{jsx as W,jsxs as Wn}from"react/jsx-runtime";var e1=()=>{let{ready:t}=D(),{isLinking:e}=_(),{ready:o,currentScreen:r,app:i}=C(),n=!!(i!=null&&i.walletAuth),s=!!((i==null?void 0:i.emailAuth)||(i==null?void 0:i.smsAuth)),a=n!==s,d;return["AWAITING_CONNECTION","AWAITING_OAUTH_SCREEN","ALLOWLIST_REJECTION_SCREEN","SETTING_ACTIVE_WALLET"].includes(r)||a&&r==="LANDING"?d="compact":"WALLET_EDUCATION"===r?d="full":e?d="medium":d="full",!t||!o?Wn(rt,{"data-height":d,children:[W(L,{}),W(r1,{children:W(At,{})}),W(oe,{})]}):Wn(rt,{"data-height":d,children:[r==="LANDING"&&W(Li,{}),r==="AWAITING_PASSWORDLESS_CODE"&&W(Ii,{}),r==="SETTING_ACTIVE_WALLET"&&W(sn,{}),r==="WALLET_EDUCATION"&&W(qi,{}),r==="AWAITING_CONNECTION"&&W(en,{}),r==="AWAITING_OAUTH_SCREEN"&&W(Ln,{}),r==="ALLOWLIST_REJECTION_SCREEN"&&W(Ui,{}),r==="INSTALL_METAMASK_SCREEN"&&W(on,{}),r==="INSTALL_COINBASE_WALLET_SCREEN"&&W(ln,{}),r==="LINK_EMAIL_SCREEN"&&W(An,{}),r==="LINK_PHONE_SCREEN"&&W(_n,{}),r==="LINK_WALLET_SCREEN"&&W(Sn,{}),r==="EMBEDDED_WALLET_SCREEN"&&W(vn,{}),r==="EMBEDDED_WALLET_CREATED_SCREEN"&&W(Tn,{}),r==="SIGN_REQUEST_SCREEN"&&W(pn,{})]})},In=()=>{let{app:t}=C();return Xl.createPortal(W(o1,{id:"privy-dialog",children:W(Cn,{accentColor:t==null?void 0:t.accentColor,children:W(e1,{})})}),document.body)},t1=({children:t,...e})=>(Ql(()=>{var r;(r=document==null?void 0:document.activeElement)==null||r.blur();let o=(document==null?void 0:document.getElementById("root"))||(document==null?void 0:document.getElementById("__next"));if(!!o)return o.setAttribute("inert","true"),()=>{let i=(document==null?void 0:document.getElementById("root"))||(document==null?void 0:document.getElementById("__next"));!i||i.removeAttribute("inert")}},[e.open,e.onClose]),W("dialog",{open:!0,role:"dialog",...e,children:t})),o1=gr(t1)`
1704
+ `;import{disableBodyScroll as t1,clearAllBodyScrollLocks as o1}from"body-scroll-lock";import{jsx as W,jsxs as Wn}from"react/jsx-runtime";var r1=()=>{let{ready:t}=D(),{isLinking:e}=_(),{ready:o,currentScreen:r,app:i}=C(),n=!!(i!=null&&i.walletAuth),s=!!((i==null?void 0:i.emailAuth)||(i==null?void 0:i.smsAuth)),a=n!==s,d;return["AWAITING_CONNECTION","AWAITING_OAUTH_SCREEN","ALLOWLIST_REJECTION_SCREEN","SETTING_ACTIVE_WALLET"].includes(r)||a&&r==="LANDING"?d="compact":"WALLET_EDUCATION"===r?d="full":e?d="medium":d="full",!t||!o?Wn(rt,{"data-height":d,children:[W(L,{}),W(s1,{children:W(At,{})}),W(oe,{})]}):Wn(rt,{"data-height":d,children:[r==="LANDING"&&W(Li,{}),r==="AWAITING_PASSWORDLESS_CODE"&&W(Ii,{}),r==="SETTING_ACTIVE_WALLET"&&W(sn,{}),r==="WALLET_EDUCATION"&&W(qi,{}),r==="AWAITING_CONNECTION"&&W(en,{}),r==="AWAITING_OAUTH_SCREEN"&&W(Ln,{}),r==="ALLOWLIST_REJECTION_SCREEN"&&W(Ui,{}),r==="INSTALL_METAMASK_SCREEN"&&W(on,{}),r==="INSTALL_COINBASE_WALLET_SCREEN"&&W(ln,{}),r==="LINK_EMAIL_SCREEN"&&W(An,{}),r==="LINK_PHONE_SCREEN"&&W(_n,{}),r==="LINK_WALLET_SCREEN"&&W(Sn,{}),r==="EMBEDDED_WALLET_SCREEN"&&W(vn,{}),r==="EMBEDDED_WALLET_CREATED_SCREEN"&&W(Tn,{}),r==="SIGN_REQUEST_SCREEN"&&W(pn,{})]})},In=()=>{let{app:t}=C();return Ql.createPortal(W(n1,{id:"privy-dialog",children:W(Cn,{accentColor:t==null?void 0:t.accentColor,children:W(r1,{})})}),document.body)},i1=({children:t,...e})=>{let o=Xl(null);return e1(()=>{var i;(i=document==null?void 0:document.activeElement)==null||i.blur();let r=(document==null?void 0:document.getElementById("root"))||(document==null?void 0:document.getElementById("__next"));if(!!r)return r.setAttribute("inert","true"),t1(o==null?void 0:o.current),()=>{let n=(document==null?void 0:document.getElementById("root"))||(document==null?void 0:document.getElementById("__next"));!n||(n.removeAttribute("inert"),o1())}},[e.open,e.onClose]),W("dialog",{open:!0,role:"dialog",...e,ref:o,children:t})},n1=gr(i1)`
1705
1705
  position: fixed;
1706
1706
  top: 0;
1707
1707
  left: 0;
@@ -1753,10 +1753,10 @@ Resources:
1753
1753
  min-height: 0;
1754
1754
  }
1755
1755
  }
1756
- `,r1=gr.div`
1756
+ `,s1=gr.div`
1757
1757
  display: flex;
1758
1758
  flex-direction: column;
1759
1759
  align-items: center;
1760
1760
  justify-content: center;
1761
1761
  height: 100%;
1762
- `;import{jsx as Ao,jsxs as Mn}from"react/jsx-runtime";function n1(t){return typeof t=="string"&&t.length===25}var Mt;function s1(){if(!Mt){let t=V.get($e);return Promise.resolve(t||null)}return Mt.getAccessToken()}var a1=t=>{if(!n1(t.appId))throw new g("Cannot initialize the Privy provider with an invalid Privy app ID");return Mt||(Mt=new yt({appId:t.appId,apiURL:_o})),Ao(c1,{...t,client:Mt})},l1=t=>{let e=!!(t!=null&&t.emailAuth),o=!!(t!=null&&t.smsAuth);return e&&o&&(console.warn("Enabling both email and SMS passwordless is not currently supported. Disabling SMS."),o=!1),{email:e,sms:o,wallet:!!(t!=null&&t.walletAuth),google:!!(t!=null&&t.googleOAuth),twitter:!!(t!=null&&t.twitterOAuth),discord:!!(t!=null&&t.discordOAuth),github:!!(t!=null&&t.githubOAuth)}},c1=t=>{let e=t.client,[o,r]=J(!1),[i,n]=J(!1),[s,a]=J(!1),[d,p]=J(null),[E,k]=J(!1),[w,m]=J(null),[f,c]=J(!1),[S,N]=J(null),[B,P]=J(null),[T,$]=J(null),[ne,Q]=J({accentColor:"#696ffd",theme:"System",showWalletLoginFirst:!0,allowlistConfig:{errorTitle:null,errorDetail:null,errorCtaText:null,errorCtaLink:null},walletAuth:!0,emailAuth:!0,smsAuth:!1,googleOAuth:!1,twitterOAuth:!1,discordOAuth:!1,githubOAuth:!1,termsAndConditionsUrl:null,privacyPolicyUrl:null}),[A,b]=J(!1),[z,Ve]=J({}),ut=l1(ne),se=l=>{l&&m(l),r(!0)};Rn(()=>{async function l(){let u=await e.getAppSettings();Q(u),e.connectors.initialize(),Nt();let I=await e.getAuthenticatedUser();a(!!I),p(I),n(!0)}l()},[e]);let Nt=()=>{let l=new URLSearchParams(window.location.search),u=l.get("privy_oauth_code"),I=l.get("privy_oauth_state"),xe=l.get("privy_oauth_provider");u&&I&&xe&&(e.startAuthFlow(new Ke(xe,u,I)),se("AWAITING_OAUTH_SCREEN"))};Rn(()=>{i&&s&&d===null&&e.getAuthenticatedUser().then(p)},[i,s,d,e]);let He=()=>{c(!0),se("LINK_WALLET_SCREEN")},Y={ready:i,authenticated:s,user:d,walletConnectors:e.connectors,linkWallet:He,linkEmail:()=>{c(!0),se("LINK_EMAIL_SCREEN")},linkPhone:()=>{c(!0),se("LINK_PHONE_SCREEN")},linkGoogle:async()=>{await ht.initLoginWithOAuth("google")},linkTwitter:async()=>{await ht.initLoginWithOAuth("twitter")},linkDiscord:async()=>{await ht.initLoginWithOAuth("discord")},linkGithub:async()=>{await ht.initLoginWithOAuth("github")},login:()=>{if(i&&s){console.warn("Attempted to log in, but user is already logged in. Use a `link` helper instead.");return}se()},logout:async()=>{await e.logout(),p(null),a(!1),m(null),c(!1),r(!1)},getAccessToken:()=>e.getAccessToken(),getEthereumProvider:()=>e.connectors.getEthereumProvider(),getEthersProvider:()=>new i1(new Re(e.connectors.getEthereumProvider())),getWeb3jsProvider:()=>new Gt(e.connectors.getEthereumProvider()),unlinkWallet:async l=>{let u=await e.unlinkWallet(l);return p(u),u},unlinkEmail:async l=>{let u=await e.unlinkEmail(l);return p(u),u},unlinkPhone:async l=>{let u=await e.unlinkPhone(l);return p(u),u},unlinkGoogle:async l=>{let u=await e.unlinkOAuth("google",l);return p(u),u},unlinkTwitter:async l=>{let u=await e.unlinkOAuth("twitter",l);return p(u),u},unlinkDiscord:async l=>{let u=await e.unlinkOAuth("discord",l);return p(u),u},unlinkGithub:async l=>{let u=await e.unlinkOAuth("github",l);return p(u),u},setActiveWallet:async l=>{if(!d)return;let u=e.connectors.getConnectorByAddress(l);if(!u){P(l),He();return}N({address:l,walletType:u.walletType,success:!1}),se("SETTING_ACTIVE_WALLET"),e.setActiveWallet(l,d).then(I=>{p(I),N({address:l,walletType:u.walletType,success:!0})}).catch(I=>{I instanceof g&&I.message==="Error setting the active wallet."&&(P(l),He()),N({address:l,walletType:u.walletType,success:!1,error:I.message})})},forkSession:()=>e.forkSession(),createWallet:()=>new Promise((l,u)=>{if(!s||!d){u(new Error("User must be authenticated before creating a Privy wallet"));return}if(fe(d)){u(new Error("Only one Privy wallet per user is currently allowed"));return}b(!0),Ve({createWallet:{onSuccess:l,onFailure:u}}),se("EMBEDDED_WALLET_SCREEN")}),signMessage:(l,u)=>new Promise((I,xe)=>{if(!s||!d){xe(new Error("User must be authenticated before signing with a Privy wallet"));return}if(!fe(d)){xe(new Error("Must have a Privy wallet before signing"));return}if(typeof l!="string"||l.length<1){xe(new Error("Message must be a non-empty string"));return}b(!0),Ve({signMessage:{message:l,onSuccess:I,onFailure:xe,uiOptions:u||{}}}),se("SIGN_REQUEST_SCREEN")})},ht=(()=>({isLinking:f,linkingHint:B,activeStatus:S,getAuthFlow:()=>e.authFlow,getAuthMeta:()=>{var l;return(l=e.authFlow)==null?void 0:l.meta},closePrivyModal:(l={shouldCallAuthOnSuccess:!0})=>{var I;let u=i&&s&&d;l.shouldCallAuthOnSuccess&&u&&((I=t.onSuccess)==null||I.call(t,d,E)),e.authFlow=void 0,P(null),m(null),c(!1),N(null),k(!1),r(!1)},initLoginWithWallet:l=>{if(!e.connectors)throw new g("Connector not initialized");l||(l="metamask"),e.startAuthFlow(new wt(e.connectors,l))},loginWithWallet:async()=>{if(!(e.authFlow instanceof wt))throw new g("Must initialize SIWE flow first.");let l,u;f?(l=await e.link(),l&&(l=gt(l))):{user:l,isNewUser:u}=await e.authenticate(),p(l||d||null),k(u||!1),a(!0)},initLoginWithOAuth:async l=>{e.startAuthFlow(new Ke(l));let u=await e.authFlow.getAuthorizationUrl();u&&u.url&&window.location.assign(u.url)},loginWithOAuth:async()=>{if(!(e.authFlow instanceof Ke))throw new g("Must initialize OAuth flow before calling loginWithOAuth");let l,u;i&&s?l=await e.link():{user:l,isNewUser:u}=await e.authenticate(),p(l),k(u||!1),a(!0)},initLoginWithEmail:async l=>{let u=new vt(l);e.startAuthFlow(u),await u.sendCodeEmail()},initLoginWithSms:async l=>{let u=new Ct(l);e.startAuthFlow(u),await u.sendSmsCode()},resendEmailCode:async()=>{var l;await((l=e.authFlow)==null?void 0:l.sendCodeEmail())},resendSmsCode:async()=>{var l;await((l=e.authFlow)==null?void 0:l.sendSmsCode())},loginWithCode:async l=>{if(e.authFlow instanceof vt)e.authFlow.meta.emailCode=l.trim();else if(e.authFlow instanceof Ct)e.authFlow.meta.smsCode=l.trim();else throw new g("Must initialize a passwordless code flow first");let u,I;f?u=await e.link():{user:u,isNewUser:I}=await e.authenticate(),p(u||d||null),k(I||!1),a(!0)},refreshUser:async()=>{let l=await e.getAuthenticatedUser();return p(l),l},walletProxy:T}))();return Mn(Do.Provider,{value:Y,children:[t.children,Mn(Go.Provider,{value:ht,children:[Ao(Qr,{appSettings:ne,options:ut,data:z,initialScreen:w,visible:o,authenticated:s,children:o&&Ao(In,{})}),A&&Ao(Kr,{appId:t.appId,origin:_o,onLoad:$,onLoadFailed:()=>{}})]})]})};export{Re as AsExternalProvider,ft as ConnectorManager,yt as PrivyClient,a1 as PrivyProvider,le as PrivyProxyProvider,ko as VERSION,me as WalletConnector,s1 as getAccessToken,D as usePrivy};
1762
+ `;import{jsx as Ao,jsxs as Mn}from"react/jsx-runtime";function l1(t){return typeof t=="string"&&t.length===25}var Mt;function c1(){if(!Mt){let t=V.get($e);return Promise.resolve(t||null)}return Mt.getAccessToken()}var d1=t=>{if(!l1(t.appId))throw new g("Cannot initialize the Privy provider with an invalid Privy app ID");return Mt||(Mt=new yt({appId:t.appId,apiURL:_o})),Ao(u1,{...t,client:Mt})},p1=t=>{let e=!!(t!=null&&t.emailAuth),o=!!(t!=null&&t.smsAuth);return e&&o&&(console.warn("Enabling both email and SMS passwordless is not currently supported. Disabling SMS."),o=!1),{email:e,sms:o,wallet:!!(t!=null&&t.walletAuth),google:!!(t!=null&&t.googleOAuth),twitter:!!(t!=null&&t.twitterOAuth),discord:!!(t!=null&&t.discordOAuth),github:!!(t!=null&&t.githubOAuth)}},u1=t=>{let e=t.client,[o,r]=J(!1),[i,n]=J(!1),[s,a]=J(!1),[d,p]=J(null),[E,k]=J(!1),[w,m]=J(null),[f,c]=J(!1),[S,N]=J(null),[B,P]=J(null),[T,$]=J(null),[ne,Q]=J({accentColor:"#696ffd",theme:"System",showWalletLoginFirst:!0,allowlistConfig:{errorTitle:null,errorDetail:null,errorCtaText:null,errorCtaLink:null},walletAuth:!0,emailAuth:!0,smsAuth:!1,googleOAuth:!1,twitterOAuth:!1,discordOAuth:!1,githubOAuth:!1,termsAndConditionsUrl:null,privacyPolicyUrl:null}),[A,b]=J(!1),[z,Ve]=J({}),ut=p1(ne),se=l=>{l&&m(l),r(!0)};Rn(()=>{async function l(){let u=await e.getAppSettings();Q(u),e.connectors.initialize(),Nt();let I=await e.getAuthenticatedUser();a(!!I),p(I),n(!0)}l()},[e]);let Nt=()=>{let l=new URLSearchParams(window.location.search),u=l.get("privy_oauth_code"),I=l.get("privy_oauth_state"),xe=l.get("privy_oauth_provider");u&&I&&xe&&(e.startAuthFlow(new Ke(xe,u,I)),se("AWAITING_OAUTH_SCREEN"))};Rn(()=>{i&&s&&d===null&&e.getAuthenticatedUser().then(p)},[i,s,d,e]);let He=()=>{c(!0),se("LINK_WALLET_SCREEN")},Y={ready:i,authenticated:s,user:d,walletConnectors:e.connectors,linkWallet:He,linkEmail:()=>{c(!0),se("LINK_EMAIL_SCREEN")},linkPhone:()=>{c(!0),se("LINK_PHONE_SCREEN")},linkGoogle:async()=>{await ht.initLoginWithOAuth("google")},linkTwitter:async()=>{await ht.initLoginWithOAuth("twitter")},linkDiscord:async()=>{await ht.initLoginWithOAuth("discord")},linkGithub:async()=>{await ht.initLoginWithOAuth("github")},login:()=>{if(i&&s){console.warn("Attempted to log in, but user is already logged in. Use a `link` helper instead.");return}se()},logout:async()=>{await e.logout(),p(null),a(!1),m(null),c(!1),r(!1)},getAccessToken:()=>e.getAccessToken(),getEthereumProvider:()=>e.connectors.getEthereumProvider(),getEthersProvider:()=>new a1(new Re(e.connectors.getEthereumProvider())),getWeb3jsProvider:()=>new Gt(e.connectors.getEthereumProvider()),unlinkWallet:async l=>{let u=await e.unlinkWallet(l);return p(u),u},unlinkEmail:async l=>{let u=await e.unlinkEmail(l);return p(u),u},unlinkPhone:async l=>{let u=await e.unlinkPhone(l);return p(u),u},unlinkGoogle:async l=>{let u=await e.unlinkOAuth("google",l);return p(u),u},unlinkTwitter:async l=>{let u=await e.unlinkOAuth("twitter",l);return p(u),u},unlinkDiscord:async l=>{let u=await e.unlinkOAuth("discord",l);return p(u),u},unlinkGithub:async l=>{let u=await e.unlinkOAuth("github",l);return p(u),u},setActiveWallet:async l=>{if(!d)return;let u=e.connectors.getConnectorByAddress(l);if(!u){P(l),He();return}N({address:l,walletType:u.walletType,success:!1}),se("SETTING_ACTIVE_WALLET"),e.setActiveWallet(l,d).then(I=>{p(I),N({address:l,walletType:u.walletType,success:!0})}).catch(I=>{I instanceof g&&I.message==="Error setting the active wallet."&&(P(l),He()),N({address:l,walletType:u.walletType,success:!1,error:I.message})})},forkSession:()=>e.forkSession(),createWallet:()=>new Promise((l,u)=>{if(!s||!d){u(new Error("User must be authenticated before creating a Privy wallet"));return}if(fe(d)){u(new Error("Only one Privy wallet per user is currently allowed"));return}b(!0),Ve({createWallet:{onSuccess:l,onFailure:u}}),se("EMBEDDED_WALLET_SCREEN")}),signMessage:(l,u)=>new Promise((I,xe)=>{if(!s||!d){xe(new Error("User must be authenticated before signing with a Privy wallet"));return}if(!fe(d)){xe(new Error("Must have a Privy wallet before signing"));return}if(typeof l!="string"||l.length<1){xe(new Error("Message must be a non-empty string"));return}b(!0),Ve({signMessage:{message:l,onSuccess:I,onFailure:xe,uiOptions:u||{}}}),se("SIGN_REQUEST_SCREEN")})},ht=(()=>({isLinking:f,linkingHint:B,activeStatus:S,getAuthFlow:()=>e.authFlow,getAuthMeta:()=>{var l;return(l=e.authFlow)==null?void 0:l.meta},closePrivyModal:(l={shouldCallAuthOnSuccess:!0})=>{var I;let u=i&&s&&d;l.shouldCallAuthOnSuccess&&u&&((I=t.onSuccess)==null||I.call(t,d,E)),e.authFlow=void 0,P(null),m(null),c(!1),N(null),k(!1),r(!1)},initLoginWithWallet:l=>{if(!e.connectors)throw new g("Connector not initialized");l||(l="metamask"),e.startAuthFlow(new wt(e.connectors,l))},loginWithWallet:async()=>{if(!(e.authFlow instanceof wt))throw new g("Must initialize SIWE flow first.");let l,u;f?(l=await e.link(),l&&(l=gt(l))):{user:l,isNewUser:u}=await e.authenticate(),p(l||d||null),k(u||!1),a(!0)},initLoginWithOAuth:async l=>{e.startAuthFlow(new Ke(l));let u=await e.authFlow.getAuthorizationUrl();u&&u.url&&window.location.assign(u.url)},loginWithOAuth:async()=>{if(!(e.authFlow instanceof Ke))throw new g("Must initialize OAuth flow before calling loginWithOAuth");let l,u;i&&s?l=await e.link():{user:l,isNewUser:u}=await e.authenticate(),p(l),k(u||!1),a(!0)},initLoginWithEmail:async l=>{let u=new vt(l);e.startAuthFlow(u),await u.sendCodeEmail()},initLoginWithSms:async l=>{let u=new Ct(l);e.startAuthFlow(u),await u.sendSmsCode()},resendEmailCode:async()=>{var l;await((l=e.authFlow)==null?void 0:l.sendCodeEmail())},resendSmsCode:async()=>{var l;await((l=e.authFlow)==null?void 0:l.sendSmsCode())},loginWithCode:async l=>{if(e.authFlow instanceof vt)e.authFlow.meta.emailCode=l.trim();else if(e.authFlow instanceof Ct)e.authFlow.meta.smsCode=l.trim();else throw new g("Must initialize a passwordless code flow first");let u,I;f?u=await e.link():{user:u,isNewUser:I}=await e.authenticate(),p(u||d||null),k(I||!1),a(!0)},refreshUser:async()=>{let l=await e.getAuthenticatedUser();return p(l),l},walletProxy:T}))();return Mn(Do.Provider,{value:Y,children:[t.children,Mn(Go.Provider,{value:ht,children:[Ao(Qr,{appSettings:ne,options:ut,data:z,initialScreen:w,visible:o,authenticated:s,children:o&&Ao(In,{})}),A&&Ao(Kr,{appId:t.appId,origin:_o,onLoad:$,onLoadFailed:()=>{}})]})]})};export{Re as AsExternalProvider,ft as ConnectorManager,yt as PrivyClient,d1 as PrivyProvider,le as PrivyProxyProvider,ko as VERSION,me as WalletConnector,c1 as getAccessToken,D as usePrivy};