UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

3 lines (2 loc) 9.34 kB
import{jsxs as e,Fragment as t,jsx as a}from"react/jsx-runtime";import i from"@heroicons/react/24/outline/CheckCircleIcon";import{useState as n,useEffect as r}from"react";import{createWalletClient as o,custom as s,publicActions as d,createPublicClient as c,http as m,formatUnits as l}from"viem";import{addToDefaultChains as u}from"@privy-io/js-sdk-core";import{b as p,c as h,R as g}from"./Layouts-Bmf8DxNP.mjs";import{B as f}from"./ModalHeader-BLGC-7ev.mjs";import{C as v}from"./ScreenHeader-Biz1wq02.mjs";import{t as I}from"./FundWalletMethodHeader-I8a6Y30s.mjs";import{N as j}from"./index-CJMgUOnw.mjs";import{u as w,t as y}from"./context-Bycd1SKV.mjs";import{u as T,a as C,b}from"./internal-context-e-Eni5bG.mjs";import{Q as S,D as N}from"./useActiveWallet-Bsy5GTCV.mjs";import{a as E}from"./get-is-unified-wallet-DvKS5IUO.mjs";import{u as x}from"./useGetTokenPrice-0Bn0Y88A.mjs";import{u as A}from"./useWallets-D0lpBS44.mjs";import{O as k}from"./analytics-mkkvFRju.mjs";import{g as F,t as B,a as U,b as L,c as M,u as P}from"./reservoir-kvLjIrEo.mjs";import{w as W}from"./index-CCyaupaz.mjs";import{g as q}from"./getChainName-DjpPdUSc.mjs";import{g as H,a as R}from"./transaction-CnfuREWo.mjs";import{g as D,B as O}from"./BridgeNetworkSelectionView-Dn5uqa3q.mjs";import{a as $}from"./getPublicClient-A9RSftUZ.mjs";import{T as _}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"./getFormattedUsdFromLamports-B6EqSEho.mjs";import"./getErc20Balance-CaKjNAs9.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"./Chip-Bsgj4Yc-.mjs";import"./NetworkIcon-B48ilzF8.mjs";import"@heroicons/react/24/outline/GlobeAltIcon";import"./shared-CtYf3O54.mjs";import"@heroicons/react/24/outline/ChevronDownIcon";import"./formatErc20TokenAmount-BuPk9xcy.mjs";import"./ethers-C3Y94dat.mjs";import"./styles-DY17fuAX.mjs";import"./InjectedWalletIcon-DLcYOGDj.mjs";import"./Address-BsvZLUXE.mjs";import"lucide-react";const Q={component:()=>{let Q=w(),{rpcConfig:V,appId:G,closePrivyModal:z,createAnalyticsEvent:X}=T(),{navigate:Y,setModalData:J,data:K}=E(),Z=w(),{wallets:ee}=A(),[te,ae]=n(null),[ie,ne]=n(null),[re,oe]=n([]),[se,de]=n(0),[ce,me]=n(!1),[le,ue]=n(!1),[pe,he]=n(!1),[ge,fe]=n(!1),[ve,Ie]=n(),[je,we]=n();if(!K?.funding||"solana"!==K.funding.chainType)throw Error("Invalid funding data");let{address:ye,chain:Te,connectedWallet:Ce}=K.funding,[be,Se]=n(K.funding.amount),Ne=("ethereum"===Ce?.type?Ce:void 0)??ee[0],Ee=S(Ne?.walletClientType||"unknown"),xe=Ee?.name||"wallet",[Ae,ke]=n(null);r((()=>{(async()=>{if(!Ne)return;let e=await Ne.getEthereumProvider();ke(o({account:Ne.address,transport:s(e)}).extend(d))})().catch(console.error)}),[Ne]);let[Fe,Be]=n(0n),Ue=H(Fe);r((()=>{let e=Q.solanaRpcs[Te];e?W({rpc:e.rpc,address:ye}).then((e=>Be(BigInt(e)))).catch(console.error):console.warn("Unable to load solana rpc, skipping balance")}),[]);let[Le,Me]=n(),{tokenPrice:Pe}=x("solana"),{fundingAmountInBaseUnit:We,fundingAmountInUsd:qe}=R({amount:be,fee:0n,tokenPrice:Pe,isUsdc:K.funding.isUSDC});if(r((()=>{(async()=>{if(!Ae||!Ne)return;let e=["solana:testnet","solana:devnet"].includes(Te);e&&console.warn("Solana testnets are not supported for bridging");let t=u(Z.chains).filter((({testnet:t})=>!!t===e)),a=(await D({chains:t,address:Ne.address,appId:G,rpcConfig:V})).filter((e=>e.balance>0n));if(a.length<1)return void ae(new C(`Wallet ${N(Ne.address)} does not have enough funds.`,void 0,b.INSUFFICIENT_BALANCE));a.sort(((e,t)=>Number(t.balance-e.balance)));let i=(await Promise.allSettled(a.map((async e=>({...e,quote:await F({isTestnet:!1,input:B({appId:G,amount:We.toString(),user:Ne.address,recipient:ye,destinationChainId:L,destinationCurrency:U,originChainId:e.chain.id})})}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(i.length<1)return void ae(new C(`Unable to fetch quotes for bridging. Wallet ${N(Ne.address)} does not have enough funds.`,void 0,b.INSUFFICIENT_BALANCE));let n=i.map((({quote:e,balance:t,chain:a})=>({bridgeTx:M(e),balance:t,chain:a,isErc20Quote:!1}))).filter((({bridgeTx:e})=>!!e));if(n.length>1)return void oe(n);let r=n.at(0);r?(ue(!0),Me({data:r.bridgeTx.data,to:r.bridgeTx.to,value:r.bridgeTx.value,chain:r.chain})):ae(new C(`Unable to select bridge option from quotes. Wallet ${N(Ne.address)} does not have enough funds.`,void 0,b.INSUFFICIENT_BALANCE))})().catch(console.error)}),[Ae]),r((()=>{(async()=>{let e,t;if(!Ae||!Ne||ce||pe||!Le)return;me(!0);let a=c({chain:Le.chain,transport:m($(Le.chain,V,G))});try{e=await a.prepareTransactionRequest({account:Ne.address,to:Le.to,chain:Le.chain,data:Le.data,value:BigInt(Le.value??0)})}catch(e){console.error(e),re.length>1&&ne(e.shortMessage??"Something went wrong")}if(e){me(!1),he(!0);try{await Ae.switchChain({id:Le.chain.id})}catch(e){await Ae.addChain({chain:Le.chain}),await Ae.switchChain({id:Le.chain.id})}try{t=await Ae.sendTransaction(e)}catch(e){console.error(e),"TransactionExecutionError"===e.name&&(re.length<1?ae(new C(e.shortMessage,void 0,b.TRANSACTION_FAILURE)):ne(e.shortMessage??"Something went wrong"))}if(t)return await Ae.waitForTransactionReceipt({hash:t}),le?(we("pending"),void Ie(t)):(he(!1),fe(!0),void X({eventName:k,payload:{provider:"external",status:"success",txHash:t,address:Ne.address,chainId:Le.chain.id,chainType:"ethereum",value:Le.value?l(BigInt(Le.value),18):void 0,token:"ETH",destination:ye,destinationClusterName:"mainnet-beta",destinationChainType:"solana",destinationValue:l(We,9),destinationToken:"SOL"}}));he(!1)}else me(!1)})().catch(console.error)}),[Ae,Le]),P({transactionHash:ve,isTestnet:!1,bridgingStatus:je,setBridgingStatus:we,onSuccess({transactionHash:e}){ue(!1),fe(!0),X({eventName:k,payload:{provider:"external",status:"success",txHash:e,address:Ne?.address,chainId:Le?.chain.id,chainType:"ethereum",value:Le?.value?l(BigInt(Le.value),18):void 0,token:"ETH",destination:ye,destinationClusterName:"mainnet-beta",destinationChainType:"solana",destinationValue:l(We,9),destinationToken:"SOL"}})},onFailure({error:e}){ue(!1),ae(e)}}),r((()=>{te&&(J({funding:K?.funding,solanaFundingData:K?.solanaFundingData,sendTransaction:K?.sendTransaction,errorModalData:{error:te,previousScreen:"TransferFromWalletScreen"}}),Y("ErrorScreen",!1))}),[te]),r((()=>{if(!ge)return;let e=setTimeout(z,y);return()=>clearTimeout(e)}),[ge]),ge/*#__PURE__*/)return e(t,{children:[/*#__PURE__*/a(I,{}),/*#__PURE__*/a(p,{}),/*#__PURE__*/e(h,{children:[/*#__PURE__*/a(i,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/a(v,{title:"Success!",description:`You’ve successfully added ${be} SOL to your ${Z.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/a(g,{}),/*#__PURE__*/a(f,{})]});let He=re[se];return re.length>1&&He?/*#__PURE__*/a(O,{displayName:xe,configuredFundingChain:Te,formattedBalance:Ue,fundingAmount:be,fundingCurrency:"SOL",fundingAmountInUsd:qe,options:re,selectedOption:He,isPreparing:ce,isSubmitting:pe,addressToFund:ye,fundingWalletAddress:Ne?.address||"",errorMessage:ie,onSubmit:()=>{K.funding?.amount!==be?async function(){if(Ne&&He)try{let e=await F({isTestnet:!1,input:B({appId:G,amount:We.toString(),user:Ne.address,recipient:ye,destinationChainId:L,destinationCurrency:U,originChainId:He.chain.id})}),t=M(e);if(!t)throw Error("Invalid transaction request");ue(!0),Me({data:t.data,to:t.to,value:t.value,chain:He.chain})}catch(e){console.error(e),ae(new C("Unable to fetch quotes for bridging",e,b.INSUFFICIENT_BALANCE))}}().catch(console.error):Me({to:He.bridgeTx.to,data:He.bridgeTx.data,value:He.bridgeTx.value,chain:He.chain})},onSelect:e=>{e!==se&&(ne(null),de(e))},onAmountChange:Se}):pe&&Ne?/*#__PURE__*/a(_,{walletClientType:Ne?.walletClientType||"unknown",displayName:xe,addressToFund:ye,isBridging:le,isErc20Flow:!1,chainId:"solana",chainName:q(Te),totalPriceInUsd:void 0,totalPriceInNativeCurrency:void 0,gasPriceInUsd:void 0,gasPriceInNativeCurrency:void 0}): /*#__PURE__*/e(t,{children:[/*#__PURE__*/a(I,{}),/*#__PURE__*/a(j,{}),/*#__PURE__*/a("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/a(f,{})]})}};export{Q as AwaitingEvmToSolBridgingScreen,Q as default};