@privy-io/react-auth
Version:
React client for the Privy Auth API
3 lines (2 loc) • 9.68 kB
JavaScript
"use strict";var e=require("react/jsx-runtime"),t=require("@heroicons/react/24/outline/CheckCircleIcon"),a=require("react"),n=require("@privy-io/js-sdk-core"),r=require("./ModalHeader-C5Wuo3-1.js"),s=require("./Layouts-D3TOcPhm.js"),o=require("./ScreenHeader-CgYJ5Fmg.js"),i=require("./FundWalletMethodHeader-BTGxq_KO.js"),l=require("./InjectedWalletIcon-UY3nMvZo.js"),u=require("./index-ByFhjjzH.js"),c=require("./Value-mhPsfsxe.js"),d=require("./Row-CMqYn75Q.js"),m=require("./context-Cg3IEi80.js"),g=require("./internal-context-BJv4f_bO.js"),p=require("./privy-context-CrM9_s6G.js"),f=require("./useWallets-DX7GoSc-.js"),h=require("./useGetTokenPrice-CSWuvKuF.js"),S=require("./analytics-C6C_4JmG.js"),j=require("@solana-program/system"),I=require("@solana/kit"),T=require("@solana-program/token"),x=require("./getFormattedUsdFromLamports-Mu2fqwL2.js"),q=require("./getUsdcMintAddress-REYZSOb9.js"),C=require("./useSolanaRpcClient-DuOWyD1p.js"),F=require("./getChainName-C4rO8-3n.js"),v=require("./use-export-wallet-_EIyxyle.js");function y(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("styled-components"),require("./useActiveWallet-BfMD5hzE.js"),require("zustand"),require("react-device-detect"),require("./events-context-Di6--rDg.js"),require("viem"),require("viem/utils"),require("./useWallets-dikDynAG.js"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@heroicons/react/24/outline/WalletIcon"),require("./LoadingSkeleton-BoyADunQ.js"),require("tinycolor2"),require("ofetch"),require("@privy-io/are-addresses-equal"),require("./usePrivy-C-Rab7yP.js"),require("eventemitter3"),require("@scure/base"),require("./use-sign-with-user-signer-Cu_6Bx7m.js"),require("./useGetSolPrice-Ca32VAbF.js");var w=/*#__PURE__*/y(t);function L({rows:t}){/*#__PURE__*/return e.jsx(d.Rows,{children:t.filter((e=>!!e)).map(((t,a)=>null!=t.value||t.isLoading?/*#__PURE__*/e.jsxs(d.Row,{children:[/*#__PURE__*/e.jsx(c.LabelSm,{children:t.label}),/*#__PURE__*/e.jsx(c.Value,{$isLoading:t.isLoading,children:t.value})]},a):null))})}function E(e){return BigInt(Math.floor(1e9*parseFloat(e)))}function A(e){return+U.format(parseFloat(e.toString())/1e9)}let U=Intl.NumberFormat(void 0,{maximumFractionDigits:8});async function P({tx:e,solanaClient:t,amount:a,asset:n,tokenPrice:r}){if(!e)return null;if("SOL"===n&&r){let n=E(a),s=x.getFormattedUsdFromLamports(n,r),o=await C.fetchTransactionEstimatedFees({solanaClient:t,tx:e});return{amountInUsd:s,feeInUsd:r?x.getFormattedUsdFromLamports(o,r):void 0,totalInUsd:x.getFormattedUsdFromLamports(n+o,r)}}if("USDC"===n&&r){let n="$"+a,s=await C.fetchTransactionEstimatedFees({solanaClient:t,tx:e}),o=function(e,t){let a=parseFloat(e.toString())/x.LAMPORTS_PER_SOL*t;return a<.01?0:a}(s,r);return{amountInUsd:n,feeInUsd:x.getFormattedUsdFromLamports(s,r),totalInUsd:"$"+(parseFloat(a)+o).toFixed(2)}}if("SOL"===n){let n=E(a),r=await C.fetchTransactionEstimatedFees({solanaClient:t,tx:e});return{amountInSol:a+" SOL",feeInSol:A(r)+" SOL",totalInSol:A(n+r)+" SOL"}}return{amountInUsdc:a+" USDC",feeInSol:A(await C.fetchTransactionEstimatedFees({solanaClient:t,tx:e}))+" SOL"}}const k={component:function(){let t=m.useAppConfig(),{closePrivyModal:c,createAnalyticsEvent:d}=g.usePrivyInternal(),{data:y,setModalData:A,navigate:U}=p.usePrivyModal(),{wallets:k}=f.useWallets(),[W,M]=a.useState("preparing"),[b,N]=a.useState(),[O,R]=a.useState(),[_,D]=a.useState();if(!y?.solanaFundingData)throw Error("Funding config is missing");if(!y.solanaFundingData.sourceWalletData)throw Error("Funding config is missing source wallet data");let{amount:B,asset:$,chain:G,sourceWalletData:H,destinationAddress:V,afterSuccessScreen:K}=y.solanaFundingData,X=k.find((e=>e.address===H.address&&v.toSolanaWalletClientType(H.walletClientType)===v.toSolanaWalletClientType(e.standardWallet.name))),Y=C.useSolanaRpcClient()(G),{tokenPrice:z,isTokenPriceLoading:Q}=h.useGetTokenPrice("solana");return a.useEffect((()=>{if("preparing"!==W||Q||!X)return;let e="SOL"===$?E(B):function(e){return BigInt(Math.floor(1e6*parseFloat(e)))}(B);R({amount:("SOL"===$&&z?x.getFormattedUsdFromLamports(e,z):B)??B}),("SOL"===$?async function({solanaClient:e,source:t,destination:a,amountInLamports:n}){let{value:r}=await e.rpc.getLatestBlockhash().send(),s={address:t},o=I.pipe(I.createTransactionMessage({version:0}),(e=>I.setTransactionMessageFeePayerSigner(s,e)),(e=>I.setTransactionMessageLifetimeUsingBlockhash(r,e)),(e=>I.appendTransactionMessageInstruction(j.getTransferSolInstruction({amount:n,source:s,destination:a}),e)),(e=>I.compileTransaction(e)));return new Uint8Array(I.getTransactionEncoder().encode(o))}({solanaClient:Y,source:X.address,destination:V,amountInLamports:e}):async function({solanaClient:e,source:t,destination:a,amountInBaseUnits:n}){let r=q.getUsdcMintAddress(e.chain),{value:s}=await e.rpc.getLatestBlockhash().send(),o={address:t},[i]=await T.findAssociatedTokenPda({mint:r,owner:t,tokenProgram:x.TOKEN_PROGRAM_ID}),[l]=await T.findAssociatedTokenPda({mint:r,owner:a,tokenProgram:x.TOKEN_PROGRAM_ID}),[u,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(!u?.value)throw Error(`Source token account does not exist for address: ${t}`);let d=T.getCreateAssociatedTokenIdempotentInstruction({payer:o,ata:l,owner:a,mint:r}),m=I.pipe(I.createTransactionMessage({version:0}),(e=>I.setTransactionMessageFeePayerSigner(o,e)),(e=>I.setTransactionMessageLifetimeUsingBlockhash(s,e)),(e=>c?.value?e:I.appendTransactionMessageInstruction(d,e)),(e=>I.appendTransactionMessageInstruction(T.getTransferInstruction({source:i,destination:l,authority:o,amount:n}),e)),(e=>I.compileTransaction(e)));return new Uint8Array(I.getTransactionEncoder().encode(m))}({solanaClient:Y,source:X.address,destination:V,amountInBaseUnits:e})).then(N).catch((e=>{M("error"),D(e)}))}),[W,B,$,G,X,V,Q,z]),a.useEffect((()=>{"preparing"===W&&b&&P({tx:b,solanaClient:Y,amount:B,asset:$,tokenPrice:z}).then((e=>{M("loaded"),R({amount:e?.amountInUsd??e?.amountInUsdc??e?.amountInSol??B,fee:e?.feeInUsd??e?.feeInSol,total:e?.totalInUsd??e?.totalInSol})})).catch((e=>{M("error"),D(e)}))}),[b,B,$,W,z]),a.useEffect((()=>{"error"===W&&_&&(A({errorModalData:{error:_,previousScreen:"FundSolWalletWithExternalSolanaWallet"},solanaFundingData:y.solanaFundingData}),U("ErrorScreen",!1))}),[W,U]),a.useEffect((()=>{if("success"!==W)return;let e=setTimeout(K?()=>U(K):c,m.DEFAULT_SUCCESS_SCREEN_EXTRA_LONG_DURATION_MS);return()=>clearTimeout(e)}),[W]),"success"===W?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(i.t,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(s.CenteredItemWithGap,{children:[/*#__PURE__*/e.jsx(w.default,{color:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:"Success!",description:`You’ve successfully added ${B} ${$} to your ${t.name} wallet. It may take a minute before the funds are available to use.`})]}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(r.BlobbyFooter,{})]}):"preparing"===W||"loaded"===W||"sending"===W?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(i.t,{}),/*#__PURE__*/e.jsx(s.CenteredItem,{style:{marginTop:"16px"},children:/*#__PURE__*/e.jsx(l.InjectedWalletIcon,{icon:X?.standardWallet.icon,name:X?.standardWallet.name})}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{style:{marginTop:"8px",marginBottom:"12px"},title:"sending"===W&&X?`Confirming with ${X.standardWallet.name}`:"Confirm transaction"}),/*#__PURE__*/e.jsx(L,{rows:[{label:"Source",value:n.formatWalletAddress(H.address)},{label:"Destination",value:n.formatWalletAddress(V)},{label:"Network",value:F.getChainName(G)},{label:"Amount",value:O?.amount,isLoading:"preparing"===W},{label:"Estimated fee",value:O?.fee,isLoading:"preparing"===W},{label:"Total",value:O?.total,isLoading:"preparing"===W}]}),/*#__PURE__*/e.jsx(r.PrimaryButton,{style:{marginTop:"1rem"},loading:"preparing"===W||"sending"===W,onClick:function(){"loaded"===W&&b&&X&&(M("sending"),async function({transaction:e,chain:t,sourceWallet:a,solanaClient:r}){let{hasFunds:s}=await C.simulateTransaction({solanaClient:r,tx:e});if(!s)throw new g.PrivyClientError(`Wallet ${n.formatWalletAddress(a.address)} does not have enough funds.`,void 0,g.PrivyErrorCode.INSUFFICIENT_BALANCE);let o=f.getAddressFromBuffer((await a.signAndSendTransaction({transaction:e,chain:t}).catch((e=>{throw new g.PrivyClientError("Transaction was rejected by the user",e,g.PrivyErrorCode.TRANSACTION_FAILURE)}))).signature);return await C.waitForSignatureConfirmation({rpcSubscriptions:r.rpcSubscriptions,signature:o,timeout:2e4}),o}({solanaClient:Y,transaction:b,chain:G,sourceWallet:X}).then((e=>{M("success"),d({eventName:S.ON_RAMP_COMPLETE_ANALYTICS_EVENT,payload:{provider:"external",status:"success",txHash:e,address:X.address,value:B,chainType:"solana",clusterName:G,token:$,destinationAddress:V,destinationValue:B,destinationChainType:"solana",destinationClusterName:G,destinationToken:$}})})).catch((e=>{M("error"),D(e)})))},children:"Confirm"}),/*#__PURE__*/e.jsx(r.BlobbyFooter,{})]}):
/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(i.t,{}),/*#__PURE__*/e.jsx(u.NeutralSpinner,{}),/*#__PURE__*/e.jsx("div",{style:{marginTop:"1rem"}}),/*#__PURE__*/e.jsx(r.BlobbyFooter,{})]})}};exports.FundSolWalletWithExternalSolanaWallet=k,exports.default=k;