Use the Keyring API from a dapp
Your dapp can use the Keyring API to interact with custom EVM accounts.
Use the KeyringSnapRpcClient
of the Keyring API to invoke Keyring RPC methods on your Keyring Snap.
You can follow the end-to-end tutorial to create a Snap to connect to custom EVM accounts.
See the Keyring API reference for all the Keyring API methods.
Create the KeyringSnapRpcClient
To use the KeyringSnapRpcClient
, install @metamask/keyring-api
in your project directory using
Yarn or npm:
yarn add @metamask/keyring-api
or
npm install @metamask/keyring-api
Create the client by adding the following to your project script:
import { KeyringSnapRpcClient } from "@metamask/keyring-api";
let client = new KeyringSnapRpcClient(snapId, window.ethereum);
Call Keyring API methods
You can now use the KeyringSnapRpcClient
to invoke the following
Keyring API
methods on your Snap.
createAccount
Creates a Keyring account.
let keyringAccount = await client.createAccount("KeyringAccount1");
getAccount
Gets a Keyring account.
// accountId is returned when the account is created using createAccount.
let keyringAccount = await client.getAccount(accountId);
listAccounts
Lists all Keyring accounts created by the Snap.
let keyringAccounts = await client.listAccounts();
updateAccount
Updates a Keyring account.
let updatedAccount = await client.updateAccount(modifiedKeyringAccount);
deleteAccount
Deletes a Keyring account.
let snapResponse = await client.deleteAccount(accountId);
submitRequest
Submits a Keyring request.
import { v4 as uuid } from "uuid";
// Example submitting an eth_sendTransaction request
let submitRequestResponse = await client.submitRequest({
// ID of the account to which you want to submit this request
account: accountId,
scope: "eip155:1", // Ethereum Mainnet
request: {
jsonrpc: "2.0",
// Unique ID to identify every request
id: uuid(),
// The method and parameter structure is subjective to the Keyring API implementation in the Snap code.
method: "eth_sendTransaction",
params:
{
from: "",
to: "0xcEF0f7f7ee1650b4A8151f605d9258bA65D733F5",
data,
chainId: "1",
},
,
},
});
getRequest
Gets a Keyring request.
// requestId is returned during request submission.
let keyringRequest = await client.getRequest(requestId);
listRequests
Lists all requests submitted to the Snap.
let requests = await client.listRequests();
approveRequest
Approves a request.
// requestId is returned during request submission.
await client.approveRequest(requestId);
rejectRequest
Rejects a request.
// requestId is returned during request submission.
await client.rejectRequest(requestId);
filterAccountChains
Returns a filtered list of CAIP-2 IDs representing the supported chains.
// accountId - ID of the account to be checked
// chains - List of chains (CAIP-2) to be checked
let supportedChains = await client.filterAccountChains(accountId, chains);