Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add examples of how to use the React component #365

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions apps/nextjs-example/src/examples/ChangeNetworkDemo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import React from 'react';
import { useWallet } from '@aptos-labs/wallet-adapter-react';
import { Network } from '@aptos-labs/ts-sdk';

const ChangeNetworkDemo = () => {
const { network, changeNetwork, wallet } = useWallet();
// Update this with a non-manual check to verify whether the network change is a supported feature.
// Or have error handling if a network change is attempted for a wallet that does not support the feature.
const isNetworkChangeSupported = wallet?.name === "Nightly";

const isValidNetworkName = () => {
return network && Object.values<string>(Network).includes(network.name);
};

return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
<h4 style={{ fontSize: '1.25rem', fontWeight: '500' }}>Network Info</h4>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: '8px' }}>
<div><strong>Network name</strong></div>
<div>
<span style={{ color: isValidNetworkName() ? 'green' : 'red' }}>
{network?.name ?? 'Not Present'}
</span>
{` (Expected: ${Object.values<string>(Network).join(', ')})`}
</div>
<div><strong>URL</strong></div>
<div>
{network?.url ? (
<a href={network.url} target="_blank" rel="noreferrer" style={{ color: 'blue' }}>
{network.url}
</a>
) : (
'Not Present'
)}
</div>
<div><strong>Chain ID</strong></div>
<div>{network?.chainId ?? 'Not Present'}</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
<h4 style={{ fontSize: '1.25rem', fontWeight: '500' }}>Change Network</h4>
<div style={{ display: 'flex', gap: '16px' }}>
<label>
<input
type="radio"
name="network"
value={Network.DEVNET}
checked={network?.name === Network.DEVNET}
onChange={() => changeNetwork(Network.DEVNET)}
disabled={!isNetworkChangeSupported}
/>
Devnet
</label>
<label>
<input
type="radio"
name="network"
value={Network.TESTNET}
checked={network?.name === Network.TESTNET}
onChange={() => changeNetwork(Network.TESTNET)}
disabled={!isNetworkChangeSupported}
/>
Testnet
</label>
<label>
<input
type="radio"
name="network"
value={Network.MAINNET}
checked={network?.name === Network.MAINNET}
onChange={() => changeNetwork(Network.MAINNET)}
disabled={!isNetworkChangeSupported}
/>
Mainnet
</label>
</div>
{!isNetworkChangeSupported && (
<div style={{ fontSize: '0.875rem', color: 'red' }}>
* {wallet?.name ?? 'This wallet'} does not support network change requests
</div>
)}
</div>
</div>
);
};

export default ChangeNetworkDemo;
3 changes: 3 additions & 0 deletions apps/nextjs-example/src/examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This folder contains examples of how to use each of the AIP-62 functions via the aptos-wallet-adapter React library.

You can try out the examples by adding them to the [`page.tsx`](../app/page.tsx) file then building the demo app with the instructions in the demo app [README.md](../../README.md).
38 changes: 38 additions & 0 deletions apps/nextjs-example/src/examples/SignAndSubmit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import React from 'react';
import { useWallet } from '@aptos-labs/wallet-adapter-react';
import { Aptos, AptosConfig, Network } from '@aptos-labs/ts-sdk';

const config = new AptosConfig({ network: Network.TESTNET });
const aptos = new Aptos(config);

const SignAndSubmit = () => {
const { account, signAndSubmitTransaction } = useWallet();

const onSignAndSubmitTransaction = async () => {
if(account == null) {
throw new Error("Unable to find account to sign transaction")
}
const response = await signAndSubmitTransaction({
sender: account.address,
data: {
function: "0x1::coin::transfer",
typeArguments: ["0x1::aptos_coin::AptosCoin"],
functionArguments: [account.address, 1],
},
});
// if you want to wait for transaction
try {
await aptos.waitForTransaction({ transactionHash: response.hash });
} catch (error) {
console.error(error);
}
};

return (
<button onClick={onSignAndSubmitTransaction}>
Sign and submit transaction
</button>
);
};

export default SignAndSubmit;
86 changes: 86 additions & 0 deletions apps/nextjs-example/src/examples/SignMessageDemo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import React, { useState } from 'react';
import { useWallet } from '@aptos-labs/wallet-adapter-react';

const SignMessageDemo = () => {
const { signMessage, signMessageAndVerify, connected, account } = useWallet();
const [message, setMessage] = useState<string>('');
const [nonce, setNonce] = useState<string>('');
const [signedMessage, setSignedMessage] = useState<any>(null);
const [verificationResult, setVerificationResult] = useState<boolean | null>(null);
const [error, setError] = useState<string | null>(null);

const handleSignMessage = async () => {
setError(null);
try {
const response = await signMessage({ message, nonce });
setSignedMessage(response);
} catch (err: any) {
setError(`Failed to sign message: ${err.message}`);
}
};

const handleVerifyMessage = async () => {
setError(null);
try {
const result = await signMessageAndVerify({ message, nonce });
setVerificationResult(result);
} catch (err: any) {
setError(`Failed to verify message: ${err.message}`);
}
};

return (
<div>
<h1>Aptos Sign and Verify Message</h1>
<div>
{connected ? (
<div>
<p>Connected to: {account?.address}</p>
<div className="flex flex-col gap-4">
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Enter your message here"
className="border rounded p-2"
/>
<input
type="text"
value={nonce}
onChange={(e) => setNonce(e.target.value)}
placeholder="Enter nonce (random string) here"
className="border rounded p-2 mt-2"
/>
<button onClick={handleSignMessage} className="bg-blue-500 text-white rounded p-2 mt-2">
Sign Message
</button>
{signedMessage && (
<div>
<h4>Signed Message</h4>
<pre>{JSON.stringify(signedMessage, null, 2)}</pre>
<button onClick={handleVerifyMessage} className="bg-green-500 text-white rounded p-2 mt-2">
Verify Message
</button>
</div>
)}
{verificationResult !== null && (
<div>
<h4>Verification Result</h4>
<p>{verificationResult ? 'Message is verified!' : 'Failed to verify message.'}</p>
</div>
)}
{error && (
<div className="text-red-600">
<p>{error}</p>
</div>
)}
</div>
</div>
) : (
<p>Please connect your wallet to sign and verify messages.</p>
)}
</div>
</div>
);
};

export default SignMessageDemo;
42 changes: 42 additions & 0 deletions apps/nextjs-example/src/examples/WalletConnectDemo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React from 'react';
import { WalletName, useWallet } from '@aptos-labs/wallet-adapter-react';

const WalletConnectDemo = () => {
const { connect, disconnect, account, connected } = useWallet();

const handleConnect = async () => {
try {
await connect("Petra" as WalletName<"Petra">); // Change to the desired wallet name
console.log('Connected to wallet:', account);
} catch (error) {
console.error('Failed to connect to wallet:', error);
}
};

const handleDisconnect = async () => {
try {
await disconnect();
console.log('Disconnected from wallet');
} catch (error) {
console.error('Failed to disconnect from wallet:', error);
}
};

return (
<div>
<h1>Aptos Wallet Connection</h1>
<div>
{connected ? (
<div>
<p>Connected to: {account?.address}</p>
<button onClick={handleDisconnect}>Disconnect</button>
</div>
) : (
<button onClick={handleConnect}>Connect Wallet</button>
)}
</div>
</div>
);
};

export default WalletConnectDemo;