@privy-io/react-auth
Version:
React client for the Privy Auth API
3 lines (2 loc) • 12.2 kB
JavaScript
import{jsxs as e,Fragment as t,jsx as r}from"react/jsx-runtime";import a from"@heroicons/react/24/outline/CheckCircleIcon";import{useState as i,useEffect as n}from"react";import{parseEther as o,createWalletClient as s,custom as d,publicActions as c,createPublicClient as l,http as m,encodeFunctionData as u,formatUnits as p}from"viem";import{addToDefaultChains as h}from"@privy-io/js-sdk-core";import{b as f,c as g,R as v}from"./Layouts-BlFm53ED.mjs";import{B as y}from"./ModalHeader-BnVmXtvG.mjs";import{C}from"./ScreenHeader-CHmc4-Lu.mjs";import{t as I}from"./FundWalletMethodHeader-Cb-ACySl.mjs";import{N as w}from"./index-Dq_xe9dz.mjs";import{u as j,t as T}from"./context-DLtU3JQy.mjs";import{u as b,a as E,b as S}from"./internal-context-Z-fyxadS.mjs";import{z as x}from"./useActiveWallet-CvP7iYvj.mjs";import{a as N}from"./privy-context-DrMxzgOR.mjs";import{u as A}from"./useGetTokenPrice-LPJMl6JV.mjs";import{u as F,b as k}from"./useWallets-BzNCTucF.mjs";import{E as P,a as B}from"./transfer-6YztDh-t.mjs";import{f as U}from"./formatErc20TokenAmount-BuPk9xcy.mjs";import{c as L,a as M,g as W,s as H}from"./ethers-Dnv1tMN3.mjs";import{O as q}from"./analytics-mkkvFRju.mjs";import{t as $,g as G,c as D,u as R}from"./reservoir-0wfhnc0j.mjs";import{y as _}from"./index-YDEix4mU.mjs";import{g as O,B as Q}from"./BridgeNetworkSelectionView-CiJQDIy_.mjs";import{g as V}from"./getErc20Balance-o7J9W1su.mjs";import{v as z}from"./use-export-wallet-_wu5ex5t.mjs";import{T as X}from"./TransferOrBridgeLoadingScreen-DVeIRghG.mjs";import"styled-components";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/QuestionMarkCircleIcon";import"@heroicons/react/24/outline/XMarkIcon";import"tinycolor2";import"ofetch";import"zustand";import"react-device-detect";import"./events-context-CI0iqAXA.mjs";import"viem/utils";import"@privy-io/are-addresses-equal";import"./useGetSolPrice-DwwjjGbd.mjs";import"uuid";import"jose";import"eventemitter3";import"@coinbase/wallet-sdk";import"@privy-io/ethereum";import"mipd";import"@privy-io/popup";import"./paths-3HW55qZg.mjs";import"./usePrivy-C_sY2Duk.mjs";import"@scure/base";import"@headlessui/react";import"@walletconnect/ethereum-provider";import"@privy-io/urls";import"./PrivyPluginContext-2QN2dVUw.mjs";import"./getEmbeddedConnectedWallet-JzK4iD-L.mjs";import"js-cookie";import"./frame-uzTmvtww.mjs";import"@privy-io/routes";import"x402/client";import"@privy-io/api-base";import"viem/accounts";import"./use-sign-with-user-signer-Do5Oi_rb.mjs";import"./Row-C9vrS4Zi.mjs";import"./ErrorMessage-D8VaAP5m.mjs";import"./Value-tcJV9e0L.mjs";import"./LoadingSkeleton-U6-3yFwI.mjs";import"./Subtitle-CV-2yKE4.mjs";import"./Title-BnzYV3Is.mjs";import"@heroicons/react/24/outline/WalletIcon";import"./getChainName-DjpPdUSc.mjs";import"./Chip-D2-wZOHJ.mjs";import"./NetworkIcon-B48ilzF8.mjs";import"@heroicons/react/24/outline/GlobeAltIcon";import"./shared-FM0rljBt.mjs";import"@heroicons/react/24/outline/ChevronDownIcon";import"./styles-DDaGxKdi.mjs";import"./LinkPasskeyScreen-DmtRo8xi.mjs";import"lucide-react";import"./TodoList-CgrU7uwu.mjs";import"./ScreenLayout-D1p_ntex.mjs";import"./Screen-Cycy3IzT.mjs";import"./InjectedWalletIcon-DLcYOGDj.mjs";import"./Address-N-mzBgMy.mjs";const Y={component:()=>{let{rpcConfig:Y,appId:Z,closePrivyModal:J,createAnalyticsEvent:K}=b(),{navigate:ee,setModalData:te,data:re}=N(),ae=j(),{wallets:ie}=F(),[ne,oe]=i(!1),[se,de]=i(0n),[ce,le]=i(!1),[me,ue]=i(null),[pe,he]=i(null),[fe,ge]=i([]),[ve,ye]=i(0),[Ce,Ie]=i(!1),[we,je]=i(!1),[Te,be]=i(!1),[Ee,Se]=i(!1),[xe,Ne]=i(),[Ae,Fe]=i();if(!re?.funding||"ethereum"!==re.funding.chainType)throw Error("Invalid funding data");let{erc20ContractInfo:ke,chain:Pe,connectedWallet:Be}=re.funding,Ue=re.funding.address,Le=re.funding.erc20Address,[Me,We]=i(re.funding.amount);n((()=>{Le&&!ke&&ue(Error("Unable to fetch token details"))}),[]);let He=!!Le&&!!ke,qe=He?BigInt(parseFloat(Me)*10**ke.decimals):o(Me),$e=("ethereum"===Be?.type?Be:void 0)??ie[0],Ge=x($e?.walletClientType||"unknown"),De=Ge?.name||"wallet",[Re,_e]=i(null);n((()=>{(async()=>{if(!$e)return;let e=await $e.getEthereumProvider();_e(s({account:$e.address,transport:d(e)}).extend(c))})().catch(console.error)}),[$e]);let[Oe,Qe]=i(0n);n((()=>{l({chain:Pe,transport:m(k(Pe,Y,Z))}).getBalance({address:Ue}).then(Qe).catch(console.error)}),[]);let[Ve,ze]=i(0n);n((()=>{He&&V({chain:Pe,address:Ue,appId:Z,rpcConfig:Y,erc20Address:Le}).then((e=>ze(e.balance))).catch(console.error)}),[]);let{tokenPrice:Xe}=A(Pe.id),[Ye,Ze]=i({to:Ue,chain:Pe,value:qe,data:void 0});n((()=>{(async()=>{let e,t;if(!Re||!$e||Ce||Te)return;Ie(!0);let r=l({chain:Ye.chain,transport:m(k(Ye.chain,Y,Z))});if(He&&!Ye.data)return await r.simulateContract({address:Le,chain:Ye.chain,abi:P,functionName:"transfer",args:[Ue,qe],account:$e.address}).catch((e=>{if("ContractFunctionZeroDataError"===e?.cause?.name||e?.message?.includes("returned no data"))return r.simulateContract({address:Le,chain:Ye.chain,abi:B,functionName:"transfer",args:[Ue,qe],account:$e.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)}))?(Ie(!1),void Ze({to:Le,chain:Ye.chain,data:u({abi:P,functionName:"transfer",args:[Ue,qe]}),value:"0x0"})):(Ie(!1),void le(!0));try{e=await r.prepareTransactionRequest({account:$e.address,to:Ye.to,chain:Ye.chain,data:Ye.data,value:BigInt(Ye.value??0)})}catch(e){if(console.error(e),fe.length>1)he(e.shortMessage??"Something went wrong");else if(we&&0===fe.length)return void ue(new E(`Wallet ${z($e.address)} does not have enough funds.`,void 0,S.INSUFFICIENT_BALANCE))}if(!e)return Ie(!1),void le(!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),Ie(!1),be(!0),oe(!0),de(e.gas);try{await Re.switchChain({id:Ye.chain.id})}catch(e){await Re.addChain({chain:Ye.chain}),await Re.switchChain({id:Ye.chain.id})}try{t=await Re.sendTransaction(e)}catch(e){if(console.error(e),"TransactionExecutionError"===e.name)if(fe.length<1){let t=e.shortMessage;(e.shortMessage.includes("rejected the request")||e.details.includes("rejected the request"))&&(t="User rejected the request."),ue(new E(t,void 0,S.TRANSACTION_FAILURE))}else he(e.shortMessage??"Something went wrong")}if(t)return await Re.waitForTransactionReceipt({hash:t}),be(!1),we?(Ne(t),void Fe("pending")):(Se(!0),te(_(re,"completed",t,$e?.walletClientType,He,ke,Pe)),void K({eventName:q,payload:{provider:"external",status:"success",txHash:t,address:$e.address,chainId:Ye.chain.id,chainType:"ethereum",value:Ye.value?p(BigInt(Ye.value),ke?.decimals??18):void 0,token:ke?.symbol??Le??"ETH",destinationAddress:Ue,destinationChainId:Pe.id,destinationChainType:"ethereum",destinationValue:qe?p(qe,ke?.decimals??18):void 0,destinationToken:ke?.symbol??Le??Pe.nativeCurrency.name}}));be(!1)})().catch(console.error)}),[Re,Ye]),n((()=>{(async()=>{if(!ce||!Re||!$e)return;let e=h(ae.chains).filter((e=>e.id!==Pe.id&&!!e.testnet==!!Pe.testnet));He&&e.unshift(Pe);let t=await O({chains:e,address:$e.address,appId:Z,rpcConfig:Y,includeUsdc:re.funding?.isUSDC}),r=He?t.filter((e=>e.balance>0n)):t.filter((e=>e.balance>qe)),a=He&&t.every((e=>0n===e.balance));if(r.length<1)return void ue(new E(a?`Wallet ${z($e.address)} doesn't have enough funds to cover gas fees. Top up your wallet and try again.`:`Wallet ${z($e.address)} does not have enough funds.`,void 0,S.INSUFFICIENT_BALANCE));r.sort(((e,t)=>Number(He?(t.erc20Balance??0n)-(e.erc20Balance??0n):t.balance-e.balance)));let i=r.flatMap((e=>{let t=[{...e,isErc20Quote:!1,isTestnet:!!Pe.testnet,input:$({appId:Z,amount:qe.toString(),user:$e.address,recipient:Ue,destinationChainId:Pe.id,destinationCurrency:Le,originChainId:e.chain.id})}];return He&&Le&&(e.erc20Balance??0n)>=qe&&t.push({...e,isErc20Quote:!0,isTestnet:!!Pe.testnet,input:$({appId:Z,amount:qe.toString(),user:$e.address,recipient:Ue,destinationChainId:Pe.id,destinationCurrency:Le,originChainId:e.chain.id,originCurrency:e.erc20Address})}),t})),n=(await Promise.allSettled(i.map((async e=>({...e,quote:await G(e)}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(n.length<1)return void ue(new E(`Wallet ${z($e.address)} does not have enough funds.`,void 0,S.INSUFFICIENT_BALANCE));let o=n.map((e=>({bridgeTx:D(e.quote),balance:e.balance,chain:e.chain,erc20Balance:e.erc20Balance,isErc20Quote:e.isErc20Quote}))).filter((e=>!!e.bridgeTx));if(o.length>1)return void ge(o);let s=o[0];s?(je(!0),Ze({data:s.bridgeTx.data,to:s.bridgeTx.to,value:s.bridgeTx.value,chain:s.chain})):ue(new E(`Wallet ${z($e.address)} does not have enough funds.`,void 0,S.INSUFFICIENT_BALANCE))})().catch(console.error)}),[ce]),R({transactionHash:xe,isTestnet:!!Pe.testnet,bridgingStatus:Ae,setBridgingStatus:Fe,onSuccess({transactionHash:e}){je(!1),Se(!0),te(_(re,"completed",e,$e?.walletClientType,He,ke,Pe)),K({eventName:q,payload:{provider:"external",status:"success",txHash:e,address:$e?.address,chainId:Ye.chain.id,chainType:"ethereum",value:Ye.value?p(BigInt(Ye.value),ke?.decimals??18):void 0,token:ke?.symbol??Le??"ETH",destinationAddress:Ue,destinationChainId:Pe.id,destinationChainType:"ethereum",destinationValue:qe?p(qe,ke?.decimals??18):void 0,destinationToken:ke?.symbol??Le??Pe.nativeCurrency.name}})},onFailure({error:e}){je(!1),ue(e)}}),n((()=>{me&&(te({funding:re?.funding,solanaFundingData:re?.solanaFundingData,sendTransaction:re?.sendTransaction,errorModalData:{error:me,previousScreen:"TransferFromWalletScreen"}}),ee("ErrorScreen",!1))}),[me]);let Je=!He&&Xe?L(Me??"0",Xe):void 0,Ke=He?se:H([se,qe]),et=Ke&&Xe?M(Ke,Xe):void 0,tt=Ke?W(Ke,re?.funding?.erc20Address?re?.funding?.erc20ContractInfo?.symbol||"ETH":re?.funding?.chain.nativeCurrency.symbol||"ETH"):void 0,rt=se&&Xe?M(se,Xe):void 0,at=se?W(se,Pe?.nativeCurrency?.symbol||"ETH"):void 0;if(n((()=>{if(!Ee)return;let e=setTimeout(J,T);return()=>clearTimeout(e)}),[Ee]),Ee/*#__PURE__*/)return e(t,{children:[/*#__PURE__*/r(I,{}),/*#__PURE__*/r(f,{}),/*#__PURE__*/e(g,{children:[/*#__PURE__*/r(a,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/r(C,{title:"Success!",description:`You’ve successfully added ${Me} ${He?ke.symbol:Pe.nativeCurrency.symbol} to your ${ae.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/r(v,{}),/*#__PURE__*/r(y,{})]});let it=He?`${U({amount:Ve,decimals:ke.decimals})} ${ke.symbol}`:W(Oe,Pe.nativeCurrency.symbol,3,!0),nt=fe[ve];return fe.length>1&&nt?/*#__PURE__*/r(Q,{displayName:De,configuredFundingChain:Pe,erc20ContractInfo:ke,formattedBalance:it,fundingAmount:Me,fundingCurrency:He?ke.symbol:Pe.nativeCurrency.symbol,fundingAmountInUsd:Je,options:fe,selectedOption:nt,isPreparing:Ce,isSubmitting:Te,addressToFund:Ue,fundingWalletAddress:$e?.address||"",errorMessage:pe,onSubmit:()=>{re.funding?.amount!==Me?async function(){if($e&&nt)try{let e=await G({isTestnet:!!Pe.testnet,input:$({appId:Z,amount:qe.toString(),user:$e.address,recipient:Ue,destinationChainId:Pe.id,destinationCurrency:Le,originChainId:nt.chain.id})}),t=D(e);if(!t)throw Error("Invalid transaction request");je(!0),Ze({data:t.data,to:t.to,value:t.value,chain:nt.chain})}catch(e){console.error(e),ue(new E("Unable to fetch quotes for bridging",e,S.INSUFFICIENT_BALANCE))}}().catch(console.error):Ze({to:nt.bridgeTx.to,data:nt.bridgeTx.data,value:nt.bridgeTx.value,chain:nt.chain})},onSelect:e=>{e!==ve&&(he(null),ye(e))},onAmountChange:We}):ne&&se&&$e&&re?.funding?/*#__PURE__*/r(X,{walletClientType:$e?.walletClientType||"unknown",displayName:De,addressToFund:Ue,isBridging:we,isErc20Flow:He,totalPriceInUsd:et,totalPriceInNativeCurrency:tt,gasPriceInUsd:rt,gasPriceInNativeCurrency:at,chainId:Pe.id,chainName:Pe.name}):
/*#__PURE__*/e(t,{children:[/*#__PURE__*/r(I,{}),/*#__PURE__*/r(w,{}),/*#__PURE__*/r("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/r(y,{})]})}};export{Y as AwaitingExternalEthereumTransferScreen,Y as default};