### Quick Start: Connect and Sign Messages (TypeScript) Source: https://docs.phantom.com/sdks/browser-sdk Demonstrates a quick start guide for using the Phantom Browser SDK. It shows how to connect to the Phantom browser extension, retrieve Solana and Ethereum addresses, and then sign messages using chain-specific methods. ```typescript import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; // Connect to Phantom browser extension const sdk = new BrowserSDK({ providers: ["injected"], // Only allow browser extension addressTypes: [AddressType.solana, AddressType.ethereum], }); const { addresses } = await sdk.connect({ provider: "injected" }); console.log("Connected addresses:", addresses); // Chain-specific operations const message = "Hello from Phantom!"; const solanaSignature = await sdk.solana.signMessage(message); // Encode the message as hex for EVM const encoded = "0x" + Buffer.from(message, "utf8").toString("hex"); const ethSignature = await sdk.ethereum.signPersonalMessage(encoded, addresses[1].address); ``` -------------------------------- ### React Eager Connection Example Source: https://docs.phantom.com/solana/establishing-a-connection Demonstrates how to implement eager connection in a React component using the `useEffect` hook. It attempts to connect to Phantom only if trusted, handling both successful connections and potential failures. ```javascript import { useEffect } from "react"; useEffect(() => { // Will either automatically connect to Phantom, or do nothing. provider.connect({ onlyIfTrusted: true }) .then(({ publicKey }) => { // Handle successful eager connection }) .catch(() => { // Handle connection failure as usual }) }, []); ``` -------------------------------- ### Connect Method Example (React Native) Source: https://docs.phantom.com/phantom-deeplinks/provider-methods/connect An example implementation of the connect method, showing how to initiate a connection with Phantom. This example is taken from the official Phantom deep link demo application. ```typescript connect() { const phantomAppUrl = 'your_app_url'; // Replace with your app's URL const dappEncryptionPublicKey = 'your_public_key'; // Replace with your app's public key const redirectLink = 'your_redirect_link'; // Replace with your redirect URI const cluster = 'devnet'; // Optional: 'mainnet-beta', 'testnet', or 'devnet' const connectUrl = `https://phantom.app/ul/v1/connect?app_url=${encodeURIComponent(phantomAppUrl)}&dapp_encryption_public_key=${encodeURIComponent(dappEncryptionPublicKey)}&redirect_link=${encodeURIComponent(redirectLink)}&cluster=${cluster}`; // In a React Native app, you would typically use Linking.openURL(connectUrl) // For web, you might redirect the user or open a new window. console.log('Opening connection URL:', connectUrl); // Example: window.location.href = connectUrl; } ``` -------------------------------- ### Install Dependencies with npm Source: https://docs.phantom.com/sdks/guides/wallet-authentication-with-jwts Installs the necessary packages for the Phantom React SDK and axios. This command should be run in the project's root directory. ```bash npm install @phantom/react-sdk axios ``` -------------------------------- ### Solana Transaction Examples Source: https://docs.phantom.com/sdks/browser-sdk/sign-and-send-transaction Examples of signing and sending Solana transactions using both `@solana/web3.js` and `@solana/kit` libraries. ```APIDOC ## Solana Transaction Examples ### Description Examples demonstrating how to create and send Solana transactions using different libraries with the Phantom Browser SDK. #### Solana with `@solana/web3.js` ```typescript import { VersionedTransaction, TransactionMessage, SystemProgram, PublicKey, LAMPORTS_PER_SOL, Connection, } from "@solana/web3.js"; import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; const sdk = new BrowserSDK({ providers: ["injected"], addressTypes: [AddressType.solana], }); await sdk.connect({ provider: "injected" }); // Get recent blockhash const connection = new Connection("https://api.mainnet-beta.solana.com"); const { blockhash } = await connection.getLatestBlockhash(); // Create transfer instruction const fromAddress = await sdk.solana.getPublicKey(); const transferInstruction = SystemProgram.transfer({ fromPubkey: new PublicKey(fromAddress), toPubkey: new PublicKey(toAddress), lamports: 0.001 * LAMPORTS_PER_SOL, }); // Create VersionedTransaction const messageV0 = new TransactionMessage({ payerKey: new PublicKey(fromAddress), recentBlockhash: blockhash, instructions: [transferInstruction], }).compileToV0Message(); const transaction = new VersionedTransaction(messageV0); // Send transaction using chain-specific API const result = await sdk.solana.signAndSendTransaction(transaction); console.log("Transaction signature:", result.hash); ``` #### Solana with `@solana/kit` ```typescript import { createSolanaRpc, pipe, createTransactionMessage, setTransactionMessageFeePayer, setTransactionMessageLifetimeUsingBlockhash, address, compileTransaction, } from "@solana/kit"; import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; const sdk = new BrowserSDK({ providers: ["injected"], addressTypes: [AddressType.solana], }); await sdk.connect({ provider: "injected" }); // Create transaction with @solana/kit const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com"); const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const userPublicKey = await sdk.solana.getPublicKey(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), tx => setTransactionMessageFeePayer(address(userPublicKey), tx), tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), ); const transaction = compileTransaction(transactionMessage); // Send using chain-specific API const result = await sdk.solana.signAndSendTransaction(transaction); console.log("Transaction signature:", result.hash); ``` ``` -------------------------------- ### Install Phantom React Native SDK Source: https://docs.phantom.com/sdks/react-native-sdk/index Installs the core Phantom React Native SDK package using npm. ```bash npm install @phantom/react-native-sdk ``` -------------------------------- ### Install Phantom React SDK Source: https://docs.phantom.com/phantom-portal/get-app-id Install the Phantom React SDK using your preferred package manager. This command adds the necessary library to your project for integrating Phantom authentication into React applications. ```bash # Using npm npm install @phantom/react-sdk # Using yarn yarn add @phantom/react-sdk # Using pnpm pnpm add @phantom/react-sdk ``` -------------------------------- ### Ethereum Transaction Examples Source: https://docs.phantom.com/sdks/browser-sdk/sign-and-send-transaction Presents examples of sending Ethereum transactions using the Phantom Browser SDK. It includes a basic ETH transfer and an EIP-1559 transaction with `maxFeePerGas`. Both examples utilize `sdk.ethereum.sendTransaction` and require `@phantom/browser-sdk`. The EIP-1559 example shows how to include contract call data. ```typescript import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; const sdk = new BrowserSDK({ providers: ["injected"], addressTypes: [AddressType.ethereum], }); await sdk.connect({ provider: "injected" }); // Simple ETH transfer const result = await sdk.ethereum.sendTransaction({ to: "0x742d35Cc6634C0532925a3b8D4C8db86fB5C4A7E", value: "1000000000000000000", // 1 ETH in wei gas: "21000", gasPrice: "20000000000", // 20 gwei }); // EIP-1559 transaction with maxFeePerGas const result2 = await sdk.ethereum.sendTransaction({ to: "0x742d35Cc6634C0532925a3b8D4C8db86fB5C4A7E", value: "1000000000000000000", // 1 ETH in wei data: "0x...", // contract call data gas: "50000", maxFeePerGas: "30000000000", // 30 gwei maxPriorityFeePerGas: "2000000000", // 2 gwei }); console.log("Transaction hash:", result.hash); ``` -------------------------------- ### Sign-In with Ethereum - request Method Example Source: https://docs.phantom.com/developer-powertools/signing-a-message Example of signing a message using the Sign-In with Ethereum standard via the `request` method with `signMessage`. ```APIDOC ## POST /request (Ethereum) ### Description Signs a message using the Sign-In with Ethereum standard via the `request` method with the `signMessage` type. ### Method `POST` (simulated, actual method is `request` call on provider) ### Endpoint `/request` ### Parameters #### Request Body - **method** (string) - Required - The method to call, should be `"signMessage"`. - **params** (object) - Required - Parameters for the `signMessage` method. - **message** (string) - Required - The message to be signed, formatted according to EIP-4361. - **display** (string) - Optional - Display format of the message (e.g., 'utf8'). ### Request Example ```javascript const provider = getProvider(); // Assume getProvider() returns the Phantom provider const message = `magiceden.io wants you to sign in with your Ethereum account: 0xb9c5714089478a327f09197987f16f9e5d936e8a Click Sign or Approve only means you have proved this wallet is owned by you. URI: https://magiceden.io Version: 1 Chain ID: 1 Nonce: bZQJ0SL6gJ Issued At: 2022-10-25T16:52:02.748Z Resources: - https://foo.com - https://bar.com`; const encodedMessage = new TextEncoder().encode(message); const signedMessage = await provider.request({ method: "signMessage", params: { message: encodedMessage, display: "utf8", } }); ``` ### Response #### Success Response (200) - **signedMessage** (string) - The signature of the message. #### Response Example ```json { "signedMessage": "signature_string" } ``` ``` -------------------------------- ### Install Phantom Browser SDK (Bash) Source: https://docs.phantom.com/sdks/browser-sdk Installs the Phantom Browser SDK package using npm. This command should be run in the root directory of your project to add the SDK as a dependency. ```bash npm install @phantom/browser-sdk ``` -------------------------------- ### Sign-In with Ethereum - signMessage Example Source: https://docs.phantom.com/developer-powertools/signing-a-message Example of signing a message using the Sign-In with Ethereum standard via the `signMessage` method. ```APIDOC ## POST /signMessage (Ethereum) ### Description Signs a message using the Sign-In with Ethereum standard via the `signMessage` method. ### Method `POST` (simulated, actual method is `signMessage` call on provider) ### Endpoint `/signMessage` ### Parameters #### Request Body - **message** (string) - Required - The message to be signed, formatted according to EIP-4361. - **display** (string) - Optional - Display format of the message (e.g., 'utf8'). ### Request Example ```javascript const provider = getProvider(); // Assume getProvider() returns the Phantom provider const message = `magiceden.io wants you to sign in with your Ethereum account: 0xb9c5714089478a327f09197987f16f9e5d936e8a Click Sign or Approve only means you have proved this wallet is owned by you. URI: https://magiceden.io Version: 1 Chain ID: 1 Nonce: bZQJ0SL6gJ Issued At: 2022-10-25T16:52:02.748Z Resources: - https://foo.com - https://bar.com`; const encodedMessage = new TextEncoder().encode(message); const signedMessage = await provider.signMessage(encodedMessage, "utf8"); ``` ### Response #### Success Response (200) - **signedMessage** (string) - The signature of the message. #### Response Example ```json { "signedMessage": "signature_string" } ``` ``` -------------------------------- ### Install Authentication Dependencies (Bash) Source: https://docs.phantom.com/sdks/guides/wallet-authentication-with-jwts Installs necessary npm packages for wallet authentication, including express for the server, jsonwebtoken for JWTs, and Solana web3 libraries for cryptographic operations. ```bash npm install express jsonwebtoken @solana/web3.js tweetnacl bs58 ``` -------------------------------- ### Setting up Auth Callback Page with ConnectBox Source: https://docs.phantom.com/sdks/react-sdk/connect This code example illustrates how to set up an authentication callback page using the `ConnectBox` component from the Phantom SDK. It's designed to be used on pages that handle redirects from OAuth providers like Google and Apple. The `PhantomProvider` is configured similarly to the modal example, and `ConnectBox` is rendered within a centered div to handle the callback flow automatically. ```tsx // pages/auth/callback.tsx or app/auth/callback/page.tsx import { PhantomProvider, ConnectBox, darkTheme } from "@phantom/react-sdk"; import { AddressType } from "@phantom/browser-sdk"; function AuthCallbackPage() { return (
); } ``` -------------------------------- ### Install React Native SDK and Dependencies Source: https://docs.phantom.com/resources/cursor-prompts Installs the Phantom React Native SDK, Solana Web3.js, and necessary peer dependencies for Expo and polyfills. Ensure these are installed before proceeding with integration. ```bash npm install @phantom/react-native-sdk npm install @solana/web3.js npx expo install expo-secure-store expo-web-browser expo-auth-session expo-router npm install react-native-get-random-values ``` -------------------------------- ### Implement Phantom React SDK Integration for Solana Source: https://docs.phantom.com/resources/cursor-prompts This prompt guides Cursor AI to implement the Phantom React SDK for Solana integration. It covers installation of necessary packages, setting up the PhantomProvider, creating components for wallet connection, message signing, and transaction handling, along with specific requirements for error handling, UI states, and formatting. Dependencies include '@phantom/react-sdk', '@solana/web3.js', and '@phantom/browser-sdk'. ```text Implement Phantom React SDK integration for Solana with the following requirements: INSTALLATION: 1. Install the SDK: npm install @phantom/react-sdk 2. Install Solana dependencies: npm install @solana/web3.js SETUP: 1. Create App.tsx that wraps your application with PhantomProvider: - Import: PhantomProvider, useConnect, useSolana, useAccounts, useDisconnect from "@phantom/react-sdk" - Import: AddressType from "@phantom/browser-sdk" - Configure PhantomProvider with: * providerType: "embedded" * addressTypes: [AddressType.solana] * appId: "[YOUR_APP_ID]" * authOptions: { authUrl: "https://connect.phantom.app/login", redirectUrl: "[YOUR_REDIRECT_URL]" } WALLET CONNECTION COMPONENT: 1. Create a component that uses useConnect() and useAccounts() hooks 2. useConnect() returns: { connect, isConnecting } 3. Call connect() to initiate connection, returns: { addresses } 4. useAccounts() returns the connected Solana addresses array 5. Display "Connect Wallet" button when not connected 6. Display connected Solana address when connected 7. Add a disconnect button using useDisconnect() hook MESSAGE SIGNING COMPONENT: 1. Create component that uses useSolana() hook 2. Get Solana interface: const { solana } = useSolana() 3. Sign message: await solana.signMessage("Your message here") 4. Returns signature object with the signed message 5. Display signature to user in a readable format 6. Add copy-to-clipboard functionality for signature TRANSACTION COMPONENT: 1. Import required Solana libraries: - Import Transaction, SystemProgram, PublicKey from @solana/web3.js 2. Create transfer transaction: - Use SystemProgram.transfer() to create a SOL transfer - Set fromPubkey, toPubkey, and lamports (1 SOL = 1,000,000,000 lamports) 3. Sign and send transaction: - await solana.signAndSendTransaction(transaction) - Returns { hash } with transaction signature 4. Display transaction hash with link to Solana explorer 5. Add input fields for recipient address and amount in SOL 6. Validate inputs before sending REQUIREMENTS: - Use TypeScript with proper types - Add try-catch error handling for all async operations - Show loading states during connection and transactions - Display error messages to users with helpful context - Add null checks before accessing addresses - Style with Tailwind CSS for modern UI - Add helpful comments explaining Solana-specific concepts - Format addresses with truncation (show first 4 and last 4 characters) - Convert lamports to SOL for user display (divide by 1,000,000,000) The SDK automatically handles wallet connection UI, authentication flow, and transaction confirmation. ``` -------------------------------- ### Example: Construct and Sign a Message with Phantom Source: https://docs.phantom.com/bitcoin/signing-a-message This TypeScript example demonstrates how to construct a message using `TextEncoder`, specify the signing address, and then use `phantomProvider.signMessage` to obtain a signature. The `address` should be obtained through an established connection. ```typescript const message = new TextEncoder().encode('hello world'); const address = "bc1phajtersv55fwud5xr0t70p5234swy396a6avqhuny0qf83zssvrsm7tl4q"; // see "Establishing a Connection" const { signature } = await phantomProvider.signMessage(address, message); ``` -------------------------------- ### Complete Solana Message Signing Example Source: https://docs.phantom.com/sdks/react-sdk/sign-messages A comprehensive example of Solana message signing using the `useSolana` hook. This snippet demonstrates initiating a message signature and checking the connection status. It also includes imports for `solana/web3.js` suggesting potential further transaction interactions. ```tsx import { useSolana } from "@phantom/react-sdk"; import { VersionedTransaction, TransactionMessage, SystemProgram, PublicKey, Connection } from "solana/web3.js"; function SolanaOperations() { const { solana } = useSolana(); const signMessage = async () => { const signature = await solana.signMessage("Hello Solana!"); console.log("Signature:", signature); }; return (

Connected: {solana.isConnected ? 'Yes' : 'No'}

); } ``` -------------------------------- ### Install Phantom SDK with Solana and Ethereum Dependencies (npm) Source: https://docs.phantom.com/sdks/react-sdk/index Installs the Phantom React SDK along with necessary dependencies for Solana (`@solana/web3.js`) and Ethereum/EVM (`viem`) network support. This command ensures your application is equipped to interact with multiple blockchain networks via the Phantom wallet. ```bash npm install @phantom/react-sdk @solana/web3.js viem ``` -------------------------------- ### useIsExtensionInstalled Hook Source: https://docs.phantom.com/sdks/react-sdk/connect Checks if the Phantom browser extension is installed on the user's browser. ```APIDOC ## useIsExtensionInstalled Hook Use this hook to check if the Phantom browser extension is installed. This is particularly useful when using the `"injected"` provider. ### Request Example ```tsx import { useConnect, useIsExtensionInstalled } from "@phantom/react-sdk"; function InjectedConnectButton() { const { connect, isConnecting } = useConnect(); const { isInstalled, isLoading } = useIsExtensionInstalled(); const handleInjectedConnect = async () => { if (isInstalled) { await connect({ provider: "injected" }); } }; if (isLoading) { return
Checking for Phantom extension...
; } if (!isInstalled) { return (

Phantom extension not found.

Install Phantom
); } return ( ); } ``` ``` -------------------------------- ### Get Phantom Provider or Redirect (TypeScript) Source: https://docs.phantom.com/sui/detecting-the-provider A function to retrieve the Phantom SUI provider if available. If Phantom is not detected, it opens the Phantom website in a new tab for the user to install. This ensures a smooth user experience by guiding users to obtain the wallet. ```typescript const getProvider = () => { if ('phantom' in window) { const provider = window.phantom?.sui; if (provider?.isPhantom) { return provider; } } window.open('https://phantom.com/', '_blank'); } ``` -------------------------------- ### Detect Phantom Installation (TypeScript) Source: https://docs.phantom.com/bitcoin/detecting-the-provider Checks if the Phantom provider is installed by looking for the 'phantom' object and its 'isPhantom' flag in the window object. Returns the provider if found, otherwise redirects to the Phantom website. ```typescript const isPhantomInstalled = window?.phantom?.bitcoin?.isPhantom ``` ```typescript const getProvider = () => { if ('phantom' in window) { const anyWindow: any = window; const provider = anyWindow.phantom?.bitcoin; if (provider && provider.isPhantom) { return provider; } } window.open('https://phantom.com/', '_blank'); }; ``` -------------------------------- ### BrowserSDK Initialization Source: https://docs.phantom.com/sdks/browser-sdk Demonstrates how to initialize the BrowserSDK with different provider configurations and address types. ```APIDOC ## BrowserSDK Initialization ### Description Initialize the BrowserSDK with specific providers and address types. ### Method `new BrowserSDK(options)` ### Parameters #### Request Body - **providers** (Array) - Required - An array of authentication providers to enable. Available options: `"injected"`, `"google"`, `"apple"`, `"deeplink"`. - **addressTypes** (Array) - Required - An array specifying the blockchain address types to support. Supported types: `AddressType.solana`, `AddressType.ethereum`. - **appId** (string) - Optional - Your application's unique ID, required for embedded providers like `"google"`, `"apple"`, and `"deeplink"`. Obtain this from the Phantom Portal. - **authOptions** (object) - Optional - Configuration for authentication flow. - **authUrl** (string) - Optional - The base URL for the authentication endpoint. Defaults to `https://connect.phantom.app/login`. - **redirectUrl** (string) - Optional - The URL to redirect to after authentication. Defaults to the current page. Must be allowlisted in Phantom Portal. - **autoConnect** (boolean) - Optional - If `true`, attempts to automatically connect to an existing session on initialization. ### Request Example ```typescript import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; // Example 1: Injected provider only const sdkInjected = new BrowserSDK({ providers: [AddressType.solana], addressTypes: [AddressType.solana, AddressType.ethereum] }); // Example 2: Multiple authentication methods with appId and authOptions const sdkMultiAuth = new BrowserSDK({ providers: ["google", "apple", "injected", "deeplink"], addressTypes: [AddressType.solana, AddressType.ethereum], appId: "your-app-id", authOptions: { authUrl: "https://connect.phantom.app/login", redirectUrl: "https://yourapp.com/callback" }, autoConnect: true }); // Example 3: Mobile deeplink support const sdkMobile = new BrowserSDK({ providers: ["google", "apple", "deeplink"], addressTypes: [AddressType.solana, AddressType.ethereum], appId: "your-app-id" }); ``` ### Response N/A (This is a constructor) ``` -------------------------------- ### Connect to Solana and Ethereum with Phantom SDK Source: https://docs.phantom.com/resources/recipes This snippet demonstrates how to initialize the PhantomProvider to support both Solana and Ethereum addresses. It includes hooks to access Solana and Ethereum providers and functions to sign messages on each respective chain. Ensure you have installed the '@phantom/react-sdk' and '@phantom/browser-sdk' packages. ```tsx import { PhantomProvider, useSolana, useEthereum } from "@phantom/react-sdk"; import { AddressType } from "@phantom/browser-sdk"; function MultiChainApp() { return ( ); } function MultiChainOperations() { const { solana } = useSolana(); const { ethereum } = useEthereum(); const signOnSolana = async () => { const sig = await solana.signMessage("Hello Solana!"); console.log("Solana signature:", sig); }; const signOnEthereum = async () => { const accounts = await ethereum.getAccounts(); const sig = await ethereum.signPersonalMessage("Hello Ethereum!", accounts[0]); console.log("Ethereum signature:", sig); }; return (
); } ``` -------------------------------- ### Get Phantom Provider or Redirect (TypeScript) Source: https://docs.phantom.com/solana/detecting-the-provider A function to retrieve the Phantom Solana provider if installed, or redirect the user to the Phantom app download page if not. It checks for the `phantom` object and the `isPhantom` flag. If Phantom is not detected, it opens a new tab linking to the Phantom website. ```typescript const getProvider = () => { if ('phantom' in window) { const provider = window.phantom?.solana; if (provider?.isPhantom) { return provider; } } window.open('https://phantom.app/', '_blank'); } ``` -------------------------------- ### Install Peer Dependencies for Expo and Bare React Native Source: https://docs.phantom.com/sdks/react-native-sdk/index Installs necessary peer dependencies for Expo and bare React Native projects, including modules for secure storage, web browser interaction, authentication sessions, and SVG rendering. For bare React Native projects, additional setup might be required. ```bash # For Expo projects npx expo install expo-secure-store expo-web-browser expo-auth-session expo-router react-native-svg # For bare React Native projects (additional setup required) npm install expo-secure-store expo-web-browser expo-auth-session react-native-svg ``` -------------------------------- ### Get Network Version using window.ethereum.networkVersion Source: https://docs.phantom.com/ethereum-monad-testnet-base-and-polygon/provider-api-reference/properties/networkversion Retrieves the network number of the currently connected blockchain using the legacy window.ethereum.networkVersion property. This example logs the network version to the console, demonstrating its usage. ```javascript const networkVersion = window.phantom.ethereum.networkVersion; console.log(networkVersion); // "1" // Ethereum Mainnet's Network Version ``` -------------------------------- ### Get Phantom Ethereum Chain ID (JavaScript) Source: https://docs.phantom.com/ethereum-monad-testnet-base-and-polygon/provider-api-reference/properties/chainid Retrieves the `chainId` of the currently connected network via the Phantom Ethereum provider. This property returns a hexadecimal string. For example, '0x1' represents the Ethereum Mainnet. ```javascript const chainId = window.phantom.ethereum.chainId; console.log(chainId); // "0x1" // hexidecimal representation of Ethereum Mainnet ``` -------------------------------- ### Apply Pre-built Themes with PhantomProvider (React) Source: https://docs.phantom.com/sdks/react-sdk Shows how to apply the pre-built `darkTheme` and `lightTheme` using the `PhantomProvider` in a React application. This setup allows for consistent theming across the application's components that interact with the Phantom SDK. The provider and themes are imported from the '@phantom/react-sdk' package. ```tsx import { PhantomProvider, darkTheme, lightTheme } from "@phantom/react-sdk"; // Dark theme // Light theme ``` -------------------------------- ### Solana Chain-Specific Operations with Phantom SDK (TypeScript) Source: https://docs.phantom.com/sdks/browser-sdk/connect Provides examples of performing Solana-specific operations after establishing a connection with the Phantom Browser SDK. This includes signing messages, signing transactions (with and without sending), sending signed transactions, switching networks (on embedded wallets), and utility functions like getting the public key and checking connection status. ```typescript // Message signing const signature = await sdk.solana.signMessage("Hello Solana!"); // Transaction signing (without sending) const signedTx = await sdk.solana.signTransaction(transaction); // Sign and send transaction const result = await sdk.solana.signAndSendTransaction(transaction); // Network switching (works on embedded for solana) await sdk.solana.switchNetwork('devnet'); // Utilities const publicKey = await sdk.solana.getPublicKey(); const isConnected = sdk.solana.isConnected(); ``` -------------------------------- ### connect Source: https://docs.phantom.com/sdks/browser-sdk Initiates the connection process to the Phantom wallet using the configured providers. ```APIDOC ## connect ### Description Connects to the Phantom wallet using the specified provider. This method initiates the authentication flow based on the `providers` configured during SDK initialization. ### Method `sdk.connect(options)` ### Parameters #### Request Body - **provider** (string) - Required - The specific provider to use for this connection attempt. Must be one of the providers listed during SDK initialization (e.g., `"injected"`, `"google"`, `"apple"`, `"deeplink"`). ### Request Example ```typescript // Assuming sdk is an instance of BrowserSDK initialized previously const { addresses } = await sdk.connect({ provider: "injected" }); console.log("Connected addresses:", addresses); ``` ### Response #### Success Response (200) - **addresses** (Array) - An array of connected account objects. - **address** (string) - The wallet address. - **chain** (string) - The blockchain network (e.g., "solana", "ethereum"). - **publicKey** (object) - The public key object (for Solana). #### Response Example ```json { "addresses": [ { "address": "So11111111111111111111111111111111111111111", "chain": "solana", "publicKey": { /* ... */ } }, { "address": "0xAbC123...", "chain": "ethereum" } ] } ``` ``` -------------------------------- ### Check for Phantom Installation (TypeScript) Source: https://docs.phantom.com/solana/detecting-the-provider Detects if the Phantom browser extension is installed by checking for the existence of the `window.phantom.solana.isPhantom` flag. This is the primary method for confirming Phantom's presence in a web application. ```typescript const isPhantomInstalled = window.phantom?.solana?.isPhantom ``` -------------------------------- ### Check Phantom Extension Installation Status Source: https://docs.phantom.com/sdks/react-sdk/connect Provides a component that checks if the Phantom browser extension is installed using the `useIsExtensionInstalled` hook. It conditionally renders UI elements based on the installation status and loading state. If the extension is not found, it prompts the user to install it. This is crucial for using the 'injected' provider. ```tsx import { useConnect, useIsExtensionInstalled } from "@phantom/react-sdk"; function InjectedConnectButton() { const { connect, isConnecting } = useConnect(); const { isInstalled, isLoading } = useIsExtensionInstalled(); const handleInjectedConnect = async () => { if (isInstalled) { await connect({ provider: "injected" }); } }; if (isLoading) { return
Checking for Phantom extension...
; } if (!isInstalled) { return (

Phantom extension not found.

Install Phantom
); } return ( ); } ``` -------------------------------- ### Initialize Browser SDK and Handle Connection Events Source: https://docs.phantom.com/sdks/browser-sdk/index Initializes the Browser SDK with specified providers, app ID, and address types. It also sets up event listeners for connection status changes, including start, success, errors, and disconnections. Event listeners should be set up before any connection attempts, especially for autoConnect. ```typescript import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; const sdk = new BrowserSDK({ providers: ["google", "apple"], appId: "your-app-id", addressTypes: [AddressType.solana], }); // Fired when connection starts sdk.on("connect_start", (data) => { console.log("Connection starting:", data.source); // "auto-connect" | "manual-connect" }); // Fired when connection succeeds sdk.on("connect", (data) => { console.log("Connected successfully!"); console.log("Provider type:", data.provider); console.log("Addresses:", data.addresses); console.log("Status:", data.status); }); // Fired when connection fails sdk.on("connect_error", (data) => { console.error("Connection failed:", data.error); console.log("Source:", data.source); }); // Fired when disconnected sdk.on("disconnect", (data) => { console.log("Disconnected from wallet"); }); // Remove listeners when done sdk.off("connect", handleConnect); ``` -------------------------------- ### Connect to Phantom Wallet with React SDK Source: https://docs.phantom.com/resources/recipes Demonstrates how to connect to the Phantom wallet using the React SDK. It requires the '@phantom/react-sdk' and '@phantom/browser-sdk' packages. The configuration includes provider type, address types, app ID, and authentication redirect URL. The output is a button that initiates the wallet connection process. ```tsx import { PhantomProvider, useConnect } from "@phantom/react-sdk"; import { AddressType } from "@phantom/browser-sdk"; function App() { return ( ); } function ConnectButton() { const { connect, isConnecting } = useConnect(); return ( ); } ``` -------------------------------- ### Disconnect deeplink example Source: https://docs.phantom.com/phantom-deeplinks/provider-methods/disconnect Example of how to initiate a disconnect from Phantom using their deeplink method. This snippet demonstrates the structure of the URL and parameters required for a successful disconnection. It relies on the user having previously connected via the 'connect' deeplink. ```text https://phantom.app/ul/v1/disconnect?dapp_encryption_public_key=<...>& nonce=<...>& redirect_link=<...>& payload=<...> ``` -------------------------------- ### Send Ethereum Transactions with Phantom SDK and viem (TypeScript) Source: https://docs.phantom.com/sdks/browser-sdk/sign-and-send-transaction This snippet shows how to send an Ethereum transaction using the Phantom Browser SDK and viem. It includes examples for simple ETH transfers and contract interactions. Ensure you have the `@phantom/browser-sdk` and `viem` libraries installed. The SDK requires provider and address type configurations. Outputs include transaction hashes or contract interaction results. ```typescript import { parseEther, parseGwei, encodeFunctionData } from "viem"; import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; const sdk = new BrowserSDK({ providers: ["injected"], addressTypes: [AddressType.ethereum], }); // Simple transfer with viem utilities const result = await sdk.ethereum.sendTransaction({ to: "0x742d35Cc6634C0532925a3b8D4C8db86fB5C4A7E", value: parseEther("1").toString(), // 1 ETH gas: "21000", gasPrice: parseGwei("20").toString(), // 20 gwei }); // Contract interaction const result2 = await sdk.ethereum.sendTransaction({ to: tokenContractAddress, data: encodeFunctionData({ abi: tokenAbi, functionName: "transfer", args: [recipientAddress, parseEther("100")], }), gas: "50000", maxFeePerGas: parseGwei("30").toString(), maxPriorityFeePerGas: parseGwei("2").toString(), }); ``` -------------------------------- ### Basic Phantom Wallet Connection and Operations (TypeScript) Source: https://docs.phantom.com/sdks/browser-sdk/connect Establishes a connection to a Phantom wallet using the Browser SDK and demonstrates basic Solana and Ethereum operations. Requires the '@phantom/browser-sdk' package. Initializes the SDK with allowed providers and address types, then connects to a specified provider. Outputs connected addresses and shows examples of signing messages and sending transactions. ```typescript import { BrowserSDK, AddressType } from "@phantom/browser-sdk"; // 1. Create SDK instance with allowed providers const sdk = new BrowserSDK({ providers: ["google", "apple", "injected"], // Allowed auth providers addressTypes: [AddressType.solana, AddressType.ethereum], appId: "your-app-id", // Required when using embedded providers }); // 2. Connect to wallet (provider parameter must be in allowed providers list) const { addresses } = await sdk.connect({ provider: "google" }); console.log("Connected addresses:", addresses); // 3. Use chain-specific methods const signature = await sdk.solana.signMessage("Hello!"); const ethResult = await sdk.ethereum.sendTransaction({ to: "0x...", value: "1000000000000000000", gas: "21000", }); ``` -------------------------------- ### Sign-In with Ethereum - signMessage Example Source: https://docs.phantom.com/developer-powertools/signing-a-message This JavaScript snippet demonstrates how to sign a message using the `signMessage` method for Sign-In with Ethereum. It requires a provider object and formats a message according to the EIP-4361 standard. The encoded message is then signed. ```javascript const provider = getProvider(); // see "Detecting the Provider" const message = `magiceden.io wants you to sign in with your Ethereum account: 0xb9c5714089478a327f09197987f16f9e5d936e8a Click Sign or Approve only means you have proved this wallet is owned by you. URI: https://magiceden.io Version: 1 Chain ID: 1 Nonce: bZQJ0SL6gJ Issued At: 2022-10-25T16:52:02.748Z Resources: - https://foo.com - https://bar.com`; const encodedMessage = new TextEncoder().encode(message); const signedMessage = await provider.signMessage(encodedMessage, "utf8"); ``` -------------------------------- ### Check Phantom Ethereum Provider Installation Source: https://docs.phantom.com/ethereum-monad-testnet-base-and-polygon/provider-api-reference/properties/isphantom This endpoint allows you to check if the Phantom Ethereum provider is installed and available in the browser environment. ```APIDOC ## GET window.phantom.ethereum.isPhantom ### Description A boolean property that identifies if the Phantom Ethereum provider is installed and accessible. ### Method GET ### Endpoint window.phantom?.ethereum?.isPhantom ### Parameters This property does not take any parameters. ### Request Example ```javascript const isPhantomInstalled = window.phantom?.ethereum?.isPhantom; console.log(isPhantomInstalled); // Expected output: true or undefined ``` ### Response #### Success Response (Boolean) - **isPhantom** (boolean) - `true` if the Phantom Ethereum provider is installed, `undefined` otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### Provider API Overview Source: https://docs.phantom.com/ethereum-monad-testnet-base-and-polygon/provider-api-reference/README This section details the properties, events, and methods available through the Phantom Provider API, which is accessible via `window.ethereum` and `window.phantom.ethereum`. ```APIDOC ## Provider API Overview ### Description The Phantom Provider API is the interface through which decentralized applications (dapps) interact with the user's Phantom wallet. It allows dapps to request information such as account details, establish connections with the website, prompt the user to sign messages, and send transactions. This API adheres to the standards defined in [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193). ### Access The provider is made available in the browser's JavaScript environment through two global objects: - `window.ethereum` - `window.phantom.ethereum` (provided to prevent namespace collisions) ### Key Functionality - **Reading Account Data**: Retrieving information about the user's connected accounts. - **Connecting to Website**: Allowing the user to authorize a dapp to connect to their wallet. - **Signing Messages**: Enabling users to cryptographically sign arbitrary messages. - **Sending Transactions**: Facilitating the submission of blockchain transactions initiated by the dapp. ``` -------------------------------- ### Connect Wallet and Sign Messages using SDK Hooks Source: https://docs.phantom.com/sdks/react-native-sdk Illustrates direct usage of Phantom SDK hooks like `useConnect`, `useAccounts`, `useSolana`, `useEthereum`, and `useDisconnect`. This example shows how to initiate a connection, handle connection states and errors, retrieve account addresses, sign messages for both Solana and Ethereum, and disconnect the wallet. ```tsx import React from "react"; import { View, Button, Text, Alert } from "react-native"; import { useConnect, useAccounts, useSolana, useEthereum, useDisconnect } from "@phantom/react-native-sdk"; export function WalletScreen() { const { connect, isConnecting, error: connectError } = useConnect(); const { addresses, isConnected } = useAccounts(); const { solana } = useSolana(); const { ethereum } = useEthereum(); const { disconnect } = useDisconnect(); const handleConnect = async () => { try { await connect({ provider: "google" }); Alert.alert("Success", "Wallet connected!"); } catch (error) { Alert.alert("Error", `Failed to connect: ${error.message}`); } }; const handleSignSolanaMessage = async () => { try { const signature = await solana.signMessage("Hello from Solana!"); Alert.alert("Solana Signed!", `Signature: ${signature.signature.slice(0, 10)}...`); } catch (error) { Alert.alert("Error", `Failed to sign: ${error.message}`); } }; const handleSignEthereumMessage = async () => { try { const accounts = await ethereum.getAccounts(); const signature = await ethereum.signPersonalMessage("Hello from Ethereum!", accounts[0]); Alert.alert("Ethereum Signed!", `Signature: ${signature.signature.slice(0, 10)}...`); } catch (error) { Alert.alert("Error", `Failed to sign: ${error.message}`); } }; if (!isConnected) { return (