@privy-io/react-auth 1.16.1-beta.3 → 1.16.1-beta.4
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 +3 -3
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{useEffect as Ri,useState as Y}from"react";import So from"axios";import Ni 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,n,i){super(n,i);this.type=o;this.status=r}},g=class extends ee{constructor(o,r){super(o,r);this.type="client_error"}};var U=class extends ee{constructor(o,r){super(o,r);this.type="connector_error"}},M=t=>{if(t instanceof ee)return t;if(!Ni.isAxiosError(t))return Q(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)},Q=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
|
+
import{useEffect as Ri,useState as Y}from"react";import So from"axios";import Ni 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,n,i){super(n,i);this.type=o;this.status=r}},g=class extends ee{constructor(o,r){super(o,r);this.type="client_error"}};var U=class extends ee{constructor(o,r){super(o,r);this.type="connector_error"}},M=t=>{if(t instanceof ee)return t;if(!Ni.isAxiosError(t))return Q(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)},Q=t=>t instanceof ee?t:t instanceof Error?new g(t.message,t):new g(`Internal error: ${t}`);var yr="1.16.1-beta.4";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(n){throw M(n)}}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 Ui(){return typeof window<"u"&&window.localStorage?new To:new Po}var H=Ui();import{ErrorCode as Di}from"@ethersproject/logger";var je=class extends U{constructor(){super("Wallet timeout");this.type="wallet_error"}},Le=t=>{if(t instanceof U)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new Ze(t);return t.code===Di.ACTION_REJECTED&&(e.details=Ie.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new Ze(t):new U("Unknown connector error",t)},Wo=class extends ee{constructor(o,r,n){super(o);this.type="provider_error";this.code=r,this.data=n}},Ze=class extends Wo{constructor(o){var i,s,a;let r=o;super(r.message,r.code,r.data);let n=Object.values(Ie).find(d=>d.eipCode===r.code);this.details=n||Ie.UNKNOWN_ERROR,r.code===-32002&&((i=r.message)!=null&&i.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))}},Fi={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}},Gi={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}},Bi={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},...Bi,...Gi},qe={...Fi,...Ie};var Vi=12e4,Io=(t=new je,e=Vi)=>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 U(`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 ji}from"@ethersproject/providers";import{getAddress as Hi}from"@ethersproject/address";import{Web3Provider as zi}from"@ethersproject/providers";var me=class{constructor(e,o,r){this.createSiweMessage=(e,o,r,n,i,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: ${i}
|
|
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=Hi(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 zi(new Re(this.provider)).getSigner().signMessage(e)}prepareMessage(e,o,r){let n=window.location.host,i=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,n,i,a,r,s)}};import{isPossiblePhoneNumber as $i}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=>$i(String(t),"US"),Bt=t=>{var e=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(e,function(r,n,i,s){return n+n+i+i+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,n=3;if(e+o+r+n>=t.length)return t;let i=t.slice(0,r+e),s=t.slice(t.length-o,t.length);return`${i}...${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(n,i)=>{let s=!1,a=0;for(;!s&&a<r;)t().then(()=>{s=!0,n()},(...d)=>{s=!0,i(...d)}),a+=1,await Ro(o);s||i(new Error("Exceeded max attempts before resolving function"))})},_r=(...t)=>{let o=t.length-1;return t.map((n,i)=>(i===0&&(n.startsWith("//")||n.endsWith("://"))?n=n.replace(new RegExp("/$"),""):i!==o&&(n=n.replace(new RegExp("/+$"),"")),i!==0&&(n=n.replace(new RegExp("^/+"),"")),n)).join("/")};import{isMobile as Zi}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 n=>{n.isMetaMask&&this.provider.setProvider(n)}),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 ji(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(!Zi&&(await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.address&&await this.isConnected()))throw new U("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 U("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 qi}from"@ethersproject/address";import Ki from"@coinbase/wallet-sdk";var Ji=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 Ki({appName:"Privy",darkMode:!1,headlessMode:!1}))}async connect(e){return this.provider.setProvider(Ji(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=qi(o[0])),!e||e==="")throw new U("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,n){super("wallet_connect",r,n);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(n)}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 U("Unable to retrieve address");this.connected=!0}catch(o){throw Le(o)}}disconnect(){}},$t=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},H.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 n=new Sr({infuraId:mt,storageId:o});return this._storageIdToProvider[o]=n,n}indexProvider(e){this._storageIdToProvider[e.storageId]=e;for(let o of e.accounts)this._addressToStorageId[o]=e.storageId}};import{getAddress as Yi}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===Yi(e)).length):!1},Pr=()=>{var e;let t=H.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(){(H.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)}});H.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(n=>n.address!==e),e===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let n=this.walletConnectors[this.walletConnectors.length-1];await this.setActiveWallet(n.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){if(!this.activeWalletConnector)throw new U("Cannot sign, no wallet is active. Is a wallet connected?");if(!await this.activeWalletConnector.connect({showPrompt:!1}))throw new U("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 Xi(t){let e=[];for(let o of t){let r=o.type;switch(o.type){case"wallet":let n={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at),chainType:o.chain_type,walletClient:o.wallet_client};e.push(n);break;case"email":let i={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(i);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(n=>n.type==="wallet"&&n.address===e);if(!o)return t;let 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=Xi(t.linked_accounts),o=Ne(e,"wallet"),r=Ne(e,"email"),n=Ne(e,"phone"),i=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:n&&{number:n==null?void 0:n.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletClient:o.walletClient},google:i&&{subject:i.subject,email:i.email,name:i.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 Qi=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=H.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=H.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(Qi)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:n,is_new_user:i}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:ge(n),isNewUser:i}}catch(o){throw console.warn("Error authenticating session"),Q(o)}}async _link(e){try{let o=await e.link();return ge(o)}catch(o){throw console.warn("Error linking account"),Q(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 Q(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 Q(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?H.put($e,e):H.del($e)}storeRefreshToken(e){typeof e=="string"?H.put(Ut,e):H.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 Q(o)}}async unlinkPhone(e){try{let o=await this.api.post(Zr(),{phoneNumber:e});return ge(o.data)}catch(o){throw Q(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 Q(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(qr(),{provider:e,subject:o});return ge(r.data)}catch(r){throw Q(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 Q(e)}}async setActiveWallet(e,o){if(!o.linkedAccounts.map(i=>i.type==="wallet"?i.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 c1}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}),F=()=>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,n=o.chainId,i=await e.post(Rr(),{address:r}),s=this.walletConnector.prepareMessage(n,r,i.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 ns=function(t){return()=>`id-${t++}`}(0);function is(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((n,i)=>{let s=ns();bt.enqueue(s,{resolve:n,reject:i}),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 n=bt.dequeue(t.event,t.id);return Kt(t)?n.reject(new Error(t.error.message)):n.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&&is(a.data)&&ss(a.data)}let n={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 i=()=>t.onLoad(n),s=(...a)=>{console.error("privy iframe failed to load: ",...a),t.onLoadFailed()};return Ar(()=>Jt("privy:iframe:ready",{},o)).then(i,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 e1}from"react";import t1 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,[n,i]=Yr(t.initialScreen||ye),[s,a]=Yr(t.initialScreen||ye);Fo(()=>{o||i(ye)},[o]),Fo(()=>{r||(a(ye),i(ye))},[r]),Fo(()=>{t.initialScreen&&n===ye&&(i(t.initialScreen),a(t.initialScreen))},[t.initialScreen]);let d=t.initialScreen&&n===ye?t.initialScreen:n,p={ready:!!(e!=null&&e.id),app:e,options:t.options,data:t.data,currentScreen:d,lastScreen:s,navigate:E=>{a(n),i(E)},navigateBack:()=>{i(s)}};return us(Xr.Provider,{value:p,children:[e&&e.logoUrl&&ps(Jr,{src:e.logoUrl}),t.children]})},C=()=>ds(Xr);import{useState as ia}from"react";import et from"styled-components";import fs from"styled-components";import{jsx as en}from"react/jsx-runtime";var tn=({style:t,...e})=>en("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:en("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});import{jsx as on}from"react/jsx-runtime";var rn=({style:t,...e})=>on("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:on("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(rn,{onClick:t})}),ws=t=>we("div",{children:we("div",{children:we(tn,{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=Hi(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 zi(new Re(this.provider)).getSigner().signMessage(e)}prepareMessage(e,o,r){let n=window.location.host,i=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,n,i,a,r,s)}};import{isPossiblePhoneNumber as $i}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=>$i(String(t),"US"),Bt=t=>{var e=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(e,function(r,n,i,s){return n+n+i+i+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,n=3;if(e+o+r+n>=t.length)return t;let i=t.slice(0,r+e),s=t.slice(t.length-o,t.length);return`${i}...${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(n,i)=>{let s=!1,a=0;for(;!s&&a<r;)t().then(()=>{s=!0,n()},(...d)=>{s=!0,i(...d)}),a+=1,await Ro(o);s||i(new Error("Exceeded max attempts before resolving function"))})},_r=(...t)=>{let o=t.length-1;return t.map((n,i)=>(i===0&&(n.startsWith("//")||n.endsWith("://"))?n=n.replace(new RegExp("/$"),""):i!==o&&(n=n.replace(new RegExp("/+$"),"")),i!==0&&(n=n.replace(new RegExp("^/+"),"")),n)).join("/")};import{isMobile as Zi}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 n=>{n.isMetaMask&&this.provider.setProvider(n)}),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 ji(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(!Zi&&(await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.address&&await this.isConnected()))throw new U("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 U("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 qi}from"@ethersproject/address";import Ki from"@coinbase/wallet-sdk";var Ji=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 Ki({appName:"Privy",darkMode:!1,headlessMode:!1}))}async connect(e){return this.provider.setProvider(Ji(Ht)),e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}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=qi(o[0])),!e||e==="")throw new U("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,n){super("wallet_connect",r,n);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(n)}async connect(o){return this.provider.setProvider(this._provider),o.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}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 U("Unable to retrieve address");this.connected=!0}catch(o){throw Le(o)}}disconnect(){}},$t=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},H.getKeys().forEach(e=>{if(e.startsWith("walletconnect")){let o=new Sr({infuraId:mt,storageId:e});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 n=new Sr({infuraId:mt,storageId:o});return this._storageIdToProvider[o]=n,n}indexProvider(e){this._storageIdToProvider[e.storageId]=e;for(let o of e.accounts)this._addressToStorageId[o]=e.storageId}};import{getAddress as Yi}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===Yi(e)).length):!1},Pr=()=>{var e;let t=H.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(){(H.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)}});H.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(n=>n.address!==e),e===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let n=this.walletConnectors[this.walletConnectors.length-1];await this.setActiveWallet(n.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(e){if(!this.activeWalletConnector)throw new U("Cannot sign, no wallet is active. Is a wallet connected?");if(!await this.activeWalletConnector.connect({showPrompt:!1}))throw new U("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 Xi(t){let e=[];for(let o of t){let r=o.type;switch(o.type){case"wallet":let n={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at),chainType:o.chain_type,walletClient:o.wallet_client};e.push(n);break;case"email":let i={address:o.address,type:o.type,verifiedAt:Ae(o.verified_at)};e.push(i);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(n=>n.type==="wallet"&&n.address===e);if(!o)return t;let 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=Xi(t.linked_accounts),o=Ne(e,"wallet"),r=Ne(e,"email"),n=Ne(e,"phone"),i=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:n&&{number:n==null?void 0:n.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletClient:o.walletClient},google:i&&{subject:i.subject,email:i.email,name:i.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 Qi=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=H.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=H.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(Qi)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:n,is_new_user:i}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:ge(n),isNewUser:i}}catch(o){throw console.warn("Error authenticating session"),Q(o)}}async _link(e){try{let o=await e.link();return ge(o)}catch(o){throw console.warn("Error linking account"),Q(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 Q(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 Q(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(e){typeof e=="string"?H.put($e,e):H.del($e)}storeRefreshToken(e){typeof e=="string"?H.put(Ut,e):H.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 Q(o)}}async unlinkPhone(e){try{let o=await this.api.post(Zr(),{phoneNumber:e});return ge(o.data)}catch(o){throw Q(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 Q(o)}}async unlinkOAuth(e,o){try{let r=await this.api.post(qr(),{provider:e,subject:o});return ge(r.data)}catch(r){throw Q(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 Q(e)}}async setActiveWallet(e,o){if(!o.linkedAccounts.map(i=>i.type==="wallet"?i.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 c1}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}),F=()=>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,n=o.chainId,i=await e.post(Rr(),{address:r}),s=this.walletConnector.prepareMessage(n,r,i.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 ns=function(t){return()=>`id-${t++}`}(0);function is(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((n,i)=>{let s=ns();bt.enqueue(s,{resolve:n,reject:i}),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 n=bt.dequeue(t.event,t.id);return Kt(t)?n.reject(new Error(t.error.message)):n.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&&is(a.data)&&ss(a.data)}let n={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 i=()=>t.onLoad(n),s=(...a)=>{console.error("privy iframe failed to load: ",...a),t.onLoadFailed()};return Ar(()=>Jt("privy:iframe:ready",{},o)).then(i,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 e1}from"react";import t1 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,[n,i]=Yr(t.initialScreen||ye),[s,a]=Yr(t.initialScreen||ye);Fo(()=>{o||i(ye)},[o]),Fo(()=>{r||(a(ye),i(ye))},[r]),Fo(()=>{t.initialScreen&&n===ye&&(i(t.initialScreen),a(t.initialScreen))},[t.initialScreen]);let d=t.initialScreen&&n===ye?t.initialScreen:n,p={ready:!!(e!=null&&e.id),app:e,options:t.options,data:t.data,currentScreen:d,lastScreen:s,navigate:E=>{a(n),i(E)},navigateBack:()=>{i(s)}};return us(Xr.Provider,{value:p,children:[e&&e.logoUrl&&ps(Jr,{src:e.logoUrl}),t.children]})},C=()=>ds(Xr);import{useState as ia}from"react";import et from"styled-components";import fs from"styled-components";import{jsx as en}from"react/jsx-runtime";var tn=({style:t,...e})=>en("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:en("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});import{jsx as on}from"react/jsx-runtime";var rn=({style:t,...e})=>on("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:on("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(rn,{onClick:t})}),ws=t=>we("div",{children:we("div",{children:we(tn,{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;
|
|
@@ -745,7 +745,7 @@ Resources:
|
|
|
745
745
|
border-color: var(--primary-color);
|
|
746
746
|
border-bottom-color: var(--primary-color);
|
|
747
747
|
}
|
|
748
|
-
`;import{jsx as Nn}from"react/jsx-runtime";var On=({style:t,...e})=>Nn("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:Nn("path",{
|
|
748
|
+
`;import{jsx as Nn}from"react/jsx-runtime";var On=({style:t,...e})=>Nn("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:Nn("path",{fillRule:"evenodd",d:"M12 1.5a5.25 5.25 0 00-5.25 5.25v3a3 3 0 00-3 3v6.75a3 3 0 003 3h10.5a3 3 0 003-3v-6.75a3 3 0 00-3-3v-3c0-2.9-2.35-5.25-5.25-5.25zm3.75 8.25v-3a3.75 3.75 0 10-7.5 0v3h7.5z",clipRule:"evenodd"})});import{Fragment as Xo,jsx as pe,jsxs as uo}from"react/jsx-runtime";var Dn=()=>{let{navigate:t,app:e}=C(),o=(e==null?void 0:e.allowlistConfig.errorTitle)||"You don't have access to this app",r=(e==null?void 0:e.allowlistConfig.errorDetail)||"Have you been invited?",n=(e==null?void 0:e.allowlistConfig.errorCtaText)||"Try another account";return uo(Xo,{children:[pe(L,{}),uo(Ea,{children:[pe(Aa,{children:uo("div",{children:[pe(Mn,{}),pe(On,{style:{width:"38px",height:"38px",strokeWidth:"1",stroke:"var(--primary-color)",fill:"var(--primary-color)"}})]})}),uo(La,{children:[typeof o=="string"?pe("h3",{children:o}):pe(Xo,{children:o}),typeof r=="string"?pe("p",{children:r}):pe(Xo,{children:r})]}),e!=null&&e.allowlistConfig.errorCtaLink?pe(Un,{as:"a",href:e.allowlistConfig.errorCtaLink,visible:!0,children:n}):pe(Un,{onClick:()=>{t("LANDING")},visible:!0,children:n})]})]})},Ea=ho.div`
|
|
749
749
|
display: flex;
|
|
750
750
|
flex-direction: column;
|
|
751
751
|
align-items: center;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Vi=Object.create;var Xt=Object.defineProperty;var Hi=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var $i=Object.getPrototypeOf,ji=Object.prototype.hasOwnProperty;var Zi=(e,t)=>{for(var o in t)Xt(e,o,{get:t[o],enumerable:!0})},Wr=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of zi(t))!ji.call(e,n)&&n!==o&&Xt(e,n,{get:()=>t[n],enumerable:!(r=Hi(t,n))||r.enumerable});return e};var E=(e,t,o)=>(o=e!=null?Vi($i(e)):{},Wr(t||!e||!e.__esModule?Xt(o,"default",{value:e,enumerable:!0}):o,e)),qi=e=>Wr(Xt({},"__esModule",{value:!0}),e);var Qa={};Zi(Qa,{AsExternalProvider:()=>Ge,ConnectorManager:()=>ut,PrivyClient:()=>ht,PrivyProvider:()=>Bi,PrivyProxyProvider:()=>fe,VERSION:()=>Qt,WalletConnector:()=>_e,getAccessToken:()=>Gi,usePrivy:()=>z});module.exports=qi(Qa);var Z=require("react");var oo=E(require("axios"));var Ir=E(require("axios")),me=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}]`:""}`}},at=class extends me{constructor(o,r,n,i){super(n,i);this.type=o;this.status=r}},y=class extends me{constructor(o,r){super(o,r);this.type="client_error"}};var H=class extends me{constructor(o,r){super(o,r);this.type="connector_error"}},F=e=>{if(e instanceof me)return e;if(!Ir.default.isAxiosError(e))return ce(e);if(!e.response)return new at("api_error",null,e.message,e);let{type:t,message:o,error:r}=e.response.data;return new at(t||"ApiError",e.response.status,o||r,e)},ce=e=>e instanceof me?e:e instanceof Error?new y(e.message,e):new y(`Internal error: ${e}`);var Rr="1.16.1-beta.
|
|
1
|
+
"use strict";var Vi=Object.create;var Xt=Object.defineProperty;var Hi=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var $i=Object.getPrototypeOf,ji=Object.prototype.hasOwnProperty;var Zi=(e,t)=>{for(var o in t)Xt(e,o,{get:t[o],enumerable:!0})},Wr=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of zi(t))!ji.call(e,n)&&n!==o&&Xt(e,n,{get:()=>t[n],enumerable:!(r=Hi(t,n))||r.enumerable});return e};var E=(e,t,o)=>(o=e!=null?Vi($i(e)):{},Wr(t||!e||!e.__esModule?Xt(o,"default",{value:e,enumerable:!0}):o,e)),qi=e=>Wr(Xt({},"__esModule",{value:!0}),e);var Qa={};Zi(Qa,{AsExternalProvider:()=>Ge,ConnectorManager:()=>ut,PrivyClient:()=>ht,PrivyProvider:()=>Bi,PrivyProxyProvider:()=>fe,VERSION:()=>Qt,WalletConnector:()=>_e,getAccessToken:()=>Gi,usePrivy:()=>z});module.exports=qi(Qa);var Z=require("react");var oo=E(require("axios"));var Ir=E(require("axios")),me=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}]`:""}`}},at=class extends me{constructor(o,r,n,i){super(n,i);this.type=o;this.status=r}},y=class extends me{constructor(o,r){super(o,r);this.type="client_error"}};var H=class extends me{constructor(o,r){super(o,r);this.type="connector_error"}},F=e=>{if(e instanceof me)return e;if(!Ir.default.isAxiosError(e))return ce(e);if(!e.response)return new at("api_error",null,e.message,e);let{type:t,message:o,error:r}=e.response.data;return new at(t||"ApiError",e.response.status,o||r,e)},ce=e=>e instanceof me?e:e instanceof Error?new y(e.message,e):new y(`Internal error: ${e}`);var Rr="1.16.1-beta.4";var Mr="https://api.privy.io/v0",Vo=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",Rt="4df5e2316331463a9130964bd6078dfa",Nr=1e4,Ae=1400,Qt=Rr;var lt="privy:token",eo="privy:refresh_token",to="privy:connectors",Or="walletconnect";var ro=class{constructor(t,o,r){this.appId=t,this.sdkVersion=Qt,this.client=o,this.defaults=r}async get(t,o){try{return await oo.default.get(t,await this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw F(r)}}async post(t,o,r){try{return await oo.default.post(t,o,await this.buildConfig(r))}catch(n){throw F(n)}}async delete(t,o){try{return await oo.default.delete(t,await this.buildConfig(o))}catch(r){throw F(r)}}async buildConfig(t){if(t=t||{},t.headers=t.headers||{},t.headers["privy-app-id"]=this.appId,t.headers["privy-client"]=`react-auth:${this.sdkVersion}`,!t.headers.authorization){let o=await this.client.getAccessToken();o!==null&&(t.headers.authorization=`Bearer ${o}`)}return{...this.defaults,...t}}};var Ur=E(require("jose")),We=class{static parse(t){try{return new We(t)}catch{return null}}constructor(t){this.value=t,this._decoded=Ur.decodeJwt(t)}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(t=0){let o=Date.now(),r=(this.expiration-t)*1e3;return o>=r}};var De=class{constructor(t){this.promise=null;this.fn=t}execute(t){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(t)}finally{this.promise=null}})()),this.promise}};var Ho=class{constructor(){this._cache={}}get(t){return this._cache[t]}put(t,o){o!==void 0?this._cache[t]=o:this.del(t)}del(t){delete this._cache[t]}getKeys(){return Object.keys(this._cache)}},zo=class{get(t){let o=localStorage.getItem(t);return o===null?void 0:JSON.parse(o)}put(t,o){o!==void 0?localStorage.setItem(t,JSON.stringify(o)):this.del(t)}del(t){localStorage.removeItem(t)}getKeys(){return Object.entries(localStorage).map(([t])=>t)}};function Ji(){return typeof window<"u"&&window.localStorage?new zo:new Ho}var Q=Ji();var Dr=require("@ethersproject/logger");var ct=class extends H{constructor(){super("Wallet timeout");this.type="wallet_error"}},Fe=e=>{if(e instanceof H)return e;if((e==null?void 0:e.code)&&(e==null?void 0:e.reason)){let t=new dt(e);return e.code===Dr.ErrorCode.ACTION_REJECTED&&(t.details=Xe.E4001_USER_REJECTED_REQUEST),t}return e!=null&&e.code?new dt(e):new H("Unknown connector error",e)},$o=class extends me{constructor(o,r,n){super(o);this.type="provider_error";this.code=r,this.data=n}},dt=class extends $o{constructor(o){var i,s,a;let r=o;super(r.message,r.code,r.data);let n=Object.values(Xe).find(p=>p.eipCode===r.code);this.details=n||Xe.UNKNOWN_ERROR,r.code===-32002&&((i=r.message)!=null&&i.includes("already pending for origin")?(s=r.message)!=null&&s.includes("wallet_requestPermissions")?this.details=Xe.E32002_CONNECTION_ALREADY_PENDING:this.details=Xe.E32002_REQUEST_ALREADY_PENDING:(a=r.message)!=null&&a.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=Xe.E32002_WALLET_LOCKED))}},Yi={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}},Xi={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}},Qi={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}},Xe={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...Qi,...Xi},pt={...Yi,...Xe};var es=12e4,jo=(e=new ct,t=es)=>new Promise((o,r)=>setTimeout(()=>{r(e)},t)),fe=class{constructor(t){this.removeListener=(t,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(t,o)};this.setProvider=t=>{this.walletProvider=t,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=t,this._subscriptions=[]}on(t,o){if(this.walletProvider)return this.walletProvider.on(t,o);this._subscriptions.push({eventName:t,listener:o})}async request(t){if(!this.walletProvider)throw new H(`A wallet request of type ${t.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(t),jo()]).catch(o=>{throw Fe(o)})}},Ge=class extends fe{constructor(o){super(o)}},no=class extends fe{constructor(t){super(t)}sendAsync(t,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};var qo=require("@ethersproject/address"),Zr=require("@ethersproject/providers");var Fr=require("@ethersproject/address");var Gr=require("@ethersproject/providers"),_e=class{constructor(t,o,r){this.createSiweMessage=(t,o,r,n,i,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: ${t}
|
|
|
9
9
|
Nonce: ${s}
|
|
10
10
|
Issued At: ${i}
|
|
11
11
|
Resources:
|
|
12
|
-
- https://privy.io`;this.provider=o,this.walletType=t,this.address=r,this.chain=null,this.connected=!1}async fetchAddress(){if(!this.address){let t=await this.provider.request({method:"eth_accounts"});Array.isArray(t)&&t.length>0&&(this.address=(0,Fr.getAddress)(t[0]))}return this.address}async fetchChainId(){if(!this.chain){let t=await this.provider.request({method:"eth_chainId"}),o=Number(t);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(t){return new Gr.Web3Provider(new Ge(this.provider)).getSigner().signMessage(t)}prepareMessage(t,o,r){let n=window.location.host,i=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(t,o,n,i,a,r,s)}};var Br=require("libphonenumber-js/min");var Vr=e=>!!String(e).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,}))$/),Hr=e=>(0,Br.isPossiblePhoneNumber)(String(e),"US"),io=e=>{var t=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;e=e.replace(t,function(r,n,i,s){return n+n+i+i+s+s});var o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);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)}},zr=(e,t)=>{var o=e.slice(0);let r=[];for(;o.length;)r.push(o.splice(0,t));return r},Qe=(e,t=3,o=4)=>{if(!e)return"";let r=2,n=3;if(t+o+r+n>=e.length)return e;let i=e.slice(0,r+t),s=e.slice(e.length-o,e.length);return`${i}...${s}`},Zo=e=>new Promise(t=>setTimeout(t,e)),$r=(e,t={})=>{let o=t.delayMs||40,r=t.maxAttempts||1e3;return new Promise(async(n,i)=>{let s=!1,a=0;for(;!s&&a<r;)e().then(()=>{s=!0,n()},(...p)=>{s=!0,i(...p)}),a+=1,await Zo(o);s||i(new Error("Exceeded max attempts before resolving function"))})},jr=(...e)=>{let o=e.length-1;return e.map((n,i)=>(i===0&&(n.startsWith("//")||n.endsWith("://"))?n=n.replace(new RegExp("/$"),""):i!==o&&(n=n.replace(new RegExp("/+$"),"")),i!==0&&(n=n.replace(new RegExp("^/+"),"")),n)).join("/")};var qr=require("react-device-detect"),so=class extends _e{constructor(t,o){var r;super("metamask",t,o),this.provider.setProvider(window.ethereum),(r=window.ethereum.providers)==null||r.forEach(async n=>{n.isMetaMask&&this.provider.setProvider(n)}),this.subscribeListeners()}async connect(t){return t.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}async isConnected(){let t=await this.connectedMetamaskAddress();return this.address===t}async connectedMetamaskAddress(){let o=await new Zr.Web3Provider(this.provider).listAccounts();return o.length===0?null:(0,qo.getAddress)(o[0])}disconnect(){console.warn("Metamask does not support programmetic disconnect.")}async promptConnection(){try{let t="";if(!qr.isMobile&&(await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.address&&await this.isConnected()))throw new H("Selected the wrong wallet in MetaMask");let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(t=(0,qo.getAddress)(o[0])),!t||t==="")throw new H("Unable to retrieve address");this.connected=!0,this.address=t}catch(t){throw Fe(t)}}async setActive(){if(await this.connectedMetamaskAddress()===this.address)return this.connected=!0,!0;for(;!this.connected;)await Zo(200);return!0}subscribeListeners(){this.provider.on("accountsChanged",t=>{var o;if(t.length>0){let r=t[0];this.connected=((o=this.address)==null?void 0:o.toLowerCase())===(r==null?void 0:r.toLowerCase())}}),this.provider.on("disconnect",()=>{this.connected=!1})}};var Kr=require("@ethersproject/address");var Jr=E(require("@coinbase/wallet-sdk"));var ts=e=>{let t=`https://mainnet.infura.io/v3/${Rt}`,o=1;return e.makeWeb3Provider(t,o)},ao,lo=class extends _e{constructor(t,o){super("coinbase_wallet",t,o),ao||(ao=new Jr.default({appName:"Privy",darkMode:!1,headlessMode:!1}))}async connect(t){return this.provider.setProvider(ts(ao)),(!await this.isConnected()||t.showPrompt)&&await this.promptConnection(),this.getConnectedWallet()}disconnect(){ao.disconnect()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let t="",o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(t=(0,Kr.getAddress)(o[0])),!t||t==="")throw new H("Unable to retrieve address");this.connected=!0}catch(t){throw Fe(t)}}};var Ko=E(require("@walletconnect/web3-provider"));var Jo=class extends _e{constructor(o,r,n){super("wallet_connect",r,n);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(n)}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(),jo()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new H("Unable to retrieve address");this.connected=!0}catch(o){throw Fe(o)}}disconnect(){}},co=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},Q.getKeys().forEach(t=>{if(t.startsWith("walletconnect")){let o=new Ko.default({infuraId:Rt,storageId:t});o.enable(),this._storageIdToProvider[t]=o;for(let r of o.accounts)this._addressToStorageId[r]=t}})}build(t,o){return new Jo(this,t,o)}async disconnect(){Object.values(this._storageIdToProvider).forEach(async t=>{await t.disconnect()})}getProviderForAddress(t){let o=Or,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;t===null?o=r():o=this._addressToStorageId[t]||r();let n=new Ko.default({infuraId:Rt,storageId:o});return this._storageIdToProvider[o]=n,n}indexProvider(t){this._storageIdToProvider[t.storageId]=t;for(let o of t.accounts)this._addressToStorageId[o]=t.storageId}};var Yr=require("@ethersproject/address"),Yo=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let e of window.ethereum.providers)if(e.isMetaMask)return!0}return!1},po=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let e of window.ethereum.providers)if(e.isCoinbaseWallet)return!0}return!1},Xo=e=>{let t=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses");return t?!!(e==null?void 0:e.linkedAccounts.filter(r=>r.type=="wallet"&&r.address===(0,Yr.getAddress)(t)).length):!1},Xr=()=>{var t;let e=Q.get(to);return e?(t=e.find(o=>o.active))==null?void 0:t.address:null},ut=class{constructor(){this.getEthereumProvider=()=>{var t;return((t=this.activeWalletConnector)==null?void 0:t.provider)||new fe};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new co,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}),this.initialized=!0)}initializeLinkedWallets(t){t.linkedAccounts.forEach(()=>{})}load(){(Q.get(to)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)})}save(){let t=this.walletConnectors.map(o=>{var r;return{address:o.address,walletType:o.walletType,active:o.address===((r=this.activeWalletConnector)==null?void 0:r.address)}});Q.put(to,t)}addWalletConnector(t){this.walletConnectors.find(r=>r.address===t.address&&r.walletType===t.walletType)||this.walletConnectors.push(t)}getConnectorByAddress(t){return this.walletConnectors.find(o=>{var r;return((r=o.address)==null?void 0:r.toLowerCase())===t.toLowerCase()})}async removeWallet(t){var r;if(this.walletConnectors=this.walletConnectors.filter(n=>n.address!==t),t===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let n=this.walletConnectors[this.walletConnectors.length-1];await this.setActiveWallet(n.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(t){if(!this.activeWalletConnector)throw new H("Cannot sign, no wallet is active. Is a wallet connected?");if(!await this.activeWalletConnector.connect({showPrompt:!1}))throw new H("Cannot sign - unable to connect to wallet.");return this.activeWalletConnector.sign(t)}async setActiveWallet(t){let o=this.walletConnectors.find(r=>r.address===t);return o?(await o.setActive(),this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(t,o){switch(t){case"metamask":return new so(new fe,o);case"coinbase_wallet":return new lo(new fe,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new fe,o)}}};function Be(e){return new Date(e*1e3)}function os(e){let t=[];for(let o of e){let r=o.type;switch(o.type){case"wallet":let n={address:o.address,type:o.type,verifiedAt:Be(o.verified_at),chainType:o.chain_type,walletClient:o.wallet_client};t.push(n);break;case"email":let i={address:o.address,type:o.type,verifiedAt:Be(o.verified_at)};t.push(i);break;case"phone":let s={number:o.phoneNumber,type:o.type,verifiedAt:Be(o.verified_at)};t.push(s);break;case"google_oauth":let a={subject:o.subject,email:o.email,name:o.name,type:o.type,verifiedAt:Be(o.verified_at)};t.push(a);break;case"twitter_oauth":let p={subject:o.subject,username:o.username,name:o.name,type:o.type,verifiedAt:Be(o.verified_at)};t.push(p);break;case"discord_oauth":let h={subject:o.subject,username:o.username,email:o.email,type:o.type,verifiedAt:Be(o.verified_at)};t.push(h);break;case"github_oauth":let L={subject:o.subject,username:o.username,name:o.name,email:o.email,type:o.type,verifiedAt:Be(o.verified_at)};t.push(L);break;default:console.warn(`Unrecognized account type: ${r}. Please consider upgrading the Privy SDK.`)}}return t}function et(e,t){return e.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),e.find(o=>o.type===t)}function Mt(e){let t=Xr();if(!t)return e.wallet&&console.warn("[Privy] User has linked wallets but no active wallet"),e;let o=e.linkedAccounts.find(n=>n.type==="wallet"&&n.address===t);if(!o)return e;let r=Object.assign({},e);return r.wallet=o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletClient:o.walletClient},r}var Ie=e=>e==null?void 0:e.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClient==="privy");function Re(e){if(!e)return null;let t=os(e.linked_accounts),o=et(t,"wallet"),r=et(t,"email"),n=et(t,"phone"),i=et(t,"google_oauth"),s=et(t,"twitter_oauth"),a=et(t,"discord_oauth"),p=et(t,"github_oauth"),h={id:e.id,createdAt:Be(e.created_at),linkedAccounts:t,email:r&&{address:r==null?void 0:r.address},phone:n&&{number:n==null?void 0:n.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletClient:o.walletClient},google:i&&{subject:i.subject,email:i.email,name:i.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:a&&{subject:a.subject,username:a.username,email:a.email},github:p&&{subject:p.subject,username:p.username,name:p.name,email:p.email}};return Mt(h)}var Qr=()=>"/api/v1/sessions",en=()=>"/api/v1/sessions/logout",tn=()=>"/api/v1/sessions/fork",on=()=>"/api/v1/siwe/init",rn=()=>"/api/v1/siwe/authenticate",nn=()=>"/api/v1/siwe/link",sn=()=>"/api/v1/passwordless/init",an=()=>"/api/v1/passwordless/authenticate",ln=()=>"/api/v1/passwordless/link",cn=()=>"/api/v1/passwordless_sms/init",dn=()=>"/api/v1/passwordless_sms/authenticate",pn=()=>"/api/v1/passwordless_sms/link",un=()=>"/api/v1/oauth/init",hn=()=>"/api/v1/oauth/authenticate",mn=()=>"/api/v1/oauth/link",fn=()=>"/api/v1/siwe/unlink",gn=()=>"/api/v1/passwordless/unlink",yn=()=>"/api/v1/passwordless_sms/unlink",wn=()=>"/api/v1/oauth/unlink";var rs=30,uo=class{constructor(){this.authenticateOnce=new De(async t=>this._authenticate(t)),this.linkOnce=new De(async t=>this._link(t)),this.refreshOnce=new De(this._refresh.bind(this)),this.destroyOnce=new De(this._destroy.bind(this)),this.forkSessionOnce=new De(this._forkSession.bind(this))}get token(){try{let t=Q.get(lt);return typeof t=="string"?new We(t).value:null}catch(t){return console.error(t),this.destroyLocalState(),null}}get refreshToken(){try{let t=Q.get(eo);return typeof t=="string"?t:null}catch(t){return console.error(t),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let t=We.parse(this.token);return t!==null&&!t.isExpired(rs)}authenticate(t){return this.authenticateOnce.execute(t)}link(t){return this.linkOnce.execute(t)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(t){try{let{token:o,refresh_token:r,user:n,is_new_user:i}=await t.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:Re(n),isNewUser:i}}catch(o){throw console.warn("Error authenticating session"),ce(o)}}async _link(t){try{let o=await t.link();return Re(o)}catch(o){throw console.warn("Error linking account"),ce(o)}}async _refresh(){if(!this.api)throw new y("Session has no API instance");if(!this.client)throw new y("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let t=this.token,o=this.refreshToken;if(!t||!o)return null;try{let r=await this.api.post(Qr(),{refresh_token:o},{headers:{authorization:`Bearer ${t}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),Re(r.data.user)}catch(r){if(r instanceof at&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw ce(r)}}async _destroy(){var t;try{await((t=this.api)==null?void 0:t.post(en(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new y("Session has no API instance");let t=this.refreshToken;try{let o=await this.api.post(tn(),{refresh_token:t});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw ce(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(t){typeof t=="string"?Q.put(lt,t):Q.del(lt)}storeRefreshToken(t){typeof t=="string"?Q.put(eo,t):Q.del(eo)}};var Qo,ht=class{constructor(t){let o=t.apiURL||Mr,r=t.timeout||Nr;this.appId=t.appId,this.connectors=new ut,Qo||(Qo=new uo),this.session=Qo,this.api=new ro(t.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new y("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new y("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.authFlow=void 0}startAuthFlow(t){t.api=this.api,this.authFlow=t}async unlinkEmail(t){try{let o=await this.api.post(gn(),{address:t});return Re(o.data)}catch(o){throw ce(o)}}async unlinkPhone(t){try{let o=await this.api.post(yn(),{phoneNumber:t});return Re(o.data)}catch(o){throw ce(o)}}async unlinkWallet(t){try{let o=await this.api.post(fn(),{address:t});return this.connectors.removeWallet(t),Re(o.data)}catch(o){throw ce(o)}}async unlinkOAuth(t,o){try{let r=await this.api.post(wn(),{provider:t,subject:o});return Re(r.data)}catch(r){throw ce(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(t){var o;return this.session.hasActiveToken()?((o=We.parse(this.session.token))==null?void 0:o.audience)!==this.appId?(await this.logout(),null):this.session.token:!(t!=null&&t.disableAutoRefresh)&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getAppSettings(){try{let t=await this.api.get(`/api/v1/apps/${this.appId}`);return{id:t.data.id,name:t.data.name,verificationKey:t.data.verification_key,logoUrl:t.data.logo_url||void 0,theme:t.data.theme,accentColor:t.data.accent_color||void 0,showWalletLoginFirst:t.data.show_wallet_login_first,allowlistConfig:{errorTitle:t.data.allowlist_config.error_title,errorDetail:t.data.allowlist_config.error_detail,errorCtaText:t.data.allowlist_config.cta_text,errorCtaLink:t.data.allowlist_config.cta_link},walletAuth:t.data.wallet_auth,emailAuth:t.data.email_auth,smsAuth:t.data.sms_auth,googleOAuth:t.data.google_oauth,twitterOAuth:t.data.twitter_oauth,discordOAuth:t.data.discord_oauth,githubOAuth:t.data.github_oauth,termsAndConditionsUrl:t.data.terms_and_conditions_url,privacyPolicyUrl:t.data.privacy_policy_url,createdAt:new Date(t.data.created_at*1e3),updatedAt:new Date(t.data.updated_at*1e3)}}catch(t){throw ce(t)}}async setActiveWallet(t,o){if(!o.linkedAccounts.map(i=>i.type==="wallet"?i.address:null).includes(t))throw new y("Cannot set an unlinked address as active.");if(!await this.connectors.setActiveWallet(t))throw new y("Error setting the active wallet.");return Mt(o)}async forkSession(){return await this.session.forkSession()}};var Fi=require("@ethersproject/providers");var ho=require("react");var v=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var er=(0,ho.createContext)({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}),z=()=>(0,ho.useContext)(er);var Nt=class{constructor(t,o){this.meta={walletType:o},this.connectors=t,this.walletConnector=this.connectors.createWalletConnector(o,null)}async authenticate(){if(!this.api)throw new y("Auth flow has no API instance");try{let{message:t,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(rn(),{message:t,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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");try{let{message:t,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(nn(),{message:t,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(t){throw F(t)}}async promptConnectAndSign(t){let o=await this.walletConnector.connect({showPrompt:!0}),r=o.address,n=o.chainId,i=await t.post(on(),{address:r}),s=this.walletConnector.prepareMessage(n,r,i.data.nonce),a=await this.walletConnector.sign(s);return{message:s,signature:a}}};var Ot=class{constructor(t){this.meta={email:t}}async authenticate(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new y("Email and email code must be set prior to calling authenticate.");try{let t=an(),o=await this.api.post(t,{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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new y("Email and email code must be set prior to calling authenticate.");try{let t=ln();return(await this.api.post(t,{email:this.meta.email,code:this.meta.emailCode})).data}catch(t){throw F(t)}}async sendCodeEmail(t){if(!this.api)throw new y("Auth flow has no API instance");if(t&&(this.meta.email=t),!this.meta.email)throw new y("Email must be set when initialzing authentication.");try{let o=sn();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw F(o)}}};var Ut=class{constructor(t){this.meta={phoneNumber:t}}async authenticate(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new y("phone number and sms code must be set prior to calling authenticate.");try{let t=dn(),o=await this.api.post(t,{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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new y("phone number and sms code must be set prior to calling authenticate.");try{let t=pn();return(await this.api.post(t,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})).data}catch(t){throw F(t)}}async sendSmsCode(t){if(!this.api)throw new y("Auth flow has no API instance");if(t&&(this.meta.phoneNumber=t),!this.meta.phoneNumber)throw new y("phone nNumber must be set when initialzing authentication.");try{let o=cn();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw F(o)}}};var mt=class{constructor(t,o,r){this.meta={provider:t},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 y("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new y("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new y("User denied confirmation during OAuth flow");try{let t=hn(),o=await this.api.post(t,{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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new y("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new y("User denied confirmation during OAuth flow");try{let t=mn();return(await this.api.post(t,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode})).data}catch(t){throw F(t)}}async getAuthorizationUrl(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.provider)throw new y("Provider must be set when initialzing OAuth authentication.");try{let t=un();return(await this.api.post(t,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(t){throw F(t)}}};var yo=require("react");var mo=class{constructor(){this.callbacks={}}enqueue(t,o){this.callbacks[t]=o}dequeue(t,o){let r=this.callbacks[o];if(!r)throw new Error(`cannot dequeue ${t} event: no event found for id ${o}`);switch(delete this.callbacks[o],t){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 ${t}`)}}};var Cn=require("react/jsx-runtime"),ns=function(e){return()=>`id-${e++}`}(0);function is(e){return typeof e.event=="string"&&/^privy:.+/.test(e.event)}function fo(e){return e.error!==void 0}var Dt=new mo;function go(e,t,o){let r=o.contentWindow;if(!r)throw new Error("iframe not initialized");return new Promise((n,i)=>{let s=ns();Dt.enqueue(s,{resolve:n,reject:i}),r.postMessage({id:s,event:e,data:t},"*")})}function ss(e){switch(e.event){case"privy:iframe:ready":let t=Dt.dequeue(e.event,e.id);return fo(e)?t.reject(new Error(e.error.message)):t.resolve(e.data);case"privy:wallet:create":let o=Dt.dequeue(e.event,e.id);return fo(e)?o.reject(new Error(e.error.message)):o.resolve(e.data);case"privy:wallet:sign":let r=Dt.dequeue(e.event,e.id);return fo(e)?r.reject(new Error(e.error.message)):r.resolve(e.data);case"privy:wallet:recover":let n=Dt.dequeue(e.event,e.id);return fo(e)?n.reject(new Error(e.error.message)):n.resolve(e.data)}}function vn(e){let t=(0,yo.useRef)(null);return(0,yo.useEffect)(()=>{let o=t.current;if(!o)return;function r(a){a&&a.origin===e.origin&&is(a.data)&&ss(a.data)}let n={create(a){return go("privy:wallet:create",a,o)},sign(a){return go("privy:wallet:sign",a,o)},recover(a){return go("privy:wallet:recover",a,o)}};window.addEventListener("message",r);let i=()=>e.onLoad(n),s=(...a)=>{console.error("privy iframe failed to load: ",...a),e.onLoadFailed()};return $r(()=>go("privy:iframe:ready",{},o)).then(i,s),()=>window.removeEventListener("message",r)},[t.current]),(0,Cn.jsx)("iframe",{ref:t,width:"0",height:"0",style:{visibility:"hidden"},src:jr(e.origin,`/apps/${e.appId}/embedded-wallets`)})}var a2=require("wicg-inert"),Ni=require("react"),Oi=E(require("react-dom")),Go=E(require("styled-components"));var ge=require("react");var xn=require("react/jsx-runtime");function bn(e){return(0,xn.jsx)("link",{rel:"prefetch",href:e.src})}var wo=require("react/jsx-runtime"),Me="LANDING",En=(0,ge.createContext)({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:Me,lastScreen:Me,navigate:v,navigateBack:v}),Ln=e=>{let t=e.appSettings,o=e.authenticated,r=e.visible,[n,i]=(0,ge.useState)(e.initialScreen||Me),[s,a]=(0,ge.useState)(e.initialScreen||Me);(0,ge.useEffect)(()=>{o||i(Me)},[o]),(0,ge.useEffect)(()=>{r||(a(Me),i(Me))},[r]),(0,ge.useEffect)(()=>{e.initialScreen&&n===Me&&(i(e.initialScreen),a(e.initialScreen))},[e.initialScreen]);let p=e.initialScreen&&n===Me?e.initialScreen:n,h={ready:!!(t!=null&&t.id),app:t,options:e.options,data:e.data,currentScreen:p,lastScreen:s,navigate:L=>{a(n),i(L)},navigateBack:()=>{i(s)}};return(0,wo.jsxs)(En.Provider,{value:h,children:[t&&t.logoUrl&&(0,wo.jsx)(bn,{src:t.logoUrl}),e.children]})},C=()=>(0,ge.useContext)(En);var On=require("react"),ot=E(require("styled-components"));var kn=E(require("styled-components"));var tr=require("react/jsx-runtime"),An=({style:e,...t})=>(0,tr.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...e},...t,children:(0,tr.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});var or=require("react/jsx-runtime"),_n=({style:e,...t})=>(0,or.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...e},...t,children:(0,or.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});var vo=require("react");var rr=(0,vo.createContext)({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}),S=()=>(0,vo.useContext)(rr);var de=require("react/jsx-runtime"),as=()=>(0,de.jsx)("div",{}),ls=({backFn:e})=>(0,de.jsx)("div",{children:(0,de.jsx)(_n,{onClick:e})}),cs=e=>(0,de.jsx)("div",{children:(0,de.jsx)("div",{children:(0,de.jsx)(An,{onClick:e.onClose})})});var _=({backFn:e,onClose:t})=>{let{closePrivyModal:o}=S();return(0,de.jsxs)(ds,{children:[e?(0,de.jsx)(ls,{backFn:e}):(0,de.jsx)(as,{}),(0,de.jsx)(cs,{onClose:t||(()=>o())})]})},ds=kn.default.div`
|
|
12
|
+
- https://privy.io`;this.provider=o,this.walletType=t,this.address=r,this.chain=null,this.connected=!1}async fetchAddress(){if(!this.address){let t=await this.provider.request({method:"eth_accounts"});Array.isArray(t)&&t.length>0&&(this.address=(0,Fr.getAddress)(t[0]))}return this.address}async fetchChainId(){if(!this.chain){let t=await this.provider.request({method:"eth_chainId"}),o=Number(t);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(t){return new Gr.Web3Provider(new Ge(this.provider)).getSigner().signMessage(t)}prepareMessage(t,o,r){let n=window.location.host,i=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(t,o,n,i,a,r,s)}};var Br=require("libphonenumber-js/min");var Vr=e=>!!String(e).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,}))$/),Hr=e=>(0,Br.isPossiblePhoneNumber)(String(e),"US"),io=e=>{var t=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;e=e.replace(t,function(r,n,i,s){return n+n+i+i+s+s});var o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);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)}},zr=(e,t)=>{var o=e.slice(0);let r=[];for(;o.length;)r.push(o.splice(0,t));return r},Qe=(e,t=3,o=4)=>{if(!e)return"";let r=2,n=3;if(t+o+r+n>=e.length)return e;let i=e.slice(0,r+t),s=e.slice(e.length-o,e.length);return`${i}...${s}`},Zo=e=>new Promise(t=>setTimeout(t,e)),$r=(e,t={})=>{let o=t.delayMs||40,r=t.maxAttempts||1e3;return new Promise(async(n,i)=>{let s=!1,a=0;for(;!s&&a<r;)e().then(()=>{s=!0,n()},(...p)=>{s=!0,i(...p)}),a+=1,await Zo(o);s||i(new Error("Exceeded max attempts before resolving function"))})},jr=(...e)=>{let o=e.length-1;return e.map((n,i)=>(i===0&&(n.startsWith("//")||n.endsWith("://"))?n=n.replace(new RegExp("/$"),""):i!==o&&(n=n.replace(new RegExp("/+$"),"")),i!==0&&(n=n.replace(new RegExp("^/+"),"")),n)).join("/")};var qr=require("react-device-detect"),so=class extends _e{constructor(t,o){var r;super("metamask",t,o),this.provider.setProvider(window.ethereum),(r=window.ethereum.providers)==null||r.forEach(async n=>{n.isMetaMask&&this.provider.setProvider(n)}),this.subscribeListeners()}async connect(t){return t.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}async isConnected(){let t=await this.connectedMetamaskAddress();return this.address===t}async connectedMetamaskAddress(){let o=await new Zr.Web3Provider(this.provider).listAccounts();return o.length===0?null:(0,qo.getAddress)(o[0])}disconnect(){console.warn("Metamask does not support programmetic disconnect.")}async promptConnection(){try{let t="";if(!qr.isMobile&&(await this.provider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.address&&await this.isConnected()))throw new H("Selected the wrong wallet in MetaMask");let o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(t=(0,qo.getAddress)(o[0])),!t||t==="")throw new H("Unable to retrieve address");this.connected=!0,this.address=t}catch(t){throw Fe(t)}}async setActive(){if(await this.connectedMetamaskAddress()===this.address)return this.connected=!0,!0;for(;!this.connected;)await Zo(200);return!0}subscribeListeners(){this.provider.on("accountsChanged",t=>{var o;if(t.length>0){let r=t[0];this.connected=((o=this.address)==null?void 0:o.toLowerCase())===(r==null?void 0:r.toLowerCase())}}),this.provider.on("disconnect",()=>{this.connected=!1})}};var Kr=require("@ethersproject/address");var Jr=E(require("@coinbase/wallet-sdk"));var ts=e=>{let t=`https://mainnet.infura.io/v3/${Rt}`,o=1;return e.makeWeb3Provider(t,o)},ao,lo=class extends _e{constructor(t,o){super("coinbase_wallet",t,o),ao||(ao=new Jr.default({appName:"Privy",darkMode:!1,headlessMode:!1}))}async connect(t){return this.provider.setProvider(ts(ao)),t.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){ao.disconnect()}async isConnected(){return await this.fetchAddress()!==null}async promptConnection(){try{let t="",o=await this.provider.request({method:"eth_requestAccounts"});if(o.length>0&&(t=(0,Kr.getAddress)(o[0])),!t||t==="")throw new H("Unable to retrieve address");this.connected=!0}catch(t){throw Fe(t)}}};var Ko=E(require("@walletconnect/web3-provider"));var Jo=class extends _e{constructor(o,r,n){super("wallet_connect",r,n);this._globalConnector=o,this._provider=this._globalConnector.getProviderForAddress(n)}async connect(o){return this.provider.setProvider(this._provider),o.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}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(),jo()]);if(r.length>0&&(o=r[0]),this._globalConnector.indexProvider(this._provider),!o||o==="")throw new H("Unable to retrieve address");this.connected=!0}catch(o){throw Fe(o)}}disconnect(){}},co=class{constructor(){this._storageIdToProvider={},this._addressToStorageId={},Q.getKeys().forEach(t=>{if(t.startsWith("walletconnect")){let o=new Ko.default({infuraId:Rt,storageId:t});this._storageIdToProvider[t]=o;for(let r of o.accounts)this._addressToStorageId[r]=t}})}build(t,o){return new Jo(this,t,o)}async disconnect(){Object.values(this._storageIdToProvider).forEach(async t=>{await t.disconnect()})}getProviderForAddress(t){let o=Or,r=()=>`walletconnect:${Math.random().toString(36).slice(2)}`;t===null?o=r():o=this._addressToStorageId[t]||r();let n=new Ko.default({infuraId:Rt,storageId:o});return this._storageIdToProvider[o]=n,n}indexProvider(t){this._storageIdToProvider[t.storageId]=t;for(let o of t.accounts)this._addressToStorageId[o]=t.storageId}};var Yr=require("@ethersproject/address"),Yo=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let e of window.ethereum.providers)if(e.isMetaMask)return!0}return!1},po=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let e of window.ethereum.providers)if(e.isCoinbaseWallet)return!0}return!1},Xo=e=>{let t=localStorage.getItem("-walletlink:https://www.walletlink.org:Addresses");return t?!!(e==null?void 0:e.linkedAccounts.filter(r=>r.type=="wallet"&&r.address===(0,Yr.getAddress)(t)).length):!1},Xr=()=>{var t;let e=Q.get(to);return e?(t=e.find(o=>o.active))==null?void 0:t.address:null},ut=class{constructor(){this.getEthereumProvider=()=>{var t;return((t=this.activeWalletConnector)==null?void 0:t.provider)||new fe};this.walletConnectors=[],this.walletConnectGlobalWalletConnector=new co,this.initialized=!1}initialize(){this.initialized||(this.load(),this.activeWalletConnector&&this.activeWalletConnector.connect({showPrompt:!1}),this.initialized=!0)}initializeLinkedWallets(t){t.linkedAccounts.forEach(()=>{})}load(){(Q.get(to)||[]).forEach(o=>{let r=this.createWalletConnector(o.walletType,o.address);this.addWalletConnector(r),o.active&&(this.activeWalletConnector=r)})}save(){let t=this.walletConnectors.map(o=>{var r;return{address:o.address,walletType:o.walletType,active:o.address===((r=this.activeWalletConnector)==null?void 0:r.address)}});Q.put(to,t)}addWalletConnector(t){this.walletConnectors.find(r=>r.address===t.address&&r.walletType===t.walletType)||this.walletConnectors.push(t)}getConnectorByAddress(t){return this.walletConnectors.find(o=>{var r;return((r=o.address)==null?void 0:r.toLowerCase())===t.toLowerCase()})}async removeWallet(t){var r;if(this.walletConnectors=this.walletConnectors.filter(n=>n.address!==t),t===((r=this.activeWalletConnector)==null?void 0:r.address))if(this.walletConnectors.length>0){let n=this.walletConnectors[this.walletConnectors.length-1];await this.setActiveWallet(n.address)}else this.activeWalletConnector=void 0;this.save()}async activeWalletSign(t){if(!this.activeWalletConnector)throw new H("Cannot sign, no wallet is active. Is a wallet connected?");if(!await this.activeWalletConnector.connect({showPrompt:!1}))throw new H("Cannot sign - unable to connect to wallet.");return this.activeWalletConnector.sign(t)}async setActiveWallet(t){let o=this.walletConnectors.find(r=>r.address===t);return o?(await o.setActive(),this.activeWalletConnector=o,this.save(),!0):!1}createWalletConnector(t,o){switch(t){case"metamask":return new so(new fe,o);case"coinbase_wallet":return new lo(new fe,o);case"wallet_connect":return this.walletConnectGlobalWalletConnector.build(new fe,o)}}};function Be(e){return new Date(e*1e3)}function os(e){let t=[];for(let o of e){let r=o.type;switch(o.type){case"wallet":let n={address:o.address,type:o.type,verifiedAt:Be(o.verified_at),chainType:o.chain_type,walletClient:o.wallet_client};t.push(n);break;case"email":let i={address:o.address,type:o.type,verifiedAt:Be(o.verified_at)};t.push(i);break;case"phone":let s={number:o.phoneNumber,type:o.type,verifiedAt:Be(o.verified_at)};t.push(s);break;case"google_oauth":let a={subject:o.subject,email:o.email,name:o.name,type:o.type,verifiedAt:Be(o.verified_at)};t.push(a);break;case"twitter_oauth":let p={subject:o.subject,username:o.username,name:o.name,type:o.type,verifiedAt:Be(o.verified_at)};t.push(p);break;case"discord_oauth":let h={subject:o.subject,username:o.username,email:o.email,type:o.type,verifiedAt:Be(o.verified_at)};t.push(h);break;case"github_oauth":let L={subject:o.subject,username:o.username,name:o.name,email:o.email,type:o.type,verifiedAt:Be(o.verified_at)};t.push(L);break;default:console.warn(`Unrecognized account type: ${r}. Please consider upgrading the Privy SDK.`)}}return t}function et(e,t){return e.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),e.find(o=>o.type===t)}function Mt(e){let t=Xr();if(!t)return e.wallet&&console.warn("[Privy] User has linked wallets but no active wallet"),e;let o=e.linkedAccounts.find(n=>n.type==="wallet"&&n.address===t);if(!o)return e;let r=Object.assign({},e);return r.wallet=o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletClient:o.walletClient},r}var Ie=e=>e==null?void 0:e.linkedAccounts.find(t=>t.type==="wallet"&&t.walletClient==="privy");function Re(e){if(!e)return null;let t=os(e.linked_accounts),o=et(t,"wallet"),r=et(t,"email"),n=et(t,"phone"),i=et(t,"google_oauth"),s=et(t,"twitter_oauth"),a=et(t,"discord_oauth"),p=et(t,"github_oauth"),h={id:e.id,createdAt:Be(e.created_at),linkedAccounts:t,email:r&&{address:r==null?void 0:r.address},phone:n&&{number:n==null?void 0:n.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletClient:o.walletClient},google:i&&{subject:i.subject,email:i.email,name:i.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:a&&{subject:a.subject,username:a.username,email:a.email},github:p&&{subject:p.subject,username:p.username,name:p.name,email:p.email}};return Mt(h)}var Qr=()=>"/api/v1/sessions",en=()=>"/api/v1/sessions/logout",tn=()=>"/api/v1/sessions/fork",on=()=>"/api/v1/siwe/init",rn=()=>"/api/v1/siwe/authenticate",nn=()=>"/api/v1/siwe/link",sn=()=>"/api/v1/passwordless/init",an=()=>"/api/v1/passwordless/authenticate",ln=()=>"/api/v1/passwordless/link",cn=()=>"/api/v1/passwordless_sms/init",dn=()=>"/api/v1/passwordless_sms/authenticate",pn=()=>"/api/v1/passwordless_sms/link",un=()=>"/api/v1/oauth/init",hn=()=>"/api/v1/oauth/authenticate",mn=()=>"/api/v1/oauth/link",fn=()=>"/api/v1/siwe/unlink",gn=()=>"/api/v1/passwordless/unlink",yn=()=>"/api/v1/passwordless_sms/unlink",wn=()=>"/api/v1/oauth/unlink";var rs=30,uo=class{constructor(){this.authenticateOnce=new De(async t=>this._authenticate(t)),this.linkOnce=new De(async t=>this._link(t)),this.refreshOnce=new De(this._refresh.bind(this)),this.destroyOnce=new De(this._destroy.bind(this)),this.forkSessionOnce=new De(this._forkSession.bind(this))}get token(){try{let t=Q.get(lt);return typeof t=="string"?new We(t).value:null}catch(t){return console.error(t),this.destroyLocalState(),null}}get refreshToken(){try{let t=Q.get(eo);return typeof t=="string"?t:null}catch(t){return console.error(t),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let t=We.parse(this.token);return t!==null&&!t.isExpired(rs)}authenticate(t){return this.authenticateOnce.execute(t)}link(t){return this.linkOnce.execute(t)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(t){try{let{token:o,refresh_token:r,user:n,is_new_user:i}=await t.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:Re(n),isNewUser:i}}catch(o){throw console.warn("Error authenticating session"),ce(o)}}async _link(t){try{let o=await t.link();return Re(o)}catch(o){throw console.warn("Error linking account"),ce(o)}}async _refresh(){if(!this.api)throw new y("Session has no API instance");if(!this.client)throw new y("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let t=this.token,o=this.refreshToken;if(!t||!o)return null;try{let r=await this.api.post(Qr(),{refresh_token:o},{headers:{authorization:`Bearer ${t}`}});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),Re(r.data.user)}catch(r){if(r instanceof at&&r.status===400&&r.message==="Invalid auth token")return this.destroyLocalState(),null;throw ce(r)}}async _destroy(){var t;try{await((t=this.api)==null?void 0:t.post(en(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new y("Session has no API instance");let t=this.refreshToken;try{let o=await this.api.post(tn(),{refresh_token:t});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw ce(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null)}storeToken(t){typeof t=="string"?Q.put(lt,t):Q.del(lt)}storeRefreshToken(t){typeof t=="string"?Q.put(eo,t):Q.del(eo)}};var Qo,ht=class{constructor(t){let o=t.apiURL||Mr,r=t.timeout||Nr;this.appId=t.appId,this.connectors=new ut,Qo||(Qo=new uo),this.session=Qo,this.api=new ro(t.appId,this,{baseURL:o,timeout:r}),this.session.api=this.api,this.session.client=this}authenticate(){if(!this.authFlow)throw new y("No auth flow in progress.");return this.session.authenticate(this.authFlow)}link(){if(!this.authFlow)throw new y("No auth flow in progress.");return this.session.link(this.authFlow)}async logout(){await this.session.destroy(),this.authFlow=void 0}startAuthFlow(t){t.api=this.api,this.authFlow=t}async unlinkEmail(t){try{let o=await this.api.post(gn(),{address:t});return Re(o.data)}catch(o){throw ce(o)}}async unlinkPhone(t){try{let o=await this.api.post(yn(),{phoneNumber:t});return Re(o.data)}catch(o){throw ce(o)}}async unlinkWallet(t){try{let o=await this.api.post(fn(),{address:t});return this.connectors.removeWallet(t),Re(o.data)}catch(o){throw ce(o)}}async unlinkOAuth(t,o){try{let r=await this.api.post(wn(),{provider:t,subject:o});return Re(r.data)}catch(r){throw ce(r)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(t){var o;return this.session.hasActiveToken()?((o=We.parse(this.session.token))==null?void 0:o.audience)!==this.appId?(await this.logout(),null):this.session.token:!(t!=null&&t.disableAutoRefresh)&&this.session.hasRefreshCredentials()?(await this.session.refresh(),this.session.token):null}async getAppSettings(){try{let t=await this.api.get(`/api/v1/apps/${this.appId}`);return{id:t.data.id,name:t.data.name,verificationKey:t.data.verification_key,logoUrl:t.data.logo_url||void 0,theme:t.data.theme,accentColor:t.data.accent_color||void 0,showWalletLoginFirst:t.data.show_wallet_login_first,allowlistConfig:{errorTitle:t.data.allowlist_config.error_title,errorDetail:t.data.allowlist_config.error_detail,errorCtaText:t.data.allowlist_config.cta_text,errorCtaLink:t.data.allowlist_config.cta_link},walletAuth:t.data.wallet_auth,emailAuth:t.data.email_auth,smsAuth:t.data.sms_auth,googleOAuth:t.data.google_oauth,twitterOAuth:t.data.twitter_oauth,discordOAuth:t.data.discord_oauth,githubOAuth:t.data.github_oauth,termsAndConditionsUrl:t.data.terms_and_conditions_url,privacyPolicyUrl:t.data.privacy_policy_url,createdAt:new Date(t.data.created_at*1e3),updatedAt:new Date(t.data.updated_at*1e3)}}catch(t){throw ce(t)}}async setActiveWallet(t,o){if(!o.linkedAccounts.map(i=>i.type==="wallet"?i.address:null).includes(t))throw new y("Cannot set an unlinked address as active.");if(!await this.connectors.setActiveWallet(t))throw new y("Error setting the active wallet.");return Mt(o)}async forkSession(){return await this.session.forkSession()}};var Fi=require("@ethersproject/providers");var ho=require("react");var v=()=>{throw new Error("You need to wrap your application with the <PrivyProvider> initialized with your app id.")};var er=(0,ho.createContext)({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}),z=()=>(0,ho.useContext)(er);var Nt=class{constructor(t,o){this.meta={walletType:o},this.connectors=t,this.walletConnector=this.connectors.createWalletConnector(o,null)}async authenticate(){if(!this.api)throw new y("Auth flow has no API instance");try{let{message:t,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(rn(),{message:t,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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");try{let{message:t,signature:o}=await this.promptConnectAndSign(this.api),r=await this.api.post(nn(),{message:t,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(t){throw F(t)}}async promptConnectAndSign(t){let o=await this.walletConnector.connect({showPrompt:!0}),r=o.address,n=o.chainId,i=await t.post(on(),{address:r}),s=this.walletConnector.prepareMessage(n,r,i.data.nonce),a=await this.walletConnector.sign(s);return{message:s,signature:a}}};var Ot=class{constructor(t){this.meta={email:t}}async authenticate(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new y("Email and email code must be set prior to calling authenticate.");try{let t=an(),o=await this.api.post(t,{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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new y("Email and email code must be set prior to calling authenticate.");try{let t=ln();return(await this.api.post(t,{email:this.meta.email,code:this.meta.emailCode})).data}catch(t){throw F(t)}}async sendCodeEmail(t){if(!this.api)throw new y("Auth flow has no API instance");if(t&&(this.meta.email=t),!this.meta.email)throw new y("Email must be set when initialzing authentication.");try{let o=sn();return(await this.api.post(o,{email:this.meta.email})).data}catch(o){throw F(o)}}};var Ut=class{constructor(t){this.meta={phoneNumber:t}}async authenticate(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new y("phone number and sms code must be set prior to calling authenticate.");try{let t=dn(),o=await this.api.post(t,{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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new y("phone number and sms code must be set prior to calling authenticate.");try{let t=pn();return(await this.api.post(t,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})).data}catch(t){throw F(t)}}async sendSmsCode(t){if(!this.api)throw new y("Auth flow has no API instance");if(t&&(this.meta.phoneNumber=t),!this.meta.phoneNumber)throw new y("phone nNumber must be set when initialzing authentication.");try{let o=cn();return(await this.api.post(o,{phoneNumber:this.meta.phoneNumber})).data}catch(o){throw F(o)}}};var mt=class{constructor(t,o,r){this.meta={provider:t},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 y("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new y("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if(this.meta.authorizationCode==="undefined")throw new y("User denied confirmation during OAuth flow");try{let t=hn(),o=await this.api.post(t,{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(t){throw F(t)}}async link(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new y("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if(this.meta.authorizationCode==="undefined")throw new y("User denied confirmation during OAuth flow");try{let t=mn();return(await this.api.post(t,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode})).data}catch(t){throw F(t)}}async getAuthorizationUrl(){if(!this.api)throw new y("Auth flow has no API instance");if(!this.meta.provider)throw new y("Provider must be set when initialzing OAuth authentication.");try{let t=un();return(await this.api.post(t,{provider:this.meta.provider,redirect_to:window.location.href})).data}catch(t){throw F(t)}}};var yo=require("react");var mo=class{constructor(){this.callbacks={}}enqueue(t,o){this.callbacks[t]=o}dequeue(t,o){let r=this.callbacks[o];if(!r)throw new Error(`cannot dequeue ${t} event: no event found for id ${o}`);switch(delete this.callbacks[o],t){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 ${t}`)}}};var Cn=require("react/jsx-runtime"),ns=function(e){return()=>`id-${e++}`}(0);function is(e){return typeof e.event=="string"&&/^privy:.+/.test(e.event)}function fo(e){return e.error!==void 0}var Dt=new mo;function go(e,t,o){let r=o.contentWindow;if(!r)throw new Error("iframe not initialized");return new Promise((n,i)=>{let s=ns();Dt.enqueue(s,{resolve:n,reject:i}),r.postMessage({id:s,event:e,data:t},"*")})}function ss(e){switch(e.event){case"privy:iframe:ready":let t=Dt.dequeue(e.event,e.id);return fo(e)?t.reject(new Error(e.error.message)):t.resolve(e.data);case"privy:wallet:create":let o=Dt.dequeue(e.event,e.id);return fo(e)?o.reject(new Error(e.error.message)):o.resolve(e.data);case"privy:wallet:sign":let r=Dt.dequeue(e.event,e.id);return fo(e)?r.reject(new Error(e.error.message)):r.resolve(e.data);case"privy:wallet:recover":let n=Dt.dequeue(e.event,e.id);return fo(e)?n.reject(new Error(e.error.message)):n.resolve(e.data)}}function vn(e){let t=(0,yo.useRef)(null);return(0,yo.useEffect)(()=>{let o=t.current;if(!o)return;function r(a){a&&a.origin===e.origin&&is(a.data)&&ss(a.data)}let n={create(a){return go("privy:wallet:create",a,o)},sign(a){return go("privy:wallet:sign",a,o)},recover(a){return go("privy:wallet:recover",a,o)}};window.addEventListener("message",r);let i=()=>e.onLoad(n),s=(...a)=>{console.error("privy iframe failed to load: ",...a),e.onLoadFailed()};return $r(()=>go("privy:iframe:ready",{},o)).then(i,s),()=>window.removeEventListener("message",r)},[t.current]),(0,Cn.jsx)("iframe",{ref:t,width:"0",height:"0",style:{visibility:"hidden"},src:jr(e.origin,`/apps/${e.appId}/embedded-wallets`)})}var a2=require("wicg-inert"),Ni=require("react"),Oi=E(require("react-dom")),Go=E(require("styled-components"));var ge=require("react");var xn=require("react/jsx-runtime");function bn(e){return(0,xn.jsx)("link",{rel:"prefetch",href:e.src})}var wo=require("react/jsx-runtime"),Me="LANDING",En=(0,ge.createContext)({ready:!1,app:null,options:{email:!0,sms:!1,wallet:!0,google:!1,twitter:!1,discord:!1,github:!1},currentScreen:Me,lastScreen:Me,navigate:v,navigateBack:v}),Ln=e=>{let t=e.appSettings,o=e.authenticated,r=e.visible,[n,i]=(0,ge.useState)(e.initialScreen||Me),[s,a]=(0,ge.useState)(e.initialScreen||Me);(0,ge.useEffect)(()=>{o||i(Me)},[o]),(0,ge.useEffect)(()=>{r||(a(Me),i(Me))},[r]),(0,ge.useEffect)(()=>{e.initialScreen&&n===Me&&(i(e.initialScreen),a(e.initialScreen))},[e.initialScreen]);let p=e.initialScreen&&n===Me?e.initialScreen:n,h={ready:!!(t!=null&&t.id),app:t,options:e.options,data:e.data,currentScreen:p,lastScreen:s,navigate:L=>{a(n),i(L)},navigateBack:()=>{i(s)}};return(0,wo.jsxs)(En.Provider,{value:h,children:[t&&t.logoUrl&&(0,wo.jsx)(bn,{src:t.logoUrl}),e.children]})},C=()=>(0,ge.useContext)(En);var On=require("react"),ot=E(require("styled-components"));var kn=E(require("styled-components"));var tr=require("react/jsx-runtime"),An=({style:e,...t})=>(0,tr.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...e},...t,children:(0,tr.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})});var or=require("react/jsx-runtime"),_n=({style:e,...t})=>(0,or.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...e},...t,children:(0,or.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"})});var vo=require("react");var rr=(0,vo.createContext)({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}),S=()=>(0,vo.useContext)(rr);var de=require("react/jsx-runtime"),as=()=>(0,de.jsx)("div",{}),ls=({backFn:e})=>(0,de.jsx)("div",{children:(0,de.jsx)(_n,{onClick:e})}),cs=e=>(0,de.jsx)("div",{children:(0,de.jsx)("div",{children:(0,de.jsx)(An,{onClick:e.onClose})})});var _=({backFn:e,onClose:t})=>{let{closePrivyModal:o}=S();return(0,de.jsxs)(ds,{children:[e?(0,de.jsx)(ls,{backFn:e}):(0,de.jsx)(as,{}),(0,de.jsx)(cs,{onClose:t||(()=>o())})]})},ds=kn.default.div`
|
|
13
13
|
height: 30px;
|
|
14
14
|
display: flex;
|
|
15
15
|
align-items: center;
|
|
@@ -745,7 +745,7 @@ Resources:
|
|
|
745
745
|
border-color: var(--primary-color);
|
|
746
746
|
border-bottom-color: var(--primary-color);
|
|
747
747
|
}
|
|
748
|
-
`;var wr=require("react/jsx-runtime"),Zn=({style:e,...t})=>(0,wr.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...e},...t,children:(0,wr.jsx)("path",{
|
|
748
|
+
`;var wr=require("react/jsx-runtime"),Zn=({style:e,...t})=>(0,wr.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",style:{height:"1.5rem",width:"1.5rem",...e},...t,children:(0,wr.jsx)("path",{fillRule:"evenodd",d:"M12 1.5a5.25 5.25 0 00-5.25 5.25v3a3 3 0 00-3 3v6.75a3 3 0 003 3h10.5a3 3 0 003-3v-6.75a3 3 0 00-3-3v-3c0-2.9-2.35-5.25-5.25-5.25zm3.75 8.25v-3a3.75 3.75 0 10-7.5 0v3h7.5z",clipRule:"evenodd"})});var U=require("react/jsx-runtime"),Kn=()=>{let{navigate:e,app:t}=C(),o=(t==null?void 0:t.allowlistConfig.errorTitle)||"You don't have access to this app",r=(t==null?void 0:t.allowlistConfig.errorDetail)||"Have you been invited?",n=(t==null?void 0:t.allowlistConfig.errorCtaText)||"Try another account";return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(_,{}),(0,U.jsxs)($s,{children:[(0,U.jsx)(Zs,{children:(0,U.jsxs)("div",{children:[(0,U.jsx)(jn,{}),(0,U.jsx)(Zn,{style:{width:"38px",height:"38px",strokeWidth:"1",stroke:"var(--primary-color)",fill:"var(--primary-color)"}})]})}),(0,U.jsxs)(js,{children:[typeof o=="string"?(0,U.jsx)("h3",{children:o}):(0,U.jsx)(U.Fragment,{children:o}),typeof r=="string"?(0,U.jsx)("p",{children:r}):(0,U.jsx)(U.Fragment,{children:r})]}),t!=null&&t.allowlistConfig.errorCtaLink?(0,U.jsx)(qn,{as:"a",href:t.allowlistConfig.errorCtaLink,visible:!0,children:n}):(0,U.jsx)(qn,{onClick:()=>{e("LANDING")},visible:!0,children:n})]})]})},$s=Ht.default.div`
|
|
749
749
|
display: flex;
|
|
750
750
|
flex-direction: column;
|
|
751
751
|
align-items: center;
|