Skip to content

Commit

Permalink
Merge pull request #14 from civicteam/TECH-1052__improved_web3_example
Browse files Browse the repository at this point in the history
TECH-1052 - Improved web3 example
  • Loading branch information
kevinhcolgan authored Dec 5, 2024
2 parents dd7ae87 + 0830ae8 commit d74f121
Showing 1 changed file with 13 additions and 19 deletions.
32 changes: 13 additions & 19 deletions packages/civic-auth-web3/wagmi/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import {
createConfig,
useAccount,
useConnect,
useSendTransaction,
http,
useBalance,
} from 'wagmi';
import { embeddedWallet, userHasWallet } from '@civic/auth-web3';
import { CivicAuthProvider, UserButton, useUser } from '@civic/auth-web3/react';
Expand Down Expand Up @@ -44,10 +44,12 @@ const App = () => {
// Separate component for the app content that needs access to hooks
const AppContent = () => {
const userContext = useUser();

const { connect, connectors } = useConnect();
const { isConnected } = useAccount();
const { sendTransaction } = useSendTransaction();
const balance = useBalance({
address: userHasWallet(userContext)
? userContext.walletAddress as `0x${string}` : undefined,
});

// A function to connect an existing civic embedded wallet
const connectExistingWallet = () => {
Expand All @@ -60,21 +62,10 @@ const AppContent = () => {
const createWallet = () => {
if (userContext.user && !userHasWallet(userContext)) {
// Once the wallet is created, we can connect it straight away
return userContext.createWallet().then(() => new Promise<void>((resolve) => {
setTimeout(() => {
connectExistingWallet();
resolve();
}, 200);
}));
return userContext.createWallet().then(connectExistingWallet);
}
};

// A reference implementation of a function to send a transaction
const sendTx = () => sendTransaction({
to: '0x...',
value: 1000n,
});

return (
<>
<UserButton />
Expand All @@ -86,10 +77,13 @@ const AppContent = () => {
{userHasWallet(userContext) &&
<>
<p>Wallet address: {userContext.walletAddress}</p>
{isConnected ? (
<button onClick={sendTx}>Send Transaction</button>
) : (
<button onClick={connectExistingWallet}>Connect Wallet</button>
<p>Balance: {
balance?.data
? `${(BigInt(balance.data.value) / BigInt(1e18)).toString()} ${balance.data.symbol}`
: 'Loading...'
}</p>
{isConnected ? <p>Wallet is connected</p> : (
<button onClick={connectExistingWallet}>Connect Wallet</button>
)}
</>
}
Expand Down

0 comments on commit d74f121

Please sign in to comment.