UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

3 lines (2 loc) • 11.5 kB
import{jsxs as e,Fragment as t,jsx as i}from"react/jsx-runtime";import r from"@heroicons/react/24/outline/CheckCircleIcon";import{useState as a,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-Bmf8DxNP.mjs";import{B as y}from"./ModalHeader-BLGC-7ev.mjs";import{C}from"./ScreenHeader-Biz1wq02.mjs";import{t as I}from"./FundWalletMethodHeader-I8a6Y30s.mjs";import{N as T}from"./index-CJMgUOnw.mjs";import{u as w,t as b}from"./context-Bycd1SKV.mjs";import{u as j,a as E,b as N}from"./internal-context-e-Eni5bG.mjs";import{Q as S,D as A}from"./useActiveWallet-Bsy5GTCV.mjs";import{a as x}from"./get-is-unified-wallet-DvKS5IUO.mjs";import{u as B}from"./useGetTokenPrice-0Bn0Y88A.mjs";import{u as k}from"./useWallets-D0lpBS44.mjs";import{E as F}from"./transfer-CMPmjPsM.mjs";import{f as M}from"./formatErc20TokenAmount-BuPk9xcy.mjs";import{c as U,a as W,g as P,s as H}from"./ethers-C3Y94dat.mjs";import{O as $}from"./analytics-mkkvFRju.mjs";import{t as q,g as L,c as D,u as R}from"./reservoir-kvLjIrEo.mjs";import{x as Q}from"./index-CCyaupaz.mjs";import{g as _,B as O}from"./BridgeNetworkSelectionView-Dn5uqa3q.mjs";import{g as V}from"./getErc20Balance-CaKjNAs9.mjs";import{a as G}from"./getPublicClient-A9RSftUZ.mjs";import{T as z}from"./TransferOrBridgeLoadingScreen-D5Y_FQAB.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"./prepareFundingModalData-CIgFwA7s.mjs";import"eventemitter3";import"./events-context-CI0iqAXA.mjs";import"viem/utils";import"./useGetSolPrice-Cfm8o9C5.mjs";import"uuid";import"jose";import"@coinbase/wallet-sdk";import"@privy-io/ethereum";import"mipd";import"@privy-io/popup";import"./paths-3HW55qZg.mjs";import"./usePrivy-BaiIHGte.mjs";import"@scure/base";import"@headlessui/react";import"@walletconnect/ethereum-provider";import"@privy-io/urls";import"js-cookie";import"./frame-CwE9r3cT.mjs";import"@privy-io/routes";import"x402/client";import"@privy-io/api-base";import"viem/accounts";import"./use-sign-with-user-signer-eEm9Olt_.mjs";import"./getEmbeddedConnectedWallet-CM6cDQCS.mjs";import"./Button-B8mqatRx.mjs";import"./Row-CG0lSY5Z.mjs";import"./ErrorMessage-Cx8GKGhL.mjs";import"./Value-B4M62ove.mjs";import"./LoadingSkeleton-CHdaq3pb.mjs";import"./Subtitle-DkvfP2Ev.mjs";import"./Title-D0pfZff-.mjs";import"@heroicons/react/24/outline/WalletIcon";import"./getChainName-DjpPdUSc.mjs";import"./Chip-Bsgj4Yc-.mjs";import"./NetworkIcon-B48ilzF8.mjs";import"@heroicons/react/24/outline/GlobeAltIcon";import"./shared-CtYf3O54.mjs";import"@heroicons/react/24/outline/ChevronDownIcon";import"./styles-DY17fuAX.mjs";import"./InjectedWalletIcon-DLcYOGDj.mjs";import"./Address-BsvZLUXE.mjs";import"lucide-react";const X={component:()=>{let{rpcConfig:X,appId:Y,closePrivyModal:J,createAnalyticsEvent:K}=j(),{navigate:Z,setModalData:ee,data:te}=x(),ie=w(),{wallets:re}=k(),[ae,ne]=a(!1),[oe,se]=a(0n),[de,ce]=a(!1),[le,me]=a(null),[ue,pe]=a(null),[he,fe]=a([]),[ge,ve]=a(0),[ye,Ce]=a(!1),[Ie,Te]=a(!1),[we,be]=a(!1),[je,Ee]=a(!1),[Ne,Se]=a(),[Ae,xe]=a();if(!te?.funding||"ethereum"!==te.funding.chainType)throw Error("Invalid funding data");let{erc20ContractInfo:Be,chain:ke,connectedWallet:Fe}=te.funding,Me=te.funding.address,Ue=te.funding.erc20Address,[We,Pe]=a(te.funding.amount);n((()=>{Ue&&!Be&&me(Error("Unable to fetch token details"))}),[]);let He=!!Ue&&!!Be,$e=He?BigInt(parseFloat(We)*10**Be.decimals):o(We),qe=("ethereum"===Fe?.type?Fe:void 0)??re[0],Le=S(qe?.walletClientType||"unknown"),De=Le?.name||"wallet",[Re,Qe]=a(null);n((()=>{(async()=>{if(!qe)return;let e=await qe.getEthereumProvider();Qe(s({account:qe.address,transport:d(e)}).extend(c))})().catch(console.error)}),[qe]);let[_e,Oe]=a(0n);n((()=>{l({chain:ke,transport:m(G(ke,X,Y))}).getBalance({address:Me}).then(Oe).catch(console.error)}),[]);let[Ve,Ge]=a(0n);n((()=>{He&&V({chain:ke,address:Me,appId:Y,rpcConfig:X,erc20Address:Ue}).then((e=>Ge(e.balance))).catch(console.error)}),[]);let{tokenPrice:ze}=B(ke.id),[Xe,Ye]=a({to:Me,chain:ke,value:$e,data:void 0});n((()=>{(async()=>{let e,t;if(!Re||!qe||ye||we)return;Ce(!0);let i=l({chain:Xe.chain,transport:m(G(Xe.chain,X,Y))});if(He&&!Xe.data)return await i.simulateContract({address:Ue,chain:Xe.chain,abi:F,functionName:"transfer",args:[Me,$e],account:qe.address}).catch((e=>{console.warn("Simulated token transfer failed with error, fetching bridge options.",e)}))?(Ce(!1),void Ye({to:Ue,chain:Xe.chain,data:u({abi:F,functionName:"transfer",args:[Me,$e]}),value:"0x0"})):(Ce(!1),void ce(!0));try{e=await i.prepareTransactionRequest({account:qe.address,to:Xe.to,chain:Xe.chain,data:Xe.data,value:BigInt(Xe.value??0)})}catch(e){if(console.error(e),he.length>1)pe(e.shortMessage??"Something went wrong");else if(Ie&&0===he.length)return void me(new E(`Wallet ${A(qe.address)} does not have enough funds.`,void 0,N.INSUFFICIENT_BALANCE))}if(!e)return Ce(!1),void ce(!0);Ce(!1),be(!0),ne(!0),se(e.gas);try{await Re.switchChain({id:Xe.chain.id})}catch(e){await Re.addChain({chain:Xe.chain}),await Re.switchChain({id:Xe.chain.id})}try{t=await Re.sendTransaction(e)}catch(e){if(console.error(e),"TransactionExecutionError"===e.name)if(he.length<1){let t=e.shortMessage;(e.shortMessage.includes("rejected the request")||e.details.includes("rejected the request"))&&(t="User rejected the request."),me(new E(t,void 0,N.TRANSACTION_FAILURE))}else pe(e.shortMessage??"Something went wrong")}if(t)return await Re.waitForTransactionReceipt({hash:t}),be(!1),Ie?(Se(t),void xe("pending")):(Ee(!0),ee(Q(te,"completed",t,qe?.walletClientType,He,Be,ke)),void K({eventName:$,payload:{provider:"external",status:"success",txHash:t,address:qe.address,chainId:Xe.chain.id,chainType:"ethereum",value:Xe.value?p(BigInt(Xe.value),Be?.decimals??18):void 0,token:Be?.symbol??Ue??"ETH",destinationAddress:Me,destinationChainId:ke.id,destinationChainType:"ethereum",destinationValue:$e?p($e,Be?.decimals??18):void 0,destinationToken:Be?.symbol??Ue??ke.nativeCurrency.name}}));be(!1)})().catch(console.error)}),[Re,Xe]),n((()=>{(async()=>{if(!de||!Re||!qe)return;let e=h(ie.chains).filter((e=>e.id!==ke.id&&!!e.testnet==!!ke.testnet));He&&e.unshift(ke);let t=await _({chains:e,address:qe.address,appId:Y,rpcConfig:X,includeUsdc:te.funding?.isUSDC}),i=He?t.filter((e=>e.balance>0n)):t.filter((e=>e.balance>$e)),r=He&&t.every((e=>0n===e.balance));if(i.length<1)return void me(new E(r?`Wallet ${A(qe.address)} doesn't have enough funds to cover gas fees. Top up your wallet and try again.`:`Wallet ${A(qe.address)} does not have enough funds.`,void 0,N.INSUFFICIENT_BALANCE));i.sort(((e,t)=>Number(He?(t.erc20Balance??0n)-(e.erc20Balance??0n):t.balance-e.balance)));let a=i.flatMap((e=>{let t=[{...e,isErc20Quote:!1,isTestnet:!!ke.testnet,input:q({appId:Y,amount:$e.toString(),user:qe.address,recipient:Me,destinationChainId:ke.id,destinationCurrency:Ue,originChainId:e.chain.id})}];return He&&Ue&&(e.erc20Balance??0n)>=$e&&t.push({...e,isErc20Quote:!0,isTestnet:!!ke.testnet,input:q({appId:Y,amount:$e.toString(),user:qe.address,recipient:Me,destinationChainId:ke.id,destinationCurrency:Ue,originChainId:e.chain.id,originCurrency:e.erc20Address})}),t})),n=(await Promise.allSettled(a.map((async e=>({...e,quote:await L(e)}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(n.length<1)return void me(new E(`Wallet ${A(qe.address)} does not have enough funds.`,void 0,N.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 fe(o);let s=o[0];s?(Te(!0),Ye({data:s.bridgeTx.data,to:s.bridgeTx.to,value:s.bridgeTx.value,chain:s.chain})):me(new E(`Wallet ${A(qe.address)} does not have enough funds.`,void 0,N.INSUFFICIENT_BALANCE))})().catch(console.error)}),[de]),R({transactionHash:Ne,isTestnet:!!ke.testnet,bridgingStatus:Ae,setBridgingStatus:xe,onSuccess({transactionHash:e}){Te(!1),Ee(!0),ee(Q(te,"completed",e,qe?.walletClientType,He,Be,ke)),K({eventName:$,payload:{provider:"external",status:"success",txHash:e,address:qe?.address,chainId:Xe.chain.id,chainType:"ethereum",value:Xe.value?p(BigInt(Xe.value),Be?.decimals??18):void 0,token:Be?.symbol??Ue??"ETH",destinationAddress:Me,destinationChainId:ke.id,destinationChainType:"ethereum",destinationValue:$e?p($e,Be?.decimals??18):void 0,destinationToken:Be?.symbol??Ue??ke.nativeCurrency.name}})},onFailure({error:e}){Te(!1),me(e)}}),n((()=>{le&&(ee({funding:te?.funding,solanaFundingData:te?.solanaFundingData,sendTransaction:te?.sendTransaction,errorModalData:{error:le,previousScreen:"TransferFromWalletScreen"}}),Z("ErrorScreen",!1))}),[le]);let Je=!He&&ze?U(We??"0",ze):void 0,Ke=He?oe:H([oe,$e]),Ze=Ke&&ze?W(Ke,ze):void 0,et=Ke?P(Ke,te?.funding?.erc20Address?te?.funding?.erc20ContractInfo?.symbol||"ETH":te?.funding?.chain.nativeCurrency.symbol||"ETH"):void 0,tt=oe&&ze?W(oe,ze):void 0,it=oe?P(oe,ke?.nativeCurrency?.symbol||"ETH"):void 0;if(n((()=>{if(!je)return;let e=setTimeout(J,b);return()=>clearTimeout(e)}),[je]),je/*#__PURE__*/)return e(t,{children:[/*#__PURE__*/i(I,{}),/*#__PURE__*/i(f,{}),/*#__PURE__*/e(g,{children:[/*#__PURE__*/i(r,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/i(C,{title:"Success!",description:`You’ve successfully added ${We} ${He?Be.symbol:ke.nativeCurrency.symbol} to your ${ie.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/i(v,{}),/*#__PURE__*/i(y,{})]});let rt=He?`${M({amount:Ve,decimals:Be.decimals})} ${Be.symbol}`:P(_e,ke.nativeCurrency.symbol,3,!0),at=he[ge];return he.length>1&&at?/*#__PURE__*/i(O,{displayName:De,configuredFundingChain:ke,erc20ContractInfo:Be,formattedBalance:rt,fundingAmount:We,fundingCurrency:He?Be.symbol:ke.nativeCurrency.symbol,fundingAmountInUsd:Je,options:he,selectedOption:at,isPreparing:ye,isSubmitting:we,addressToFund:Me,fundingWalletAddress:qe?.address||"",errorMessage:ue,onSubmit:()=>{te.funding?.amount!==We?async function(){if(qe&&at)try{let e=await L({isTestnet:!!ke.testnet,input:q({appId:Y,amount:$e.toString(),user:qe.address,recipient:Me,destinationChainId:ke.id,destinationCurrency:Ue,originChainId:at.chain.id})}),t=D(e);if(!t)throw Error("Invalid transaction request");Te(!0),Ye({data:t.data,to:t.to,value:t.value,chain:at.chain})}catch(e){console.error(e),me(new E("Unable to fetch quotes for bridging",e,N.INSUFFICIENT_BALANCE))}}().catch(console.error):Ye({to:at.bridgeTx.to,data:at.bridgeTx.data,value:at.bridgeTx.value,chain:at.chain})},onSelect:e=>{e!==ge&&(pe(null),ve(e))},onAmountChange:Pe}):ae&&oe&&qe&&te?.funding?/*#__PURE__*/i(z,{walletClientType:qe?.walletClientType||"unknown",displayName:De,addressToFund:Me,isBridging:Ie,isErc20Flow:He,totalPriceInUsd:Ze,totalPriceInNativeCurrency:et,gasPriceInUsd:tt,gasPriceInNativeCurrency:it,chainId:ke.id,chainName:ke.name}): /*#__PURE__*/e(t,{children:[/*#__PURE__*/i(I,{}),/*#__PURE__*/i(T,{}),/*#__PURE__*/i("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/i(y,{})]})}};export{X as AwaitingExternalEthereumTransferScreen,X as default};