UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

2 lines (1 loc) 8.55 kB
import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import n from"@heroicons/react/24/outline/CheckCircleIcon";import{useState as o,useEffect as r}from"react";import{formatWalletAddress as s}from"@privy-io/js-sdk-core";import{B as i,P as l}from"./ModalHeader-BnVmXtvG.mjs";import{b as m,c,R as u,e as d}from"./Layouts-BlFm53ED.mjs";import{C as p}from"./ScreenHeader-CHmc4-Lu.mjs";import{t as f}from"./FundWalletMethodHeader-Cb-ACySl.mjs";import{I as g}from"./InjectedWalletIcon-DLcYOGDj.mjs";import{N as h}from"./index-Dq_xe9dz.mjs";import{L as I,V as v}from"./Value-tcJV9e0L.mjs";import{a as w,R as S}from"./Row-C9vrS4Zi.mjs";import{u as j,t as y}from"./context-DLtU3JQy.mjs";import{u as C,a as L,b as x}from"./internal-context-Z-fyxadS.mjs";import{a as k}from"./privy-context-DrMxzgOR.mjs";import{u as F,g as U}from"./useWallets-z8NFrORr.mjs";import{u as T}from"./useGetTokenPrice-LPJMl6JV.mjs";import{O as A}from"./analytics-mkkvFRju.mjs";import{getTransferSolInstruction as W}from"@solana-program/system";import{pipe as b,createTransactionMessage as P,setTransactionMessageFeePayerSigner as D,setTransactionMessageLifetimeUsingBlockhash as N,appendTransactionMessageInstruction as O,compileTransaction as E,getTransactionEncoder as M}from"@solana/kit";import{findAssociatedTokenPda as B,getCreateAssociatedTokenIdempotentInstruction as $,getTransferInstruction as R}from"@solana-program/token";import{T as H,L as G,g as V}from"./getFormattedUsdFromLamports-B6EqSEho.mjs";import{g as q}from"./getUsdcMintAddress-DFI1hv05.mjs";import{u as _,f as z,s as Q,w as X}from"./useSolanaRpcClient-71aYSqHX.mjs";import{g as Y}from"./getChainName-DjpPdUSc.mjs";import{H as J}from"./use-export-wallet-_wu5ex5t.mjs";import"styled-components";import"./useActiveWallet-CvP7iYvj.mjs";import"zustand";import"react-device-detect";import"./events-context-CI0iqAXA.mjs";import"viem";import"viem/utils";import"./useWallets-BzNCTucF.mjs";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"@heroicons/react/24/outline/WalletIcon";import"./LoadingSkeleton-U6-3yFwI.mjs";import"tinycolor2";import"ofetch";import"@privy-io/are-addresses-equal";import"./usePrivy-C_sY2Duk.mjs";import"eventemitter3";import"@scure/base";import"./use-sign-with-user-signer-Do5Oi_rb.mjs";import"./useGetSolPrice-DwwjjGbd.mjs";function K({rows:a}){/*#__PURE__*/return e(w,{children:a.filter((e=>!!e)).map(((a,n)=>null!=a.value||a.isLoading?/*#__PURE__*/t(S,{children:[/*#__PURE__*/e(I,{children:a.label}),/*#__PURE__*/e(v,{$isLoading:a.isLoading,children:a.value})]},n):null))})}function Z(e){return BigInt(Math.floor(1e9*parseFloat(e)))}function ee(e){return+te.format(parseFloat(e.toString())/1e9)}let te=Intl.NumberFormat(void 0,{maximumFractionDigits:8});async function ae({tx:e,solanaClient:t,amount:a,asset:n,tokenPrice:o}){if(!e)return null;if("SOL"===n&&o){let n=Z(a),r=V(n,o),s=await z({solanaClient:t,tx:e});return{amountInUsd:r,feeInUsd:o?V(s,o):void 0,totalInUsd:V(n+s,o)}}if("USDC"===n&&o){let n="$"+a,r=await z({solanaClient:t,tx:e}),s=function(e,t){let a=parseFloat(e.toString())/G*t;return a<.01?0:a}(r,o);return{amountInUsd:n,feeInUsd:V(r,o),totalInUsd:"$"+(parseFloat(a)+s).toFixed(2)}}if("SOL"===n){let n=Z(a),o=await z({solanaClient:t,tx:e});return{amountInSol:a+" SOL",feeInSol:ee(o)+" SOL",totalInSol:ee(n+o)+" SOL"}}return{amountInUsdc:a+" USDC",feeInSol:ee(await z({solanaClient:t,tx:e}))+" SOL"}}const ne={component:function(){let I=j(),{closePrivyModal:v,createAnalyticsEvent:w}=C(),{data:S,setModalData:G,navigate:z}=k(),{wallets:ee}=F(),[te,ne]=o("preparing"),[oe,re]=o(),[se,ie]=o(),[le,me]=o();if(!S?.solanaFundingData)throw Error("Funding config is missing");if(!S.solanaFundingData.sourceWalletData)throw Error("Funding config is missing source wallet data");let{amount:ce,asset:ue,chain:de,sourceWalletData:pe,destinationAddress:fe,afterSuccessScreen:ge}=S.solanaFundingData,he=ee.find((e=>e.address===pe.address&&J(pe.walletClientType)===J(e.standardWallet.name))),Ie=_()(de),{tokenPrice:ve,isTokenPriceLoading:we}=T("solana");return r((()=>{if("preparing"!==te||we||!he)return;let e="SOL"===ue?Z(ce):function(e){return BigInt(Math.floor(1e6*parseFloat(e)))}(ce);ie({amount:("SOL"===ue&&ve?V(e,ve):ce)??ce}),("SOL"===ue?async function({solanaClient:e,source:t,destination:a,amountInLamports:n}){let{value:o}=await e.rpc.getLatestBlockhash().send(),r={address:t},s=b(P({version:0}),(e=>D(r,e)),(e=>N(o,e)),(e=>O(W({amount:n,source:r,destination:a}),e)),(e=>E(e)));return new Uint8Array(M().encode(s))}({solanaClient:Ie,source:he.address,destination:fe,amountInLamports:e}):async function({solanaClient:e,source:t,destination:a,amountInBaseUnits:n}){let o=q(e.chain),{value:r}=await e.rpc.getLatestBlockhash().send(),s={address:t},[i]=await B({mint:o,owner:t,tokenProgram:H}),[l]=await B({mint:o,owner:a,tokenProgram:H}),[m,c]=await Promise.all([e.rpc.getAccountInfo(i,{commitment:"confirmed",encoding:"jsonParsed"}).send().catch((()=>null)),e.rpc.getAccountInfo(l,{commitment:"confirmed",encoding:"jsonParsed"}).send().catch((()=>null))]);if(!m?.value)throw Error(`Source token account does not exist for address: ${t}`);let u=$({payer:s,ata:l,owner:a,mint:o}),d=b(P({version:0}),(e=>D(s,e)),(e=>N(r,e)),(e=>c?.value?e:O(u,e)),(e=>O(R({source:i,destination:l,authority:s,amount:n}),e)),(e=>E(e)));return new Uint8Array(M().encode(d))}({solanaClient:Ie,source:he.address,destination:fe,amountInBaseUnits:e})).then(re).catch((e=>{ne("error"),me(e)}))}),[te,ce,ue,de,he,fe,we,ve]),r((()=>{"preparing"===te&&oe&&ae({tx:oe,solanaClient:Ie,amount:ce,asset:ue,tokenPrice:ve}).then((e=>{ne("loaded"),ie({amount:e?.amountInUsd??e?.amountInUsdc??e?.amountInSol??ce,fee:e?.feeInUsd??e?.feeInSol,total:e?.totalInUsd??e?.totalInSol})})).catch((e=>{ne("error"),me(e)}))}),[oe,ce,ue,te,ve]),r((()=>{"error"===te&&le&&(G({errorModalData:{error:le,previousScreen:"FundSolWalletWithExternalSolanaWallet"},solanaFundingData:S.solanaFundingData}),z("ErrorScreen",!1))}),[te,z]),r((()=>{if("success"!==te)return;let e=setTimeout(ge?()=>z(ge):v,y);return()=>clearTimeout(e)}),[te]),/*#__PURE__*/t(a,"success"===te?{children:[/*#__PURE__*/e(f,{}),/*#__PURE__*/e(m,{}),/*#__PURE__*/t(c,{children:[/*#__PURE__*/e(n,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e(p,{title:"Success!",description:`You’ve successfully added ${ce} ${ue} to your ${I.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/e(u,{}),/*#__PURE__*/e(i,{})]}:"preparing"===te||"loaded"===te||"sending"===te?{children:[/*#__PURE__*/e(f,{}),/*#__PURE__*/e(d,{style:{marginTop:"16px"},children:/*#__PURE__*/e(g,{icon:he?.standardWallet.icon,name:he?.standardWallet.name})}),/*#__PURE__*/e(p,{style:{marginTop:"8px",marginBottom:"12px"},title:"sending"===te&&he?`Confirming with ${he.standardWallet.name}`:"Confirm transaction"}),/*#__PURE__*/e(K,{rows:[{label:"Source",value:s(pe.address)},{label:"Destination",value:s(fe)},{label:"Network",value:Y(de)},{label:"Amount",value:se?.amount,isLoading:"preparing"===te},{label:"Estimated fee",value:se?.fee,isLoading:"preparing"===te},{label:"Total",value:se?.total,isLoading:"preparing"===te}]}),/*#__PURE__*/e(l,{style:{marginTop:"1rem"},loading:"preparing"===te||"sending"===te,onClick:function(){"loaded"===te&&oe&&he&&(ne("sending"),async function({transaction:e,chain:t,sourceWallet:a,solanaClient:n}){let{hasFunds:o}=await Q({solanaClient:n,tx:e});if(!o)throw new L(`Wallet ${s(a.address)} does not have enough funds.`,void 0,x.INSUFFICIENT_BALANCE);let r=U((await a.signAndSendTransaction({transaction:e,chain:t}).catch((e=>{throw new L("Transaction was rejected by the user",e,x.TRANSACTION_FAILURE)}))).signature);return await X({rpcSubscriptions:n.rpcSubscriptions,signature:r,timeout:2e4}),r}({solanaClient:Ie,transaction:oe,chain:de,sourceWallet:he}).then((e=>{ne("success"),w({eventName:A,payload:{provider:"external",status:"success",txHash:e,address:he.address,value:ce,chainType:"solana",clusterName:de,token:ue,destinationAddress:fe,destinationValue:ce,destinationChainType:"solana",destinationClusterName:de,destinationToken:ue}})})).catch((e=>{ne("error"),me(e)})))},children:"Confirm"}),/*#__PURE__*/e(i,{})]}:{children:[/*#__PURE__*/e(f,{}),/*#__PURE__*/e(h,{}),/*#__PURE__*/e("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/e(i,{})]})}};export{ne as FundSolWalletWithExternalSolanaWallet,ne as default};