@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 9.64 kB
JavaScript
import{isMobile as e,isAndroid as t}from"react-device-detect";import{a as r,b as a,u as n}from"./internal-context-Z-fyxadS.mjs";import{useCallback as o,useContext as i}from"react";import{q as s,u as l}from"./use-export-wallet-_wu5ex5t.mjs";import{e as d,c,g as p,a as u,f as y,d as m,u as E,P as w}from"./privy-context-DrMxzgOR.mjs";import{a as h,u as v}from"./events-context-CI0iqAXA.mjs";import{create as f}from"@privy-io/js-sdk-core";import{g as T}from"./useWallets-BzNCTucF.mjs";import{u as W,W as g}from"./context-DLtU3JQy.mjs";function A(e){return{name:e.metadata?.shortName||e.name||"",universalLink:e.mobile.universal,deepLink:e.mobile.native}}function S(a,n){let o=A(n);if(e&&t&&o.universalLink)return M(o.universalLink,a);if(o.deepLink)return b(o.deepLink,a);if(o.universalLink)return M(o.universalLink,a);throw new r(`Unsupported wallet ${n.id}`)}function D(e,t){let r=A(t);if(r.universalLink)return M(r.universalLink,e)}let U="WALLETCONNECT_DEEPLINK_CHOICE";function x(){try{localStorage.removeItem(U)}catch{}}function I({href:e,name:t}){try{localStorage.setItem(U,JSON.stringify({href:e,name:t}))}catch{}}function _(){try{localStorage.removeItem(U)}catch{}}function k(e){return e.startsWith("http://")||e.startsWith("https://")}function b(e,t){if(k(e))return M(e,t);let r=e;return r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),{redirect:`${r}wc?uri=${encodeURIComponent(t)}`,href:r}}function M(e,t){if(!k(e))return b(e,t);let r=e;return r.endsWith("/")||(r=`${r}/`),{redirect:`${r}wc?uri=${encodeURIComponent(t)}`,href:r}}function L(e,t){window.open(e,t,"noreferrer noopener")}const C=({address:e,nonce:t})=>`${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: ${t}\nIssued At: ${(new Date).toISOString()}\nResources:\n- https://privy.io`,R=Symbol("solana-funding-plugin"),P=Symbol("solana-ledger-plugin"),N=(e,{chainType:t,walletIndex:r}={})=>e?.linkedAccounts.filter((e=>!("wallet"!==e.type||"privy"!==e.walletClientType||void 0!==r&&e.walletIndex!==r||void 0!==t&&e.chainType!==t)))??[],O=async({user:e,accessToken:t,proxy:r,refreshSessionAndUser:a,privy:n,appConfig:o,recoverEmbeddedWallet:i,setUser:l,walletIndex:p,chainType:u,recoveryMethod:y,recoveryPassword:m,recoveryAccessToken:E,idempotencyKey:w,additionalSigners:h})=>{if(0===p)if("user-controlled-server-wallets-only"===o.embeddedWallets.mode)await f(n,{request:{chain_type:u,additional_signers:h?s(h):void 0},headers:w?{"privy-idempotency-key":w}:void 0});else if("ethereum"===u){let a=d(e);a&&await i({address:a.address}),await r.create({accessToken:t,solanaAddress:a?.address,recoveryMethod:y,recoveryPassword:m,recoveryAccessToken:E})}else{if("solana"!==u)throw Error("Invalid input to create wallet");{let a=c(e);a&&await i({address:a.address}),await r.createSolana({accessToken:t,ethereumAddress:a?.address,recoveryMethod:y,recoveryPassword:m,recoveryAccessToken:E})}}else if("user-controlled-server-wallets-only"===o.embeddedWallets.mode)await f(n,{request:{chain_type:u,additional_signers:h?s(h):void 0}});else{let{entropyId:a,entropyIdVerifier:n}=T(e);await i(),await r.addWallet({accessToken:t,entropyId:a,entropyIdVerifier:n,chainType:u,hdWalletIndex:p})}let v=await a(),W=N(v,{chainType:u,walletIndex:p})[0];return l(v),{user:v,account:W}},K=e=>e.reduce(((e,t)=>!e||e.walletIndex<t.walletIndex?t:e),null),$=async({appConfig:e,getAccessToken:t,initializeWalletProxy:n,user:o,privy:i,emitPrivyEvent:s,recoverEmbeddedWallet:l,setModalData:d,openModal:c,setUser:p,options:u,timeoutDuration:y,refreshSessionAndUser:m,chainType:E,idempotencyKey:w,additionalSigners:h})=>{let[v,f]=await Promise.all([n(y),t()]);if(!f||!o)throw s("createWallet","onError",a.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");if(!v&&e.customAuth?.enabled)throw s("createWallet","onError",a.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(h&&"user-controlled-server-wallets-only"!==e.embeddedWallets.mode)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");if(u&&"walletIndex"in u&&"number"==typeof u.walletIndex){if("user-controlled-server-wallets-only"===e.embeddedWallets.mode)throw s("createWallet","onError",a.INVALID_DATA),Error("Invalid input, use `createAdditional` instead of `walletIndex` to create additional wallets.");return B({accessToken:f,appConfig:e,privy:i,emitPrivyEvent:s,openModal:c,proxy:v,refreshSessionAndUser:m,recoverEmbeddedWallet:l,setModalData:d,user:o,walletIndex:u.walletIndex,chainType:E,setUser:p,additionalSigners:h})}let T=u&&"createAdditional"in u&&u.createAdditional,W=N(o,{chainType:E});if(W[0]&&!T)throw s("createWallet","onError",a.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");return B({accessToken:f,appConfig:e,privy:i,emitPrivyEvent:s,openModal:c,proxy:v,recoverEmbeddedWallet:l,setModalData:d,user:o,walletIndex:(K(W)?.walletIndex??-1)+1,chainType:E,refreshSessionAndUser:m,setUser:p,idempotencyKey:w,additionalSigners:h})};let B=async({accessToken:e,appConfig:t,privy:r,emitPrivyEvent:n,proxy:o,refreshSessionAndUser:i,recoverEmbeddedWallet:s,user:l,walletIndex:d,setModalData:c,openModal:u,chainType:y,setUser:m,idempotencyKey:E,additionalSigners:w})=>{if(d<0)throw n("createWallet","onError",a.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${d}) is invalid.`);let h=p(l);if(d>0&&!h)throw n("createWallet","onError",a.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 n("createWallet","onError",a.EMBEDDED_WALLET_CREATE_ERROR),Error("User owned recovery not yet supported for this app.");if(!h&&t.embeddedWallets.requireUserOwnedRecoveryOnCreate)return await j({emitPrivyEvent:n,setModalData:c,openModal:u,chainType:y});let v=N(l,{chainType:y,walletIndex:d})[0];if(v)return{user:l,account:v};if(0===d&&!o)return j({emitPrivyEvent:n,setModalData:c,openModal:u,chainType:y});if(!o)throw n("createWallet","onError",a.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return O({appConfig:t,walletIndex:d,chainType:y,user:l,accessToken:e,proxy:o,refreshSessionAndUser:i,privy:r,recoverEmbeddedWallet:s,setUser:m,idempotencyKey:E,additionalSigners:w})},j=async({emitPrivyEvent:e,setModalData:t,openModal:r,chainType:n})=>new Promise(((o,i)=>{t({createWallet:{onSuccess:({user:t,account:r})=>{e("createWallet","onSuccess",{wallet:r}),o({user:t,account:r})},onFailure:t=>{e("createWallet","onError",a.UNKNOWN_EMBEDDED_WALLET_ERROR),i(t)},callAuthOnSuccessOnClose:!1,shouldCreateEth:"ethereum"===n,shouldCreateSol:"solana"===n}}),r("EmbeddedWalletOnAccountCreateScreen")}));const z=()=>{let e=W(),t=h(),{setModalData:r}=u(),{initializeWalletProxy:o,recoverEmbeddedWallet:i,setUser:s,openModal:l,refreshSessionAndUser:d,privy:c,client:p}=n();return{create:async({chainType:n,options:u,latestUser:y,idempotencyKey:m})=>{let E=y;if(E||(E=await d()),!E)throw t("createWallet","onError",a.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return await $({appConfig:e,privy:c,getAccessToken:()=>p.getAccessToken(),refreshSessionAndUser:d,initializeWalletProxy:o,user:E,emitPrivyEvent:t,recoverEmbeddedWallet:i,setModalData:r,openModal:l,setUser:s,options:u,timeoutDuration:g,chainType:n,idempotencyKey:m,additionalSigners:u?.signers})}}};function q(e){let{create:t}=z();return v("createWallet",e),{createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let{account:r}=await t({chainType:"ethereum",options:e});return r}}}const F=async({emitPrivyEvent:e,getAccessToken:t,initializeWalletProxy:n,refreshSessionAndUser:o,user:i,appConfig:s},{privateKey:l,chainType:d,additionalSigners:c})=>{if(!i)throw e("linkAccount","onError",a.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new r("User must be authenticated before linking an account.");let p="user-controlled-server-wallets-only"===s.embeddedWallets.mode?"tee":"on-device";if(c&&"on-device"===p)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[u,E]=await Promise.all([t(),n(15e3)]);if(!E||!u)throw e("linkAccount","onError",a.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new r("User must be authenticated before linking an account.");let{address:w}=await E.importWallet({privateKey:l,accessToken:u,chainType:d,mode:p,additionalSigners:c}),h=await o(),v="solana"===d?y(h):m(h),f=v?.find((e=>e.address===w));if(!f)throw e("createWallet","onError",a.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to import wallet");return e("createWallet","onSuccess",{wallet:f}),f},H=()=>{let{user:e}=E(),{client:t,refreshSessionAndUser:r,initializeWalletProxy:a}=n(),i=h(),s=W();return{importWallet:o((({privateKey:n,additionalSigners:o})=>F({getAccessToken:()=>t.getAccessToken(),user:e,initializeWalletProxy:a,refreshSessionAndUser:r,emitPrivyEvent:i,appConfig:s},{privateKey:n,chainType:"ethereum",additionalSigners:o})),[e,t,r,a,i,s])}},V=()=>{let{importWallet:e}=H(),{exportWallet:t}=l(),{createWallet:r}=q();return{...i(w),importWallet:e,createWallet:r,exportWallet:t}};export{R as S,D as a,S as b,O as c,x as d,P as e,z as f,q as g,H as h,F as i,L as o,C as p,_ as r,I as s,V as u};