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