@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 10.8 kB
JavaScript
import{useRef as e,useState as t,useCallback as n}from"react";import{http as r,createPublicClient as a}from"viem";import{a as i,u as s,b as o,d as l}from"./get-is-unified-wallet-DvKS5IUO.mjs";import{u as c}from"./context-Bycd1SKV.mjs";import{u as d,a as u}from"./internal-context-e-Eni5bG.mjs";import{u as m,g as p}from"./useWallets-D0lpBS44.mjs";import{a as y}from"./getPublicClient-A9RSftUZ.mjs";import{a as g}from"./getEmbeddedConnectedWallet-CM6cDQCS.mjs";import{createSmartAccountClient as f}from"permissionless";import{toThirdwebSmartAccount as h,toLightSmartAccount as w,toBiconomySmartAccount as P,toKernelSmartAccount as I,toSafeSmartAccount as W}from"permissionless/accounts";import{createPimlicoClient as v}from"permissionless/clients/pimlico";import{entryPoint07Address as F,entryPoint06Address as x,toCoinbaseSmartAccount as S}from"viem/account-abstraction";import{THIRDWEB as C,COINBASE_SMART_WALLET as G,LIGHT_ACCOUNT as T,BICONOMY as b,KERNEL as U,SAFE as M}from"@privy-io/js-sdk-core";let O={address:x,version:"0.6"},V={address:F,version:"0.7"},A=({owner:e,smartWalletType:t,smartWalletVersion:n,publicClient:r})=>{switch(t){case M:return W({client:r,entryPoint:V,owners:[e],version:"1.4.1"});case U:return I({client:r,version:"0.3.1",entryPoint:V,useMetaFactory:"optional",owners:[e]});case b:return P({client:r,owners:[e],entryPoint:O});case T:return w({client:r,entryPoint:O,owner:e,version:"1.1.0"});case G:return async function({client:e,owner:t,version:n}){let[r]=await t.request({method:"eth_accounts"});if(!r)throw Error("Unable to request embedded owner for eth_accounts");return await S({client:e,owners:[{type:"local",source:"privy",address:r,sign:async({hash:e})=>await t.request({method:"secp256k1_sign",params:[e]})}],version:n})}({client:r,owner:e,version:n??"1"});case C:return h({client:r,entryPoint:V,owner:e});default:throw Error(`Invalid smart account type: ${t}.`)}};const D=({calls:e,chain:t,maxPriorityFeePerGas:n,maxFeePerGas:r,nonce:a})=>e.map((e=>({to:e.to||void 0,data:e.data,value:e.value,chainId:t.id,nonce:a,maxFeePerGas:r,maxPriorityFeePerGas:n}))),E=async({chain:e,paymasterContext:t,account:n,signer:i,user:s,smartWalletsConfig:o,rpcConfig:l,privyAppId:c})=>{if(!(o?.enabled&&s&&n&&i))return;let d=o?.configuredNetworks.find((t=>t.chainId===`eip155:${e.id}`));if(!d)throw new u(`The chain ${e.name} (eip155:${e.id}) must be configured in the smart wallet configuration in your dashboard`);let m=s.smartWallet?s.smartWallet.smartWalletType:o.smartWalletType,p=s.smartWallet?s.smartWallet.smartWalletVersion:o.smartWalletVersion,g=y(e,l,c),h=a({chain:e,transport:r(g)}),w=t??d.paymasterContext,P=await(async({owner:e,smartWalletType:t,smartWalletVersion:n,chain:a,publicClient:i,bundlerUrl:s,paymasterUrl:o,paymasterContext:l})=>{let c=await A({owner:e,smartWalletType:t,publicClient:i,smartWalletVersion:n}),d=v({transport:r(s),entryPoint:c.entryPoint}),u=o?v({transport:r(o),entryPoint:c.entryPoint}):void 0;return f({account:c,chain:a,paymaster:u,paymasterContext:l,bundlerTransport:r(s),userOperation:{estimateFeesPerGas:async()=>{if(["public.pimlico.io","api.pimlico.io"].some((e=>s.includes(e))))return await d.getUserOperationGasPrice().then((e=>e.fast));if(["rpc.zerodev.app"].some((e=>s.includes(e))))return(await d.request({method:"zd_getUserOperationGasPrice",params:[]})).fast;if(["g.alchemy.com"].some((e=>s.includes(e)))){let[e,t]=await Promise.all([i.getBlock({blockTag:"latest"}),d.request({method:"rundler_maxPriorityFeePerGas",params:[]})]);if(!e.baseFeePerGas||!t)throw Error("Failed to get block or maxPriorityFeePerGasEstimate");return{maxFeePerGas:150n*e.baseFeePerGas/100n+BigInt(t.toString()),maxPriorityFeePerGas:BigInt(t.toString())}}{let e=await i.estimateFeesPerGas(),t=s.includes("api.developer.coinbase.com")?175n:150n;return{...e,maxFeePerGas:e.maxFeePerGas*t/100n,maxPriorityFeePerGas:e.maxPriorityFeePerGas*t/100n}}}}})})({owner:i,smartWalletType:m,smartWalletVersion:p,chain:e,publicClient:h,paymasterContext:w,...d});if(!P)throw new u(`Failed to create smart wallet client for chain ${e.name} (eip155:${e.id})`);return P},q=({clientConfig:r,smartWalletsConfig:a})=>{let{hideWalletUIs:y,openPrivyModal:f,appId:h,isHeadlessSigning:w}=d(),P=c(),{setModalData:I}=i(),{user:W}=s(),{chains:v}=c(),{chainId:F,clients:x,setChainId:S,chainIdState:C}=(()=>{let n=e(),[r,a]=t();return{clients:e({}),setChainId:e=>{n.current=e,a(e)},chainId:n,chainIdState:r}})(),G=v.find((e=>e.id===C)),{wallets:T}=m(),b=o(W),U=g(T,b?.address),M=!!b&&l(b),O=n((async()=>F.current),[F]),V=n((async({id:e})=>{if(!x.current[e]){let t=await E({chain:v.find((t=>t.id===e)),account:b,signer:await(U?.getEthereumProvider()),user:W,paymasterContext:r?.paymasterContext,smartWalletsConfig:a,rpcConfig:P.rpcConfig,privyAppId:h});t&&(x.current[e]=t)}S(e)}),[v,r,T,W,a]);return{wrapSmartAccountClient:e=>{x.current[e.chain.id]=e,C||S(e.chain.id);return{...e,sendTransaction:async(e,t)=>{let n=x.current[F.current];if(!n)throw new u(`Smart wallet client for chain (eip155:${F.current}) not found`);if(delete e.account,w({showWalletUIs:t?.uiOptions?.showWalletUIs}))return y.current=!0,await n.sendTransaction(e).finally((()=>y.current=!1));let r=[];"calls"in e&&void 0!==e.calls?r=[...e.calls]:"to"in e&&(r=[{to:e.to,value:e.value||BigInt(0),data:e.data||"0x"}]);let a=async()=>{let{paymasterAndData:t,paymasterData:a,maxFeePerGas:i,maxPriorityFeePerGas:s}=await n.prepareUserOperation({calls:r,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce?BigInt(e.nonce):void 0});return 0===Number(i)&&0===Number(s)||Number(t??a??0)>0};return new Promise((async(i,s)=>{y.current=!0;let{entropyId:o,entropyIdVerifier:l}=p(W);I({connectWallet:{recoveryMethod:b.recoveryMethod,connectingWalletAddress:b.address,isUnifiedWallet:M,entropyId:o,entropyIdVerifier:l,onCompleteNavigateTo:"SendTransactionScreen",onFailure:()=>{}},sendTransaction:{transactionRequests:D({calls:r,chain:n.chain,maxPriorityFeePerGas:e.maxPriorityFeePerGas,maxFeePerGas:e.maxFeePerGas,nonce:e.nonce?BigInt(e.nonce):void 0}),transactingWalletIndex:0,transactingWalletAddress:n.account.address,entropyId:o,entropyIdVerifier:l,getIsSponsored:a,signOnly:!1,onConfirm:()=>n.sendTransaction(e),onSuccess:e=>i(e.hash),onFailure:s,uiOptions:t?.uiOptions??{}}}),f("EmbeddedWalletConnectingScreen")})).finally((()=>{y.current=!1}))},signMessage:async(e,t)=>{let n=x.current[F.current];if(!n)throw new u(`Smart wallet client for chain (eip155:${F.current}) not found`);return w({showWalletUIs:t?.uiOptions?.showWalletUIs})?(y.current=!0,await n.signMessage(e).finally((()=>y.current=!1))):new Promise((async(r,a)=>{let{entropyId:i,entropyIdVerifier:s}=p(W);y.current=!0,I({connectWallet:{recoveryMethod:b.recoveryMethod,connectingWalletAddress:b.address,isUnifiedWallet:M,entropyId:i,entropyIdVerifier:s,onCompleteNavigateTo:"SignRequestScreen",onFailure:()=>{}},signMessage:{method:"personal_sign",data:"string"==typeof e.message?e.message:e.message.raw.toString(),confirmAndSign:()=>n.signMessage(e),onSuccess:e=>r(e),onFailure:a,uiOptions:t?.uiOptions??{}}}),f("EmbeddedWalletConnectingScreen")})).finally((()=>{y.current=!1}))},signTypedData:async(e,t)=>{let n=x.current[F.current];if(!n)throw new u(`Smart wallet client for chain (eip155:${F.current}) not found`);return delete e.account,w({showWalletUIs:t?.uiOptions?.showWalletUIs})?(y.current=!0,await n.signTypedData(e).finally((()=>y.current=!1))):new Promise((async(r,a)=>{y.current=!0;let{entropyId:i,entropyIdVerifier:s}=p(W);I({connectWallet:{recoveryMethod:b.recoveryMethod,connectingWalletAddress:b.address,isUnifiedWallet:M,entropyId:i,entropyIdVerifier:s,onCompleteNavigateTo:"SignRequestScreen",onFailure:()=>{}},signMessage:{method:"eth_signTypedData_v4",data:e,confirmAndSign:()=>n.signTypedData(e),onSuccess:e=>r(e),onFailure:a,uiOptions:t?.uiOptions??{}}}),f("EmbeddedWalletConnectingScreen")})).finally((()=>{y.current=!1}))},getChainId:O,chain:G,switchChain:V}}}},N=()=>{let{hideWalletUIs:e,openPrivyModal:t,isHeadlessSigning:n}=d(),{setModalData:r}=i(),{user:a}=s(),c=o(a),u=!!c&&l(c);return{wrapSmartAccountClientWithUIs:i=>({...i,sendTransaction:async(s,o)=>{if(n({showWalletUIs:o?.uiOptions?.showWalletUIs}))return e.current=!0,await i.sendTransaction(s).finally((()=>e.current=!1));let l=[];"calls"in s&&void 0!==s.calls?l=[...s.calls]:"to"in s&&(l=[{to:s.to,value:s.value||BigInt(0),data:s.data||"0x"}]);let d=async()=>{if(!i.paymaster)return!1;let{paymasterData:e,paymasterAndData:t}=await i.prepareUserOperation({calls:l,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nonce:s.nonce?BigInt(s.nonce):void 0});return Number(t??e??0)>0};return new Promise((async(n,m)=>{e.current=!0;let{entropyId:y,entropyIdVerifier:g}=p(a);r({connectWallet:{recoveryMethod:c.recoveryMethod,connectingWalletAddress:c.address,isUnifiedWallet:u,entropyId:y,entropyIdVerifier:g,onCompleteNavigateTo:"SendTransactionScreen",onFailure:()=>{}},sendTransaction:{transactionRequests:D({calls:l,chain:i.chain,maxPriorityFeePerGas:s.maxPriorityFeePerGas,maxFeePerGas:s.maxFeePerGas,nonce:s.nonce?BigInt(s.nonce):void 0}),transactingWalletIndex:0,transactingWalletAddress:i.account.address,entropyId:y,entropyIdVerifier:g,getIsSponsored:d,signOnly:!1,onConfirm:()=>i.sendTransaction(s),onSuccess:e=>n(e.hash),onFailure:m,uiOptions:o?.uiOptions??{}}}),t("EmbeddedWalletConnectingScreen")})).finally((()=>{e.current=!1}))},signMessage:async(s,o)=>n({showWalletUIs:o?.uiOptions?.showWalletUIs})?(e.current=!0,await i.signMessage(s).finally((()=>e.current=!1))):new Promise((async(n,l)=>{let{entropyId:d,entropyIdVerifier:m}=p(a);e.current=!0,r({connectWallet:{recoveryMethod:c.recoveryMethod,connectingWalletAddress:c.address,isUnifiedWallet:u,entropyId:d,entropyIdVerifier:m,onCompleteNavigateTo:"SignRequestScreen",onFailure:()=>{}},signMessage:{method:"personal_sign",data:"string"==typeof s.message?s.message:s.message.raw.toString(),confirmAndSign:()=>i.signMessage(s),onSuccess:e=>n(e),onFailure:l,uiOptions:o?.uiOptions??{}}}),t("EmbeddedWalletConnectingScreen")})).finally((()=>{e.current=!1})),signTypedData:async(s,o)=>n({showWalletUIs:o?.uiOptions?.showWalletUIs})?(e.current=!0,await i.signTypedData(s).finally((()=>e.current=!1))):new Promise((async(n,l)=>{e.current=!0;let{entropyId:d,entropyIdVerifier:m}=p(a);r({connectWallet:{recoveryMethod:c.recoveryMethod,connectingWalletAddress:c.address,isUnifiedWallet:u,entropyId:d,entropyIdVerifier:m,onCompleteNavigateTo:"SignRequestScreen",onFailure:()=>{}},signMessage:{method:"eth_signTypedData_v4",data:s,confirmAndSign:()=>i.signTypedData(s),onSuccess:e=>n(e),onFailure:l,uiOptions:o?.uiOptions??{}}}),t("EmbeddedWalletConnectingScreen")})).finally((()=>{e.current=!1}))})}};export{q as a,D as c,E as g,N as u};