Establishing a Connection

In order to start interacting with Phantom you must first establish a connection. This connection request will prompt the user for permission to share their public key, and indicate that they are willing to interact further.

Once permission is established the first time, the web application's domain will be whitelisted for future connection requests. The user may also indicate that they are willing to auto-approve certain transactions from the application as well.

Similarly, it is possible to terminate the connection both on the application and the user side.

Connecting

The recommended and easiest way to connect to Phantom is by calling window.solana.connect() . However, the provider also exposes a request JSON RPC interface.

connect()
request()
connect()
window.solana.connect();
request()
window.solana.request({ method: "connect" })

When the user has accepted the request to connect, the provider will emit a connect event.

window.solana.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 send transactions. It also exposes a convenience isConnected boolean, and will indicate whether automatic transaction approvals have been enabled by the user.

window.solana.publicKey.toString()
// 26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo
window.solana.isConnected
// true
window.solana.autoApprove
// true or false

Eagerly Connecting

After a web application connects to Phantom for the first time it becomes trusted, and it is possible for the application to automatically connect to Phantom on subsequent visits, or page refreshes. This is often called "eagerly connecting".

To implement this, Phantom allows an onlyIfTrusted option to be passed into the connect() call.

connect()
request()
connect()
window.solana.connect({ onlyIfTrusted: true });
request()
window.solana.request({ method: "connect", params: { onlyIfTrusted: true }});

When using this flag, Phantom will only connect and emit a connect event if the application is trusted. Therefore, this can be safely called on page load for new users, as they won't be bothered by a pop-up window even if they have never connected to Phantom.

Here is an example of how you might use this to implement "eagerly connecting" in a React application.

import { useEffect } from "react";
‚Äč
useEffect(() => {
// Will either automatically connect to Phantom, or do nothing.
window.solana.connect({ onlyIfTrusted: true });
}, []);

Disconnecting

Disconnecting is similar to connecting, however, it is possible for the disconnection to originate from the wallet.

disconnect()
request()
disconnect()
window.solana.disconnect();
request()
window.solana.request({ method: "disconnect" });
window.solana.on('disconnect', () => console.log("disconnected!"))