Wallet

Overview

As discussed in the "Write Data" section, users need a wallet to sign transactions. Therefore, it's essential to integrate a wallet component into your frontend.

We recommend using @aptos-labs/wallet-adapter-react for implementing wallet functionality.


Aptogotchi Example

There are 3 steps for integrating Wallet functionality into your Aptos dApp.

1. Set up a WalletProvider.

  • Import the AptosWalletAdapterProvider, developed and maintained by the Aptos Labs team
  • Add support for Aptos wallets: in this case, we will only support PetraWallet by default

Source Code


import { AptosWalletAdapterProvider } from "@aptos-labs/wallet-adapter-react";
import { PetraWallet } from "petra-plugin-wallet-adapter";
import { PropsWithChildren } from "react";
const wallets = [new PetraWallet()];
export function WalletProvider({ children }: PropsWithChildren) {
return (
<AptosWalletAdapterProvider plugins={wallets} autoConnect={true}>
{children}
</AptosWalletAdapterProvider>
);
}


2. Create a <WalletButtons> component that users can interact with.

Source Code


import {
useWallet,
WalletReadyState,
Wallet,
WalletName,
} from "@aptos-labs/wallet-adapter-react";
...
export const WalletButtons = () => {
const { wallets, connected, disconnect, isLoading } = useWallet();
...
return <WalletView wallet={wallets[0]} />;
};
const WalletView = ({ wallet }: { wallet: Wallet }) => {
const { connect } = useWallet();
const isWalletReady =
wallet.readyState === WalletReadyState.Installed ||
wallet.readyState === WalletReadyState.Loadable;
...
const onWalletConnectRequest = async (walletName: WalletName) => {
try {
await connect(walletName);
} catch (error) {
console.warn(error);
window.alert("Failed to connect wallet");
}
};
...
return (
<button
className={cn(
buttonStyles,
isWalletReady ? "hover:bg-blue-700" : "opacity-50 cursor-not-allowed"
)}
disabled={!isWalletReady}
key={wallet.name}
onClick={() => onWalletConnectRequest(wallet.name)}
>
Connect Wallet
</button>
);
};


3. Plug <WalletButtons> component into the root of your application. (or where you want the "Connect Wallet" button to appear).

Source Code


function Header() {
return (
<header className="sticky top-0 z-10 flex justify-between items-center px-6 py-4 bg-gradient-to-r from-orange-300 via-orange-400 to-red-400 shadow-md w-full gap-2">
<h1 className="text-2xl">Aptogotchi</h1>
<WalletButtons />
</header>
);
}