const isPhantomInstalled = window.phantom?.solana?.isPhantom
const getProvider = () => {
if ('phantom' in window) {
const provider = window.phantom?.solana;
if (provider?.isPhantom) {
return provider;
}
}
window.open('https://phantom.app/', '_blank');
};
//The connection request will prompt the user for permission to share their public key, indicating that they are willing to interact further
const provider = getProvider(); // see "Detecting the Provider"
try {
const resp = await provider.connect();
console.log(resp.publicKey.toString());
// 26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo
} catch (err) {
// { code: 4001, message: 'User rejected the request.' }
}
// The connect() call will return a Promise that resolves when the user accepts the connection request,
// and reject (throw when awaited) when the user declines the request or closes the pop-up.
// See Errors for a breakdown of error messages Phantom may emit.
provider.on("connect", () => console.log("connected!"));
// Once the web application is connected to Phantom, it will be able to read the connected account's public key and prompt the user for additional transactions
console.log(provider.publicKey.toString());
// 26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo
console.log(provider.isConnected);
// true
provider.connect({ onlyIfTrusted: true });
import { useEffect } from "react";
// Connect
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
})
}, []);
import { useState, useEffect } from "react";
const [pubKey, setPubKey] = useState(null);
// Disconnect
useEffect(() => {
// Store user's public key once they connect
provider.on("connect", (publicKey) => {
setPubKey(publicKey);
});
// Forget user's public key once they disconnect
provider.on("disconnect", () => {
setPubKey(null);
});
}, [provider]);
// If a user changes accounts while already connected to an application, and the new account had already whitelisted that application,
// then the user will stay connected and Phantom will pass the PublicKey of the new account:
provider.on('accountChanged', (publicKey) => {
if (publicKey) {
// Set new public key and continue as usual
console.log(`Switched to account ${publicKey.toBase58()}`);
}
});
// If Phantom does not pass the public key of the new account, an application can either do nothing or attempt to reconnect:
provider.on('accountChanged', (publicKey) => {
if (publicKey) {
// Set new public key and continue as usual
console.log(`Switched to account ${publicKey.toBase58()}`);
} else {
// Attempt to reconnect to Phantom
provider.connect().catch((error) => {
// Handle connection failure
});
}
});