Skip to main content

Establish connection

After applying Provider detected, you can initiate a connection request to UKey Wallet. After the user confirms, the application will obtain the current Solana account public key and can continue to request Sign message or Send transaction.

After the first authorization, the current site will be recorded as an authorized application. During subsequent access, the application can try to reconnect silently; the user can also revoke authorization in the wallet or actively disconnect.

connect

The preferred and easiest way to connect to UKey Wallet is to call window.$ukey.solana.connect(). However, the Provider also exposes the request JSON RPC interface.

Use connect

const provider = getProvider(); // Use the helper from "Detecting Providers"
try {
const resp = await provider.connect();
console.log(resp.publicKey.toString());
// 返回值参考类似于:26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo
} catch (err) {
// Example response: { code: 4001, message: 'User rejected the request.' }
}

Use request

const provider = getProvider(); // Use the helper from "Detecting Providers"
try {
const resp = await provider.request({ method: "connect" });
console.log(resp.publicKey.toString());
// 返回值参考类似于:26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo
} catch (err) {
// Example response: { code: 4001, message: 'User rejected the request.' }
}

connect() Returns a Promise. When the user agrees, Promise resolves and returns publicKey; when the user refuses or closes the pop-up window, Promise rejects, and the common error code is 4001.

After the connection is successful, the Provider will also trigger the connect event.

provider.on("connect", () => console.log("Connection is ready!"));

After the connection is completed, the application can read provider.publicKey and provider.isConnected to update the connection status.

console.log(provider.publicKey.toString());
console.log(provider.isConnected);
// Reference value: true

Automatically reconnect

After an app is authorized for the first time, it can attempt to connect automatically on subsequent visits or page refreshes. This process will not pop up a confirmation window and is suitable for restoring the connected state when the page is initialized.

This is accomplished by passing onlyIfTrusted in the connect() call.

Use connect

provider.connect({ onlyIfTrusted: true });

Use request

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

With onlyIfTrusted, UKey Wallet will only complete reconnection and trigger connect when the site is authorized. If it is not authorized, it will return 4001 and remain disconnected, but the pop-up window will not be opened.

Here's an example of restoring connection state in React:

import { useEffect } from "react";

useEffect(() => {
// Reconnect automatically if already authorized; otherwise stay quiet.
provider.connect({ onlyIfTrusted: true })
.then(({ publicKey }) => {
// Note: Handle successful automatic reconnection
});
.catch(() => {
// Note: Handle connection failures as usual
})
}, []);

If the user revokes the site authorization in the wallet settings, confirmation will need to pop up again next time the connection is made. The application should support both silent reconnection failure and manual connection states.

The application can actively disconnect, or the user can disconnect on the wallet side. After receiving a disconnect event, please clean up the status of the local public key and dependent accounts.

Use disconnect

provider.disconnect();

Use request

provider.request({ method: "disconnect" });

The following example shows how to listen for connection and disconnection events:

import { useState, useEffect } from "react";

const [pubKey, setPubKey] = useState(null);

useEffect(() => {
// Cache the user's public key once the connection succeeds
provider.on("connect", (publicKey) => {
setPubKey(publicKey);
});

// Reset entry user's public key after disconnecting
provider.on("disconnect", () => {
setPubKey(null);
});
}, [provider]);

Swap account

Users may manage multiple Solana accounts within UKey Wallet. Provider triggers accountChanged every time you switch accounts.

If the new account has been authorized for the current site, the event will bring a new PublicKey, and the application can directly refresh the account status:

provider.on("accountChanged", (publicKey) => {
if (publicKey) {
// Note: Set up the new public key and continue as usual
console.log(`Active account switched to ${publicKey.toBase58()}`);
}
});

If the event does not carry the public key, it means that the current site has not obtained new account authorization. The app can remain disconnected or prompt the user to reconnect:

provider.on("accountChanged", (publicKey) => {
if (publicKey) {
// Note: Set up the new public key and continue as usual
console.log(`Active account switched to ${publicKey.toBase58()}`);
} else {
// Note: Try reconnecting to UKey Wallet
provider.connect().catch((error) => {
// Note: Handle connection failure
});
}
});