Conecte a carteira Phantom React Typescript
// create phantomProvider.ts file
import {
PublicKey,
Transaction,
} from "@solana/web3.js";
type DisplayEncoding = "utf8" | "hex";
type PhantomEvent = "disconnect" | "connect" | "accountChanged";
type PhantomRequestMethod =
| "connect"
| "disconnect"
| "signTransaction"
| "signAllTransactions"
| "signMessage";
interface ConnectOpts {
onlyIfTrusted: boolean;
}
export interface PhantomProvider {
publicKey: PublicKey | null;
isConnected: boolean | null;
signTransaction: (transaction: Transaction) => Promise<Transaction>;
signAllTransactions: (transactions: Transaction[]) => Promise<Transaction[]>;
signMessage: (
message: Uint8Array | string,
display?: DisplayEncoding
) => Promise<any>;
connect: (opts?: Partial<ConnectOpts>) => Promise<{ publicKey: PublicKey }>;
disconnect: () => Promise<void>;
on: (event: PhantomEvent, handler: (args: any) => void) => void;
request: (method: PhantomRequestMethod, params: any) => Promise<unknown>;
}
//create getProvider.ts file
import { PhantomProvider } from "./PhontomProvider";
export const getProvider = (): PhantomProvider | undefined => {
if ("solana" in window) {
// @ts-ignore
const provider = window.solana as any;
if (provider.isPhantom) return provider as PhantomProvider;
}
window.open("https://phantom.app/", "_blank");
};
//App.tsx
import React, { useState } from "react";
import { PhantomProvider } from "../phantom/PhontomProvider";
import {
connectToPhantomWallet,
handleWalletDisconnect,
} from "../services/handleWallet";
const App: React.FC = () => {
const [provider, setProvider] = useState<PhantomProvider | undefined>(
undefined
);
const [walletKey, setWalletKey] = useState<PhantomProvider | undefined>(
undefined
);
return (
<div>
{!provider && !walletKey ? (
<button
onClick={() => {
connectToPhantomWallet(setProvider, setWalletKey);
}}
>
Connect Wallet
</button>
) : (
<button
onClick={() => {
handleWalletDisconnect(setProvider, setWalletKey);
}}
>
Disconnect Wallet
</button>
)}
</div>
);
};
export default App;
sushangmi55