@privy-io/react-auth
Version:
React client for the Privy Auth API
3 lines (2 loc) • 13.7 kB
JavaScript
;var e=require("react/jsx-runtime"),r=require("@heroicons/react/24/outline/CheckCircleIcon"),t=require("react"),i=require("viem"),n=require("@privy-io/js-sdk-core"),a=require("./Layouts-D3TOcPhm.js"),s=require("./ModalHeader-C5Wuo3-1.js"),o=require("./ScreenHeader-CgYJ5Fmg.js"),u=require("./FundWalletMethodHeader-BTGxq_KO.js"),d=require("./index-ByFhjjzH.js"),c=require("./context-Cg3IEi80.js"),l=require("./internal-context-BJv4f_bO.js"),h=require("./useActiveWallet-BfMD5hzE.js"),g=require("./privy-context-CrM9_s6G.js"),f=require("./useGetTokenPrice-CSWuvKuF.js"),m=require("./useWallets-dikDynAG.js"),v=require("./transfer-B1Y_9LWi.js"),p=require("./formatErc20TokenAmount-DxwoWe7e.js"),y=require("./ethers-p3w-Ig2U.js"),C=require("./analytics-C6C_4JmG.js"),q=require("./reservoir-Bx0HQwbb.js"),E=require("./index-DchMyzt9.js"),T=require("./BridgeNetworkSelectionView-DKogJoIK.js"),I=require("./getErc20Balance-CTO0RtgK.js"),S=require("./use-export-wallet-_EIyxyle.js"),j=require("./TransferOrBridgeLoadingScreen-DsutKbzS.js");function w(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("styled-components"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("tinycolor2"),require("ofetch"),require("zustand"),require("react-device-detect"),require("./events-context-Di6--rDg.js"),require("viem/utils"),require("@privy-io/are-addresses-equal"),require("./useGetSolPrice-Ca32VAbF.js"),require("uuid"),require("jose"),require("eventemitter3"),require("@coinbase/wallet-sdk"),require("@privy-io/ethereum"),require("mipd"),require("@privy-io/popup"),require("./paths-DizMb-lU.js"),require("./usePrivy-C-Rab7yP.js"),require("@scure/base"),require("@headlessui/react"),require("@walletconnect/ethereum-provider"),require("@privy-io/urls"),require("./PrivyPluginContext-DsgaS6n9.js"),require("./getEmbeddedConnectedWallet-pJd-l936.js"),require("js-cookie"),require("./frame-Oz7volks.js"),require("@privy-io/routes"),require("x402/client"),require("@privy-io/api-base"),require("viem/accounts"),require("./use-sign-with-user-signer-Cu_6Bx7m.js"),require("./Row-CMqYn75Q.js"),require("./ErrorMessage-BfTVyue9.js"),require("./Value-mhPsfsxe.js"),require("./LoadingSkeleton-BoyADunQ.js"),require("./Subtitle-CR8zM7ZJ.js"),require("./Title-ifTy35V5.js"),require("@heroicons/react/24/outline/WalletIcon"),require("./getChainName-C4rO8-3n.js"),require("./Chip-C6r7fZiR.js"),require("./NetworkIcon-BZ9Mj6vV.js"),require("@heroicons/react/24/outline/GlobeAltIcon"),require("./shared-DBm7PUrg.js"),require("@heroicons/react/24/outline/ChevronDownIcon"),require("./styles-B1M_BS_A.js"),require("./LinkPasskeyScreen-D9Y8PpKL.js"),require("lucide-react"),require("./TodoList-Cii_KrAk.js"),require("./ScreenLayout-C4QHZMbl.js"),require("./Screen-DWnRbzSA.js"),require("./InjectedWalletIcon-UY3nMvZo.js"),require("./Address-BeuDoSGB.js");var b=/*#__PURE__*/w(r);const A={component:()=>{let{rpcConfig:r,appId:w,closePrivyModal:A,createAnalyticsEvent:F}=l.usePrivyInternal(),{navigate:N,setModalData:x,data:P}=g.usePrivyModal(),B=c.useAppConfig(),{wallets:_}=m.useWallets(),[R,W]=t.useState(!1),[k,U]=t.useState(0n),[L,M]=t.useState(!1),[D,G]=t.useState(null),[H,Q]=t.useState(null),[O,$]=t.useState([]),[V,Y]=t.useState(0),[J,X]=t.useState(!1),[z,Z]=t.useState(!1),[K,ee]=t.useState(!1),[re,te]=t.useState(!1),[ie,ne]=t.useState(),[ae,se]=t.useState();if(!P?.funding||"ethereum"!==P.funding.chainType)throw Error("Invalid funding data");let{erc20ContractInfo:oe,chain:ue,connectedWallet:de}=P.funding,ce=P.funding.address,le=P.funding.erc20Address,[he,ge]=t.useState(P.funding.amount);t.useEffect((()=>{le&&!oe&&G(Error("Unable to fetch token details"))}),[]);let fe=!!le&&!!oe,me=fe?BigInt(parseFloat(he)*10**oe.decimals):i.parseEther(he),ve=("ethereum"===de?.type?de:void 0)??_[0],pe=h.useExternalWalletListing(ve?.walletClientType||"unknown"),ye=pe?.name||"wallet",[Ce,qe]=t.useState(null);t.useEffect((()=>{(async()=>{if(!ve)return;let e=await ve.getEthereumProvider();qe(i.createWalletClient({account:ve.address,transport:i.custom(e)}).extend(i.publicActions))})().catch(console.error)}),[ve]);let[Ee,Te]=t.useState(0n);t.useEffect((()=>{i.createPublicClient({chain:ue,transport:i.http(m.getJsonRpcEndpointFromChain(ue,r,w))}).getBalance({address:ce}).then(Te).catch(console.error)}),[]);let[Ie,Se]=t.useState(0n);t.useEffect((()=>{fe&&I.getErc20Balance({chain:ue,address:ce,appId:w,rpcConfig:r,erc20Address:le}).then((e=>Se(e.balance))).catch(console.error)}),[]);let{tokenPrice:je}=f.useGetTokenPrice(ue.id),[we,be]=t.useState({to:ce,chain:ue,value:me,data:void 0});t.useEffect((()=>{(async()=>{let e,t;if(!Ce||!ve||J||K)return;X(!0);let n=i.createPublicClient({chain:we.chain,transport:i.http(m.getJsonRpcEndpointFromChain(we.chain,r,w))});if(fe&&!we.data)return await n.simulateContract({address:le,chain:we.chain,abi:v.ERC20_TRANSFER_ABI_STUB,functionName:"transfer",args:[ce,me],account:ve.address}).catch((e=>{if("ContractFunctionZeroDataError"===e?.cause?.name||e?.message?.includes("returned no data"))return n.simulateContract({address:le,chain:we.chain,abi:v.ERC20_TRANSFER_ABI_STUB_NO_RETURN,functionName:"transfer",args:[ce,me],account:ve.address}).catch((e=>{console.warn("Simulated token transfer failed with error, fetching bridge options.",e)}));console.warn("Simulated token transfer failed with error, fetching bridge options.",e)}))?(X(!1),void be({to:le,chain:we.chain,data:i.encodeFunctionData({abi:v.ERC20_TRANSFER_ABI_STUB,functionName:"transfer",args:[ce,me]}),value:"0x0"})):(X(!1),void M(!0));try{e=await n.prepareTransactionRequest({account:ve.address,to:we.to,chain:we.chain,data:we.data,value:BigInt(we.value??0)})}catch(e){if(console.error(e),O.length>1)Q(e.shortMessage??"Something went wrong");else if(z&&0===O.length)return void G(new l.PrivyClientError(`Wallet ${S.formatWalletAddress(ve.address)} does not have enough funds.`,void 0,l.PrivyErrorCode.INSUFFICIENT_BALANCE))}if(!e)return X(!1),void M(!0);"eip1559"===e.type||"eip4844"===e.type||"eip7702"===e.type?void 0!==e.gasPrice&&delete e.gasPrice:("legacy"===e.type||"eip2930"===e.type)&&(void 0!==e.maxFeePerGas&&delete e.maxFeePerGas,void 0!==e.maxPriorityFeePerGas&&delete e.maxPriorityFeePerGas),X(!1),ee(!0),W(!0),U(e.gas);try{await Ce.switchChain({id:we.chain.id})}catch(e){await Ce.addChain({chain:we.chain}),await Ce.switchChain({id:we.chain.id})}try{t=await Ce.sendTransaction(e)}catch(e){if(console.error(e),"TransactionExecutionError"===e.name)if(O.length<1){let r=e.shortMessage;(e.shortMessage.includes("rejected the request")||e.details.includes("rejected the request"))&&(r="User rejected the request."),G(new l.PrivyClientError(r,void 0,l.PrivyErrorCode.TRANSACTION_FAILURE))}else Q(e.shortMessage??"Something went wrong")}if(t)return await Ce.waitForTransactionReceipt({hash:t}),ee(!1),z?(ne(t),void se("pending")):(te(!0),x(E.addFundingResultToModalData(P,"completed",t,ve?.walletClientType,fe,oe,ue)),void F({eventName:C.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:t,address:ve.address,chainId:we.chain.id,chainType:"ethereum",value:we.value?i.formatUnits(BigInt(we.value),oe?.decimals??18):void 0,token:oe?.symbol??le??"ETH",destinationAddress:ce,destinationChainId:ue.id,destinationChainType:"ethereum",destinationValue:me?i.formatUnits(me,oe?.decimals??18):void 0,destinationToken:oe?.symbol??le??ue.nativeCurrency.name}}));ee(!1)})().catch(console.error)}),[Ce,we]),t.useEffect((()=>{(async()=>{if(!L||!Ce||!ve)return;let e=n.addToDefaultChains(B.chains).filter((e=>e.id!==ue.id&&!!e.testnet==!!ue.testnet));fe&&e.unshift(ue);let t=await T.getBalanceForChains({chains:e,address:ve.address,appId:w,rpcConfig:r,includeUsdc:P.funding?.isUSDC}),i=fe?t.filter((e=>e.balance>0n)):t.filter((e=>e.balance>me)),a=fe&&t.every((e=>0n===e.balance));if(i.length<1)return void G(a?new l.PrivyClientError(`Wallet ${S.formatWalletAddress(ve.address)} doesn't have enough funds to cover gas fees. Top up your wallet and try again.`,void 0,l.PrivyErrorCode.INSUFFICIENT_BALANCE):new l.PrivyClientError(`Wallet ${S.formatWalletAddress(ve.address)} does not have enough funds.`,void 0,l.PrivyErrorCode.INSUFFICIENT_BALANCE));i.sort(((e,r)=>Number(fe?(r.erc20Balance??0n)-(e.erc20Balance??0n):r.balance-e.balance)));let s=i.flatMap((e=>{let r=[{...e,isErc20Quote:!1,isTestnet:!!ue.testnet,input:q.toGetQuoteInput({appId:w,amount:me.toString(),user:ve.address,recipient:ce,destinationChainId:ue.id,destinationCurrency:le,originChainId:e.chain.id})}];return fe&&le&&(e.erc20Balance??0n)>=me&&r.push({...e,isErc20Quote:!0,isTestnet:!!ue.testnet,input:q.toGetQuoteInput({appId:w,amount:me.toString(),user:ve.address,recipient:ce,destinationChainId:ue.id,destinationCurrency:le,originChainId:e.chain.id,originCurrency:e.erc20Address})}),r})),o=(await Promise.allSettled(s.map((async e=>({...e,quote:await q.getQuote(e)}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(o.length<1)return void G(new l.PrivyClientError(`Wallet ${S.formatWalletAddress(ve.address)} does not have enough funds.`,void 0,l.PrivyErrorCode.INSUFFICIENT_BALANCE));let u=o.map((e=>({bridgeTx:q.toEvmTransactionRequestInfoFromQuote(e.quote),balance:e.balance,chain:e.chain,erc20Balance:e.erc20Balance,isErc20Quote:e.isErc20Quote}))).filter((e=>!!e.bridgeTx));if(u.length>1)return void $(u);let d=u[0];d?(Z(!0),be({data:d.bridgeTx.data,to:d.bridgeTx.to,value:d.bridgeTx.value,chain:d.chain})):G(new l.PrivyClientError(`Wallet ${S.formatWalletAddress(ve.address)} does not have enough funds.`,void 0,l.PrivyErrorCode.INSUFFICIENT_BALANCE))})().catch(console.error)}),[L]),q.useBridgingStatusPolling({transactionHash:ie,isTestnet:!!ue.testnet,bridgingStatus:ae,setBridgingStatus:se,onSuccess({transactionHash:e}){Z(!1),te(!0),x(E.addFundingResultToModalData(P,"completed",e,ve?.walletClientType,fe,oe,ue)),F({eventName:C.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:e,address:ve?.address,chainId:we.chain.id,chainType:"ethereum",value:we.value?i.formatUnits(BigInt(we.value),oe?.decimals??18):void 0,token:oe?.symbol??le??"ETH",destinationAddress:ce,destinationChainId:ue.id,destinationChainType:"ethereum",destinationValue:me?i.formatUnits(me,oe?.decimals??18):void 0,destinationToken:oe?.symbol??le??ue.nativeCurrency.name}})},onFailure({error:e}){Z(!1),G(e)}}),t.useEffect((()=>{D&&(x({funding:P?.funding,solanaFundingData:P?.solanaFundingData,sendTransaction:P?.sendTransaction,errorModalData:{error:D,previousScreen:"TransferFromWalletScreen"}}),N("ErrorScreen",!1))}),[D]);let Ae=!fe&&je?y.getDollarsFromStringFloat(he??"0",je):void 0,Fe=fe?k:y.sumWeiQuantities([k,me]),Ne=Fe&&je?y.getDollarsFromWei(Fe,je):void 0,xe=Fe?y.getNativeCurrencyFromWei(Fe,P?.funding?.erc20Address?P?.funding?.erc20ContractInfo?.symbol||"ETH":P?.funding?.chain.nativeCurrency.symbol||"ETH"):void 0,Pe=k&&je?y.getDollarsFromWei(k,je):void 0,Be=k?y.getNativeCurrencyFromWei(k,ue?.nativeCurrency?.symbol||"ETH"):void 0;if(t.useEffect((()=>{if(!re)return;let e=setTimeout(A,c.DEFAULT_SUCCESS_SCREEN_EXTRA_LONG_DURATION_MS);return()=>clearTimeout(e)}),[re]),re/*#__PURE__*/)return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(u.t,{}),/*#__PURE__*/e.jsx(a.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(a.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(b.default,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:"Success!",description:`You’ve successfully added ${he} ${fe?oe.symbol:ue.nativeCurrency.symbol} to your ${B.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/e.jsx(a.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]});let _e=fe?`${p.formatErc20TokenAmount({amount:Ie,decimals:oe.decimals})} ${oe.symbol}`:y.getNativeCurrencyFromWei(Ee,ue.nativeCurrency.symbol,3,!0),Re=O[V];return O.length>1&&Re?/*#__PURE__*/e.jsx(T.BridgeNetworkSelectionView,{displayName:ye,configuredFundingChain:ue,erc20ContractInfo:oe,formattedBalance:_e,fundingAmount:he,fundingCurrency:fe?oe.symbol:ue.nativeCurrency.symbol,fundingAmountInUsd:Ae,options:O,selectedOption:Re,isPreparing:J,isSubmitting:K,addressToFund:ce,fundingWalletAddress:ve?.address||"",errorMessage:H,onSubmit:()=>{P.funding?.amount!==he?async function(){if(ve&&Re)try{let e=await q.getQuote({isTestnet:!!ue.testnet,input:q.toGetQuoteInput({appId:w,amount:me.toString(),user:ve.address,recipient:ce,destinationChainId:ue.id,destinationCurrency:le,originChainId:Re.chain.id})}),r=q.toEvmTransactionRequestInfoFromQuote(e);if(!r)throw Error("Invalid transaction request");Z(!0),be({data:r.data,to:r.to,value:r.value,chain:Re.chain})}catch(e){console.error(e),G(new l.PrivyClientError("Unable to fetch quotes for bridging",e,l.PrivyErrorCode.INSUFFICIENT_BALANCE))}}().catch(console.error):be({to:Re.bridgeTx.to,data:Re.bridgeTx.data,value:Re.bridgeTx.value,chain:Re.chain})},onSelect:e=>{e!==V&&(Q(null),Y(e))},onAmountChange:ge}):R&&k&&ve&&P?.funding?/*#__PURE__*/e.jsx(j.TransferOrBridgeLoadingScreen,{walletClientType:ve?.walletClientType||"unknown",displayName:ye,addressToFund:ce,isBridging:z,isErc20Flow:fe,totalPriceInUsd:Ne,totalPriceInNativeCurrency:xe,gasPriceInUsd:Pe,gasPriceInNativeCurrency:Be,chainId:ue.id,chainName:ue.name}):
/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(u.t,{}),/*#__PURE__*/e.jsx(d.NeutralSpinner,{}),/*#__PURE__*/e.jsx("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/e.jsx(s.BlobbyFooter,{})]})}};exports.AwaitingExternalEthereumTransferScreen=A,exports.default=A;