@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 9.34 kB
JavaScript
import{isMobile as e}from"react-device-detect";import{a as r,b as t,u as a}from"./internal-context-e-Eni5bG.mjs";import{jsx as n}from"react/jsx-runtime";import{useContext as o,createContext as i,useEffect as l,useRef as s,useCallback as d}from"react";import{c,b as u,g as p,a as y,j as E,f as m,u as w,P as f}from"./get-is-unified-wallet-DvKS5IUO.mjs";import{a as h,u as v}from"./events-context-CI0iqAXA.mjs";import{create as T}from"@privy-io/js-sdk-core";import{g as W}from"./useWallets-D0lpBS44.mjs";import{u as A,W as g}from"./context-Bycd1SKV.mjs";function D(e){return{name:e.metadata?.shortName||e.name||"",universalLink:e.mobile.universal,deepLink:e.mobile.native}}function U(t,a){let n=D(a);if(e&&n.universalLink)return L(n.universalLink,t);if(n.deepLink)return b(n.deepLink,t);if(n.universalLink)return L(n.universalLink,t);throw new r(`Unsupported wallet ${a.id}`)}function I(e,r){let t=D(r);if(t.universalLink)return L(t.universalLink,e)}let S="WALLETCONNECT_DEEPLINK_CHOICE";function x(){try{localStorage.removeItem(S)}catch{}}function k({href:e,name:r}){try{localStorage.setItem(S,JSON.stringify({href:e,name:r}))}catch{}}function _(){try{localStorage.removeItem(S)}catch{}}function M(e){return e.startsWith("http://")||e.startsWith("https://")}function b(e,r){if(M(e))return L(e,r);let t=e;return t.includes("://")||(t=e.replaceAll("/","").replaceAll(":",""),t=`${t}://`),t.endsWith("/")||(t=`${t}/`),{redirect:`${t}wc?uri=${encodeURIComponent(r)}`,href:t}}function L(e,r){if(!M(e))return b(e,r);let t=e;return t.endsWith("/")||(t=`${t}/`),{redirect:`${t}wc?uri=${encodeURIComponent(r)}`,href:t}}function C(e,r){window.open(e,r,"noreferrer noopener")}const P=({address:e,nonce:r})=>`${window.location.host} wants you to sign in with your Solana account:\n${e}\n\n${`You are proving you own ${e}.`}\n\nURI: ${window.location.origin}\nVersion: 1\nChain ID: mainnet\nNonce: ${r}\nIssued At: ${(new Date).toISOString()}\nResources:\n- https://privy.io`;let R=/*#__PURE__*/i({plugins:{current:{}}});const N=({children:e})=>{let r=s({});/*#__PURE__*/return n(R.Provider,{value:{plugins:r},children:e})},O=(...e)=>{let{plugins:r}=o(R);l((()=>{for(let t of e)r.current[t.id]=t;return()=>{for(let t of e)delete r.current[t.id]}}),[r])},$=()=>{let{plugins:e}=o(R);return d((r=>e.current[r]),[e])},B=Symbol("solana-funding-plugin"),j=Symbol("solana-ledger-plugin"),K=(e,{chainType:r,walletIndex:t}={})=>e?.linkedAccounts.filter((e=>!("wallet"!==e.type||"privy"!==e.walletClientType||void 0!==t&&e.walletIndex!==t||void 0!==r&&e.chainType!==r)))??[],z=e=>e.reduce(((e,r)=>!e||e.walletIndex<r.walletIndex?r:e),null),F=async({user:e,accessToken:r,proxy:t,refreshSessionAndUser:a,privy:n,appConfig:o,recoverEmbeddedWallet:i,setUser:l,walletIndex:s,chainType:d,recoveryMethod:p,recoveryPassword:y,recoveryAccessToken:E})=>{if(0===s)if("user-controlled-server-wallets-only"===o.embeddedWallets.mode)await T(n,{request:{chain_type:d}});else if("ethereum"===d){let a=c(e);a&&await i({address:a.address}),await t.create({accessToken:r,solanaAddress:a?.address,recoveryMethod:p,recoveryPassword:y,recoveryAccessToken:E})}else{if("solana"!==d)throw Error("Invalid input to create wallet");{let a=u(e);a&&await i({address:a.address}),await t.createSolana({accessToken:r,ethereumAddress:a?.address,recoveryMethod:p,recoveryPassword:y,recoveryAccessToken:E})}}else if("user-controlled-server-wallets-only"===o.embeddedWallets.mode)await T(n,{request:{chain_type:d}});else{let{entropyId:a,entropyIdVerifier:n}=W(e);await i(),await t.addWallet({accessToken:r,entropyId:a,entropyIdVerifier:n,chainType:d,hdWalletIndex:s})}let m=await a(),w=K(m,{chainType:d,walletIndex:s})[0];return l(m),{user:m,account:w}};let H=async({accessToken:e,appConfig:r,privy:a,emitPrivyEvent:n,proxy:o,refreshSessionAndUser:i,recoverEmbeddedWallet:l,user:s,walletIndex:d,setModalData:c,openModal:u,chainType:y,setUser:E})=>{if(d<0)throw n("createWallet","onError",t.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${d}) is invalid.`);let m=p(s);if(d>0&&!m)throw n("createWallet","onError",t.EMBEDDED_WALLET_NOT_FOUND),Error("Must have an existing embedded wallet to create an additional wallet.");if(r.embeddedWallets.requireUserOwnedRecoveryOnCreate&&"user-controlled-server-wallets-only"===r.embeddedWallets.mode)throw n("createWallet","onError",t.EMBEDDED_WALLET_CREATE_ERROR),Error("User owned recovery not yet supported for this app.");if(!m&&r.embeddedWallets.requireUserOwnedRecoveryOnCreate)return await q({emitPrivyEvent:n,setModalData:c,openModal:u,chainType:y});let w=K(s,{chainType:y,walletIndex:d})[0];if(w)return{user:s,account:w};if(0===d&&!o)return q({emitPrivyEvent:n,setModalData:c,openModal:u,chainType:y});if(!o)throw n("createWallet","onError",t.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return F({appConfig:r,walletIndex:d,chainType:y,user:s,accessToken:e,proxy:o,refreshSessionAndUser:i,privy:a,recoverEmbeddedWallet:l,setUser:E})},q=async({emitPrivyEvent:e,setModalData:r,openModal:a,chainType:n})=>new Promise(((o,i)=>{r({createWallet:{onSuccess:({user:r,account:t})=>{e("createWallet","onSuccess",{wallet:t}),o({user:r,account:t})},onFailure:r=>{e("createWallet","onError",t.UNKNOWN_EMBEDDED_WALLET_ERROR),i(r)},callAuthOnSuccessOnClose:!1,shouldCreateEth:"ethereum"===n,shouldCreateSol:"solana"===n}}),a("EmbeddedWalletOnAccountCreateScreen")}));const V=()=>{let e=A(),r=h(),{setModalData:n}=y(),{initializeWalletProxy:o,recoverEmbeddedWallet:i,setUser:l,openModal:s,refreshSessionAndUser:d,privy:c,client:u}=a();return{create:async({chainType:a,options:p,latestUser:y})=>{let E=y;if(E||(E=await d()),!E)throw r("createWallet","onError",t.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return await(async({appConfig:e,getAccessToken:r,initializeWalletProxy:a,user:n,privy:o,emitPrivyEvent:i,recoverEmbeddedWallet:l,setModalData:s,openModal:d,setUser:c,options:u,timeoutDuration:p,refreshSessionAndUser:y,chainType:E})=>{let[m,w]=await Promise.all([a(p),r()]);if(!w||!n)throw i("createWallet","onError",t.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");if(!m&&e.customAuth?.enabled)throw i("createWallet","onError",t.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(u&&"walletIndex"in u&&"number"==typeof u.walletIndex){if("user-controlled-server-wallets-only"===e.embeddedWallets.mode)throw i("createWallet","onError",t.INVALID_DATA),Error("Invalid input, use `createAdditional` instead of `walletIndex` to create additional wallets.");return H({accessToken:w,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:m,refreshSessionAndUser:y,recoverEmbeddedWallet:l,setModalData:s,user:n,walletIndex:u.walletIndex,chainType:E,setUser:c})}let f=u&&"createAdditional"in u&&u.createAdditional,h=K(n,{chainType:E});if(h[0]&&!f)throw i("createWallet","onError",t.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");return H({accessToken:w,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:m,recoverEmbeddedWallet:l,setModalData:s,user:n,walletIndex:(z(h)?.walletIndex??-1)+1,chainType:E,refreshSessionAndUser:y,setUser:c})})({appConfig:e,privy:c,getAccessToken:()=>u.getAccessToken(),refreshSessionAndUser:d,initializeWalletProxy:o,user:E,emitPrivyEvent:r,recoverEmbeddedWallet:i,setModalData:n,openModal:s,setUser:l,options:p,timeoutDuration:g,chainType:a})}}};function Y(e){let{create:r}=V();return v("createWallet",e),{createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let{account:t}=await r({chainType:"ethereum",options:e});return t}}}const J=async({emitPrivyEvent:e,getAccessToken:a,initializeWalletProxy:n,refreshSessionAndUser:o,user:i,appConfig:l},{privateKey:s,chainType:d,additionalSigners:c})=>{if(!i)throw e("linkAccount","onError",t.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new r("User must be authenticated before linking an account.");let u="user-controlled-server-wallets-only"===l.embeddedWallets.mode?"tee":"on-device";if(c&&"on-device"===u)throw new r("Specifying additionalSigners is only supported for TEE execution and this app uses On-device execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let[p,y]=await Promise.all([a(),n(15e3)]);if(!y||!p)throw e("linkAccount","onError",t.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new r("User must be authenticated before linking an account.");let{address:w}=await y.importWallet({privateKey:s,accessToken:p,chainType:d,mode:u,additionalSigners:c}),f=await o(),h="solana"===d?E(f):m(f),v=h?.find((e=>e.address===w));if(!v)throw e("createWallet","onError",t.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to import wallet");return e("createWallet","onSuccess",{wallet:v}),v},X=()=>{let{user:e}=w(),{client:r,refreshSessionAndUser:t,initializeWalletProxy:n}=a(),o=h(),i=A();return{importWallet:d((({privateKey:a,additionalSigners:l})=>J({getAccessToken:()=>r.getAccessToken(),user:e,initializeWalletProxy:n,refreshSessionAndUser:t,emitPrivyEvent:o,appConfig:i},{privateKey:a,chainType:"ethereum",additionalSigners:l})),[e,r,t,n,o,i])}},G=()=>{let{importWallet:e}=X(),{createWallet:r}=Y();return{...o(f),importWallet:e,createWallet:r}};export{N as P,B as S,I as a,U as b,$ as c,x as d,j as e,V as f,Y as g,X as h,J as i,O as j,F as k,C as o,P as p,_ as r,k as s,G as u};