@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 9.98 kB
JavaScript
;var e=require("react-device-detect"),r=require("./internal-context-BJv4f_bO.js"),t=require("react"),n=require("./use-export-wallet-B5ujV5Nk.js"),a=require("./get-is-unified-wallet-UpdjHxOV.js"),o=require("./events-context-Di6--rDg.js"),i=require("@privy-io/js-sdk-core"),l=require("./useWallets-CKAypPZB.js"),s=require("./context-D-ZJYjUg.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}}const E=Symbol("solana-funding-plugin"),v=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)))??[],h=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,idempotencyKey:h})=>{if(0===u)if("user-controlled-server-wallets-only"===s.embeddedWallets.mode)await i.create(o,{request:{chain_type:p},headers:h?{"privy-idempotency-key":h}:void 0});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 m=await n(),f=w(m,{chainType:p,walletIndex:u})[0];return c(m),{user:m,account:f}},m=e=>e.reduce(((e,r)=>!e||e.walletIndex<r.walletIndex?r:e),null);let f=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,idempotencyKey:v})=>{if(c<0)throw o("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${c}) is invalid.`);let m=a.getPrivyPrimaryWallet(d);if(c>0&&!m)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(!m&&t.embeddedWallets.requireUserOwnedRecoveryOnCreate)return await W({emitPrivyEvent:o,setModalData:u,openModal:p,chainType:y});let f=w(d,{chainType:y,walletIndex:c})[0];if(f)return{user:d,account:f};if(0===c&&!i)return W({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 h({appConfig:t,walletIndex:c,chainType:y,user:d,accessToken:e,proxy:i,refreshSessionAndUser:l,privy:n,recoverEmbeddedWallet:s,setUser:E,idempotencyKey:v})},W=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 T=()=>{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,idempotencyKey:v})=>{let h=E;if(h||(h=await u()),!h)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,idempotencyKey:v})=>{let[h,W]=await Promise.all([n(p),t()]);if(!W||!a)throw i("createWallet","onError",r.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");if(!h&&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 f({accessToken:W,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:h,refreshSessionAndUser:y,recoverEmbeddedWallet:l,setModalData:s,user:a,walletIndex:u.walletIndex,chainType:E,setUser:c})}let T=u&&"createAdditional"in u&&u.createAdditional,A=w(a,{chainType:E});if(A[0]&&!T)throw i("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");return f({accessToken:W,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:h,recoverEmbeddedWallet:l,setModalData:s,user:a,walletIndex:(m(A)?.walletIndex??-1)+1,chainType:E,refreshSessionAndUser:y,setUser:c,idempotencyKey:v})})({appConfig:e,privy:p,getAccessToken:()=>y.getAccessToken(),refreshSessionAndUser:u,initializeWalletProxy:i,user:h,emitPrivyEvent:t,recoverEmbeddedWallet:l,setModalData:n,openModal:c,setUser:d,options:o,timeoutDuration:s.WALLET_PROXY_TIMEOUT,chainType:a,idempotencyKey:v})}}};function A(e){let{create:r}=T();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(),w="solana"===d?a.getImportedPrivySolanaWallets(v):a.getImportedPrivyEthereumWallets(v),h=w?.find((e=>e.address===E));if(!h)throw e("createWallet","onError",r.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to import wallet");return e("createWallet","onSuccess",{wallet:h}),h},P=()=>{let{user:e}=a.usePrivyContext(),{client:n,refreshSessionAndUser:i,initializeWalletProxy:l}=r.usePrivyInternal(),d=o.useEmitPrivyEvent(),c=s.useAppConfig();return{importWallet:t.useCallback((({privateKey:r,additionalSigners:t})=>x({getAccessToken:()=>n.getAccessToken(),user:e,initializeWalletProxy:l,refreshSessionAndUser:i,emitPrivyEvent:d,appConfig:c},{privateKey:r,chainType:"ethereum",additionalSigners:t})),[e,n,i,l,d,c])}};exports.SOLANA_FUNDING_PLUGIN_ID=E,exports.SOLANA_LEDGER_PLUGIN_ID=v,exports.buildTargetUrl=function(t,n){let a=d(n);if(e.isMobile&&e.isAndroid&&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=h,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=A,exports.useCreateWalletInternal=T,exports.useImportWallet=P,exports.usePrivy=()=>{let{importWallet:e}=P(),{exportWallet:r}=n.useExportWallet(),{createWallet:o}=A();return{...t.useContext(a.PrivyContext),importWallet:e,createWallet:o,exportWallet:r}};