@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 10.5 kB
JavaScript
;var e=require("react-device-detect"),r=require("./internal-context-BJv4f_bO.js"),t=require("react"),n=require("./use-export-wallet-_EIyxyle.js"),a=require("./privy-context-CrM9_s6G.js"),o=require("./events-context-Di6--rDg.js"),i=require("@privy-io/js-sdk-core"),l=require("./useWallets-dikDynAG.js"),s=require("./context-Cg3IEi80.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 p(e){return e.startsWith("http://")||e.startsWith("https://")}function u(e,r){if(p(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(!p(e))return u(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:o,privy:s,appConfig:d,recoverEmbeddedWallet:c,setUser:p,walletIndex:u,chainType:y,recoveryMethod:E,recoveryPassword:v,recoveryAccessToken:h,idempotencyKey:m,additionalSigners:f})=>{if(0===u)if("user-controlled-server-wallets-only"===d.embeddedWallets.mode)await i.create(s,{request:{chain_type:y,additional_signers:f?n.parseAdditionalSigners(f):void 0},headers:m?{"privy-idempotency-key":m}:void 0});else if("ethereum"===y){let n=a.getPrivySolanaWallet(e);n&&await c({address:n.address}),await t.create({accessToken:r,solanaAddress:n?.address,recoveryMethod:E,recoveryPassword:v,recoveryAccessToken:h})}else{if("solana"!==y)throw Error("Invalid input to create wallet");{let n=a.getPrivyEthereumWallet(e);n&&await c({address:n.address}),await t.createSolana({accessToken:r,ethereumAddress:n?.address,recoveryMethod:E,recoveryPassword:v,recoveryAccessToken:h})}}else if("user-controlled-server-wallets-only"===d.embeddedWallets.mode)await i.create(s,{request:{chain_type:y,additional_signers:f?n.parseAdditionalSigners(f):void 0}});else{let{entropyId:n,entropyIdVerifier:a}=l.getEntropyDetailsForUser(e);await c(),await t.addWallet({accessToken:r,entropyId:n,entropyIdVerifier:a,chainType:y,hdWalletIndex:u})}let W=await o(),T=w(W,{chainType:y,walletIndex:u})[0];return p(W),{user:W,account:T}},m=e=>e.reduce(((e,r)=>!e||e.walletIndex<r.walletIndex?r:e),null),f=async({appConfig:e,getAccessToken:t,initializeWalletProxy:n,user:a,privy:o,emitPrivyEvent:i,recoverEmbeddedWallet:l,setModalData:s,openModal:d,setUser:c,options:p,timeoutDuration:u,refreshSessionAndUser:y,chainType:E,idempotencyKey:v,additionalSigners:h})=>{let[f,T]=await Promise.all([n(u),t()]);if(!T||!a)throw i("createWallet","onError",r.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");if(!f&&e.customAuth?.enabled)throw i("createWallet","onError",r.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(h&&"user-controlled-server-wallets-only"!==e.embeddedWallets.mode)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");if(p&&"walletIndex"in p&&"number"==typeof p.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:T,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:f,refreshSessionAndUser:y,recoverEmbeddedWallet:l,setModalData:s,user:a,walletIndex:p.walletIndex,chainType:E,setUser:c,additionalSigners:h})}let A=p&&"createAdditional"in p&&p.createAdditional,g=w(a,{chainType:E});if(g[0]&&!A)throw i("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");return W({accessToken:T,appConfig:e,privy:o,emitPrivyEvent:i,openModal:d,proxy:f,recoverEmbeddedWallet:l,setModalData:s,user:a,walletIndex:(m(g)?.walletIndex??-1)+1,chainType:E,refreshSessionAndUser:y,setUser:c,idempotencyKey:v,additionalSigners:h})};let W=async({accessToken:e,appConfig:t,privy:n,emitPrivyEvent:o,proxy:i,refreshSessionAndUser:l,recoverEmbeddedWallet:s,user:d,walletIndex:c,setModalData:p,openModal:u,chainType:y,setUser:E,idempotencyKey:v,additionalSigners:m})=>{if(c<0)throw o("createWallet","onError",r.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${c}) is invalid.`);let f=a.getPrivyPrimaryWallet(d);if(c>0&&!f)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(!f&&t.embeddedWallets.requireUserOwnedRecoveryOnCreate)return await T({emitPrivyEvent:o,setModalData:p,openModal:u,chainType:y});let W=w(d,{chainType:y,walletIndex:c})[0];if(W)return{user:d,account:W};if(0===c&&!i)return T({emitPrivyEvent:o,setModalData:p,openModal:u,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,additionalSigners:m})},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:p,privy:u,client:y}=r.usePrivyInternal();return{create:async({chainType:a,options:o,latestUser:E,idempotencyKey:v})=>{let w=E;if(w||(w=await p()),!w)throw t("createWallet","onError",r.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return await f({appConfig:e,privy:u,getAccessToken:()=>y.getAccessToken(),refreshSessionAndUser:p,initializeWalletProxy:i,user:w,emitPrivyEvent:t,recoverEmbeddedWallet:l,setModalData:n,openModal:c,setUser:d,options:o,timeoutDuration:s.WALLET_PROXY_TIMEOUT,chainType:a,idempotencyKey:v,additionalSigners:o?.signers})}}};function g(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 p="user-controlled-server-wallets-only"===l.embeddedWallets.mode?"tee":"on-device";if(c&&"on-device"===p)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[u,y]=await Promise.all([t(),n(15e3)]);if(!y||!u)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:u,chainType:d,mode:p,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 u(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=g,exports.useCreateWalletInternal=A,exports.useImportWallet=P,exports.usePrivy=()=>{let{importWallet:e}=P(),{exportWallet:r}=n.useExportWallet(),{createWallet:o}=g();return{...t.useContext(a.PrivyContext),importWallet:e,createWallet:o,exportWallet:r}};