Connect your App to Plug¶
π Connect your App to Plug¶
Start interacting with the user's wallet by requesting a connect, and if needed, passing the necessary information to interact with the Agent and Actor.
requestConnect
¶
requestConnect
is an asynchronous method to request a new connection by showing a pop-up to the Plug user, that resolves to Promise<PublicKey>
if the users response is Approve
.
As an example, copy and paste the following code snippet into the console and execute it.
Select Approve
or Reject
in the pop-up and to see the corresponding result (Approved or Rejected) in the console.
If accepted, the requestConnect
method returns an object containing the publicKey of the connected account.
If declined, the method will throw an error message.
(async () => {
try {
const publicKey = await window.ic.plug.requestConnect();
console.log(`The connected user's public key is:`, publicKey);
} catch (e) {
console.log(e);
}
})();
Optionally, you can pass the following parameters to integrate Plug's Agent features, for authenticating a user's identity and requesting access to the Plug Agent to sign requests to your canisters on behalf of that identity.
The fields are:
- whitelist - an Array of Canister Ids of type string
- host - a string representing a network URL that when not set defaults to the
https://icp0.io
Important
Passing a whitelist is telling Plug to pass the user a list of canisters that your app will be able to interact with through the PlugAgent, on their behalf. NOTE: You should only be interacting with whitelisted canisters through an actor created through createActor( ). More on that soon.
This is how it looks:
Object {
whitelist?: ['canister-id'],
host?: 'https://network-address',
timeout: 50000
}
Here's an hypothetical example:
(async () => {
// Canister Ids
const nnsCanisterId = 'qoctq-giaaa-aaaaa-aaaea-cai'
// Whitelist
const whitelist = [
nnsCanisterId,
];
// Host
const host = "https://mainnet.dfinity.network";
// Make the request
try {
const publicKey = await window.ic.plug.requestConnect({
whitelist,
host,
timeout: 50000
});
console.log(`The connected user's public key is:`, publicKey);
} catch (e) {
console.log(e);
}
})();
You can learn more about this and use a template button implementation by reading our Plug button guide! A ready-to-go "Connect to Plug" button for your app.
isConnected
¶
isConnected
is an asynchronous method to check the connection status, that returns a Boolean: true
or false
.
(async () => {
const result = await window.ic.plug.isConnected();
console.log(`Plug connection is ${result}`);
})()
disconnect
¶
Use window.ic.plug.disconnect
method to notify plug of user's intention to terminate dapp's session and reset Plug's internal state.
πΎ Accessing Session Data¶
Once connected, you can access properties exposed by plug
window.ic.plug.agent // access session agent (HttpAgent)
window.ic.plug.isWalletLocked // access wallet's locked state (boolean)
window.ic.plug.principalId // access principalId of the wallet that was used to connect (string)
window.ic.plug.accountId // access accountId of the wallet that was used to connect (string)
All session data will all automatically be updated by Plug's in-page provider upon any account switch or manual session termination
β‘ Persisting an App/Plug Connection¶
After initiating a connection to Plug with a whitelist, you can add this check to ensure the connection persists as the user navigates your application/website
const connected = await window.ic.plug.isConnected();
if (!connected) await window.ic.plug.requestConnect({ whitelist, host });
You can use this, for example, in a useEffect inside of your apps main component (index/app) to do a check after load. You can pass on the same whitelist as before (wonβt require re-approval by the user, unless access was revoked), or a different whitelist Canister ID set (will require the userβs approval).
const verifyConnection = async () => {
const connected = await window.ic.plug.isConnected();
if (!connected) await window.ic.plug.requestConnect({ whitelist, host });
};
useEffect(async () => {
verifyConnection();
}, []);
π Plug callbacks¶
Plug provides the following listeners to track wallet's connection and state:
onExternalDisconnect(callback: () => void)
¶
The callback passed to window.ic.plug.onExternalDisconnect
will be called whenever dapp's session is terminated outside of the dapp, for instance, when user switches wallet or revokes dapp's permissions.
You might want to terminate the user's session on the dapp's side as well in this callback.
onLockStateChange(callback: (isLocked: boolean) => void)
¶
The callback passed to window.ic.plug.onLockStateChange
will be called whenever the wallet is locked/unlocked.