@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 10.2 kB
JavaScript
;var e=require("react-device-detect"),r=require("./internal-context-NWsAL807.js"),t=require("react/jsx-runtime"),n=require("react"),a=require("./get-is-unified-wallet-D4ouXJpi.js"),o=require("./events-context-Di6--rDg.js"),i=require("@privy-io/js-sdk-core"),l=require("./useWallets-BLFNjTwC.js"),s=require("./context-DFq1obBO.js");function d(e){return{name:e.metadata?.shortName||e.name||"",universalLink:e.mobile.universal,deepLink:e.mobile.native}}let c="WALLETCONNECT_DEEPLINK_CHOICE";function u(e){return e.startsWith("http://")||e.startsWith("https://")}function p(e,r){if(u(e))return y(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 y(e,r){if(!u(e))return p(e,r);let t=e;return t.endsWith("/")||(t=`${t}/`),{redirect:`${t}wc?uri=${encodeURIComponent(r)}`,href:t}}let E=/*#__PURE__*/n.createContext({plugins:{current:{}}});const v=Symbol("solana-funding-plugin"),h=Symbol("solana-ledger-plugin"),w=(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)))??[],f=e=>e.reduce(((e,r)=>!e||e.walletIndex<r.walletIndex?r:e),null),m=async({user:e,accessToken:r,proxy:t,refreshSessionAndUser:n,privy:o,appConfig:s,recoverEmbeddedWallet:d,setUser:c,walletIndex:u,chainType:p,recoveryMethod:y,recoveryPassword:E,recoveryAccessToken:v})=>{if(0===u)if("user-controlled-server-wallets-only"===s.embeddedWallets.mode)await i.create(o,{request:{chain_type:p}});else if("ethereum"===p){let n=a.getPrivySolanaWallet(e);n&&await d({address:n.address}),await t.create({accessToken:r,solanaAddress:n?.address,recoveryMethod:y,recoveryPassword:E,recoveryAccessToken:v})}else{if("solana"!==p)throw Error("Invalid input to create wallet");{let n=a.getPrivyEthereumWallet(e);n&&await d({address:n.address}),await t.createSolana({accessToken:r,ethereumAddress:n?.address,recoveryMethod:y,recoveryPassword:E,recoveryAccessToken:v})}}else if("user-controlled-server-wallets-only"===s.embeddedWallets.mode)await i.create(o,{request:{chain_type:p}});else{let{entropyId:n,entropyIdVerifier:a}=l.getEntropyDetailsForUser(e);await d(),await t.addWallet({accessToken:r,entropyId:n,entropyIdVerifier:a,chainType:p,hdWalletIndex:u})}let h=await n(),f=w(h,{chainType:p,walletIndex:u})[0];return c(h),{user:h,account:f}};let W=async({accessToken:e,appConfig:t,privy:n,emitPrivyEvent:o,proxy:i,refreshSessionAndUser:l,recoverEmbeddedWallet:s,user:d,walletIndex:c,setModalData:u,openModal:p,chainType:y,setUser:E})=>{if(c<0)throw o("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${c}) is invalid.`);let v=a.getPrivyPrimaryWallet(d);if(c>0&&!v)throw o("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have an existing embedded wallet to create an additional wallet.");if(t.embeddedWallets.requireUserOwnedRecoveryOnCreate&&"user-controlled-server-wallets-only"===t.embeddedWallets.mode)throw o("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("User owned recovery not yet supported for this app.");if(!v&&t.embeddedWallets.requireUserOwnedRecoveryOnCreate)return await T({emitPrivyEvent:o,setModalData:u,openModal:p,chainType:y});let h=w(d,{chainType:y,walletIndex:c})[0];if(h)return{user:d,account:h};if(0===c&&!i)return T({emitPrivyEvent:o,setModalData:u,openModal:p,chainType:y});if(!i)throw o("createWallet","onError",r.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return m({appConfig:t,walletIndex:c,chainType:y,user:d,accessToken:e,proxy:i,refreshSessionAndUser:l,privy:n,recoverEmbeddedWallet:s,setUser:E})},T=async({emitPrivyEvent:e,setModalData:t,openModal:n,chainType:a})=>new Promise(((o,i)=>{t({createWallet:{onSuccess:({user:r,account:t})=>{e("createWallet","onSuccess",{wallet:t}),o({user:r,account:t})},onFailure:t=>{e("createWallet","onError",r.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),i(t)},callAuthOnSuccessOnClose:!1,shouldCreateEth:"ethereum"===a,shouldCreateSol:"solana"===a}}),n("EmbeddedWalletOnAccountCreateScreen")}));const A=()=>{let e=s.useAppConfig(),t=o.useEmitPrivyEvent(),{setModalData:n}=a.usePrivyModal(),{initializeWalletProxy:i,recoverEmbeddedWallet:l,setUser:d,openModal:c,refreshSessionAndUser:u,privy:p,client:y}=r.usePrivyInternal();return{create:async({chainType:a,options:o,latestUser:E})=>{let v=E;if(v||(v=await u()),!v)throw t("createWallet","onError",r.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return await(async({appConfig:e,getAccessToken:t,initializeWalletProxy:n,user:a,privy:o,emitPrivyEvent:i,recoverEmbeddedWallet:l,setModalData:s,openModal:d,setUser:c,options:u,timeoutDuration:p,refreshSessionAndUser:y,chainType:E})=>{let[v,h]=await Promise.all([n(p),t()]);if(!h||!a)throw i("createWallet","onError",r.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");if(!v&&e.customAuth?.enabled)throw i("createWallet","onError",r.PrivyErrorCode.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",r.PrivyErrorCode.INVALID_DATA),Error("Invalid input, use `createAdditional` instead of `walletIndex` to create additional wallets.");return W({accessToken:h,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:v,refreshSessionAndUser:y,recoverEmbeddedWallet:l,setModalData:s,user:a,walletIndex:u.walletIndex,chainType:E,setUser:c})}let m=u&&"createAdditional"in u&&u.createAdditional,T=w(a,{chainType:E});if(T[0]&&!m)throw i("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");return W({accessToken:h,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:v,recoverEmbeddedWallet:l,setModalData:s,user:a,walletIndex:(f(T)?.walletIndex??-1)+1,chainType:E,refreshSessionAndUser:y,setUser:c})})({appConfig:e,privy:p,getAccessToken:()=>y.getAccessToken(),refreshSessionAndUser:u,initializeWalletProxy:i,user:v,emitPrivyEvent:t,recoverEmbeddedWallet:l,setModalData:n,openModal:c,setUser:d,options:o,timeoutDuration:s.WALLET_PROXY_TIMEOUT,chainType:a})}}};function P(e){let{create:r}=A();return o.usePrivyEventSubscription("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 x=async({emitPrivyEvent:e,getAccessToken:t,initializeWalletProxy:n,refreshSessionAndUser:o,user:i,appConfig:l},{privateKey:s,chainType:d,additionalSigners:c})=>{if(!i)throw e("linkAccount","onError",r.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new r.PrivyClientError("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.PrivyClientError("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([t(),n(15e3)]);if(!y||!p)throw e("linkAccount","onError",r.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new r.PrivyClientError("User must be authenticated before linking an account.");let{address:E}=await y.importWallet({privateKey:s,accessToken:p,chainType:d,mode:u,additionalSigners:c}),v=await o(),h="solana"===d?a.getImportedPrivySolanaWallets(v):a.getImportedPrivyEthereumWallets(v),w=h?.find((e=>e.address===E));if(!w)throw e("createWallet","onError",r.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to import wallet");return e("createWallet","onSuccess",{wallet:w}),w},g=()=>{let{user:e}=a.usePrivyContext(),{client:t,refreshSessionAndUser:i,initializeWalletProxy:l}=r.usePrivyInternal(),d=o.useEmitPrivyEvent(),c=s.useAppConfig();return{importWallet:n.useCallback((({privateKey:r,additionalSigners:n})=>x({getAccessToken:()=>t.getAccessToken(),user:e,initializeWalletProxy:l,refreshSessionAndUser:i,emitPrivyEvent:d,appConfig:c},{privateKey:r,chainType:"ethereum",additionalSigners:n})),[e,t,i,l,d,c])}};exports.PrivyPluginProvider=({children:e})=>{let r=n.useRef({});/*#__PURE__*/return t.jsx(E.Provider,{value:{plugins:r},children:e})},exports.SOLANA_FUNDING_PLUGIN_ID=v,exports.SOLANA_LEDGER_PLUGIN_ID=h,exports.buildTargetUrl=function(t,n){let a=d(n);if(e.isMobile&&a.universalLink)return y(a.universalLink,t);if(a.deepLink)return p(a.deepLink,t);if(a.universalLink)return y(a.universalLink,t);throw new r.PrivyClientError(`Unsupported wallet ${n.id}`)},exports.buildUniversalFallbackUrl=function(e,r){let t=d(r);if(t.universalLink)return y(t.universalLink,e)},exports.createWalletAtIndex=m,exports.deleteWalletConnectDeepLink=function(){try{localStorage.removeItem(c)}catch{}},exports.importWallet=x,exports.openHref=function(e,r){window.open(e,r,"noreferrer noopener")},exports.prepareSiwsMessageWithNonce=({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`,exports.removeWalletConnectDeepLink=function(){try{localStorage.removeItem(c)}catch{}},exports.setWalletConnectDeepLink=function({href:e,name:r}){try{localStorage.setItem(c,JSON.stringify({href:e,name:r}))}catch{}},exports.useCreateWallet=P,exports.useCreateWalletInternal=A,exports.useImportWallet=g,exports.usePlugins=()=>{let{plugins:e}=n.useContext(E);return n.useCallback((r=>e.current[r]),[e])},exports.usePrivy=()=>{let{importWallet:e}=g(),{createWallet:r}=P();return{...n.useContext(a.PrivyContext),importWallet:e,createWallet:r}},exports.useRegisterPlugin=(...e)=>{let{plugins:r}=n.useContext(E);n.useEffect((()=>{for(let t of e)r.current[t.id]=t;return()=>{for(let t of e)delete r.current[t.id]}}),[r])};