![Introducing Dashboard Analytics](https://cdn.sanity.io/images/cgdhsj6q/production/af327c5bd94708db501516a75da6870aef894c64-2286x1522.png?w=400&fit=max&auto=format)
Product
Introducing Dashboard Analytics
We're introducing a new Analytics feature in the Socket dashboard so you can view changes in your organization's and repositories' alerts over time.
@metamask/keyring-api
Advanced tools
This TypeScript module simplifies the integration of Snaps with MetaMask using the Keyring API.
Features:
Keyring API Interface: The module exposes an interface representing the Keyring API. Snaps can implement this interface to seamlessly interact with MetaMask and leverage its functionality.
Dapp Client: The module includes a client that enables dapps to communicate with the account Snap. This client allows dapps to send requests to the Snap, such as retrieving account information or submitting requests.
MetaMask Client: The module provides a client specifically designed for MetaMask integration. This client enables MetaMask to send requests directly to the account Snap, facilitating smooth interoperability between the two applications.
Request Handler Helper Functions: The module offers a set of helper functions to simplify the implementation of the request handler in the account Snap. These functions assist in processing incoming requests, validating data, and handling various request types from dapps and MetaMask.
yarn add @metamask/keyring-api
or
npm install @metamask/keyring-api
:point_up: Important: Before implementing your Snap, please make sure to read the security recommendations and the architecture document.
Starting with MetaMask 11.4, Snaps can implement the Keyring API. This allows users to manage their accounts in a more flexible way, and enables developers to build new types of accounts.
:pencil2: Note: You can also build MetaMask from source from the
develop
branch.
Follow these steps to implement the Keyring API in your Snap. Please note that these instruction assume that you are already familiar with the process of developing a Snap.
Implement the Keyring API:
Inside your Snap, implement the Keyring
API:
class MySnapKeyring implements Keyring {
// Implement the required methods here...
}
:point_up: Important: Ensure that your keyring implements the methods called by MetaMask, otherwise some features may not work.
Handle requests submitted by MetaMask:
MetaMask will submit requests through the submitRequest
method of your the
Keyring API (check the supported EVM methods). Here
is an example of request:
{
"id": "d6e23af6-4bea-48dd-aeb0-7d3c30ea67f9",
"scope": "",
"account": "69438371-bef3-4957-9f91-c3f22c1d75f3",
"request": {
"method": "personal_sign",
"params": [
"0x4578616d706c652060706572736f6e616c5f7369676e60206d657373616765",
"0x5874174dcf1ab6F7Efd8496f4f09404CD1c5bA84"
]
}
}
Where:
id
is unique identifier for the request.
scope
is the CAIP-2 chain ID of the selected chain. Currently, this
property is always an empty string. Your Snap should use the chain ID
present in the request object instead.
account
is the ID of the account that should handle the request.
request
is the request object.
Your Snap must respond with either a synchronous result:
return { pending: false, result };
Or an asynchronous result:
return { pending: true, redirect: { message, url } };
The redirect message and URL will be displayed to the user to inform them about how to continue the transaction flow.
Notify MetaMask about events:
The following actions must be notified to MetaMask:
When an account is created:
try {
emitSnapKeyringEvent(snap, KeyringEvent.AccountCreated, { account });
// Update your snap's state...
} catch (error) {
// Handle the error...
}
MetaMask will return an error if the account already exists or if the account object is invalid.
When an account is updated:
try {
emitSnapKeyringEvent(snap, KeyringEvent.AccountUpdated, { account });
// Update your snap's state...
} catch (error) {
// Handle the error...
}
MetaMask will return an error if the account does not exist, if the account object is invalid, or if the account address changed.
When an account is deleted:
try {
emitSnapKeyringEvent(snap, KeyringEvent.AccountDeleted, {
id: account.id,
});
// Update your snap's state...
} catch (error) {
// Handle the error...
}
The delete event is idempotent, so it is safe to emit it even if the account does not exist.
When a request is approved:
try {
emitSnapKeyringEvent(snap, KeyringEvent.RequestApproved, {
id: request.id,
result,
});
// Update your snap's state...
} catch (error) {
// Handle the error...
}
MetaMask will return an error if the request does not exist.
:pencil2: Note: This only applies to Snaps that implement the asynchronous transaction flow.
When a request is rejected:
try {
emitSnapKeyringEvent(snap, KeyringEvent.RequestRejected, {
id: request.id,
});
// Update your snap's state...
} catch (error) {
// Handle the error...
}
MetaMask will return an error if the request does not exist.
:pencil2: Note: This only applies to Snaps that implement the asynchronous transaction flow.
Expose the Keyring API:
Then create a handler to expose the keyring methods to MetaMask and your dapp:
export const onKeyringRequest: OnKeyringRequestHandler = async ({
origin,
request,
}) => {
// Your custom logic here...
return handleKeyringRequest(keyring, request);
};
Call the keyring methods from your dapp:
Now you should be able to call your account Snap from your dapp, for example:
const client = new KeyringSnapRpcClient(snapId, window.ethereum);
const accounts = await client.listAccounts();
The following changes were made to the API, which may require changes to your implementation:
In the KeyringAccount
type, the supportedMethods
property was renamed to
methods
.
- supportedMethods: string[];
+ methods: string[];
In the KeyringAccount
type, the name
property was removed.
- name: string;
In the KeyringAccount
type, add the options
property can no longer be
null.
- options: Record<string, unknown> | null;
+ options: Record<string, unknown>;
In the KeyringAccount
type, the eth_signTypedData
method was removed from
the list of available methods.
- 'eth_signTypedData',
It was an alias for the eth_signTypedData_v1
method, which is still
present.
Snaps should now use the emitSnapKeyringEvent()
helper function to notify
MetaMask about events:
// Emit an event to indicate that an account was created.
emitSnapKeyringEvent(snap, KeyringEvent.AccountCreated, { account });
// Emit an event to indicate that an account was updated.
emitSnapKeyringEvent(snap, KeyringEvent.AccountUpdated, { account });
// Emit an event to indicate that an account was deleted.
emitSnapKeyringEvent(snap, KeyringEvent.AccountDeleted, { id: account.id });
// Emit an event to indicate that a request was approved.
emitSnapKeyringEvent(snap, KeyringEvent.RequestApproved, {
id: request.id,
result,
});
// Emit an event to indicate that a request was rejected.
emitSnapKeyringEvent(snap, KeyringEvent.RequestRejected, { id: request.id });
:point_up: Important: For all events above, MetaMask may return an error indicating that the event was not handled, possibly because it contains invalid arguments.
Keyrings that implement the asynchronous transaction flow can
now return an optional redirect
property that contains an URL and a message
to be displayed to the user. This will, in a future release of MetaMask, be
used to inform the user on how to continue the transaction flow.
return {
pending: true,
redirect: {
message: 'Please go to the Snap Dapp to finish sining the transaction.',
url: 'https://example.com/sign?tx=1234',
},
};
The buildHandlersChain
helper function was removed from the API. Instead,
you must implement your own handler. For example:
export const onRpcRequest: OnRpcRequestHandler = async ({
request,
origin,
}) => {
// Check if origin is allowed to call the method.
if (!hasPermission(origin, request.method)) {
throw new Error(
`Origin '${origin}' is not allowed to call '${request.method}'`,
);
}
// Dispatch the request to the keyring.
return handleKeyringRequest(keyring, request);
};
The following changes were made to the API, which may require changes to your implementation:
Your Snap must expose the Keyring methods through the onKeyringRequest
export instead of the onRpcRequest
export.
Your Snap must request the new endowment:keyring
endowment, and list any
dapp that should be allowed to call the Keyring methods.
For more details about the changes, please refer to the security guidelines.
See our documentation:
nvm use
will automatically choose the right node version for you.yarn install
to install dependencies and run any required post-install scriptsRun yarn test
to run the tests once. To run tests on file changes, run yarn test:watch
.
Run yarn lint
to run the linter, or run yarn lint:fix
to run the linter and fix any automatically fixable issues.
The project follows the same release process as the other libraries in the MetaMask organization. The GitHub Actions action-create-release-pr
and action-publish-release
are used to automate the release process; see those repositories for more information about how they work.
Choose a release version.
If this release is backporting changes onto a previous release, then ensure there is a major version branch for that version (e.g. 1.x
for a v1
backport release).
v1.0.2
release, you'd want to ensure there was a 1.x
branch that was set to the v1.0.1
tag.Trigger the workflow_dispatch
event manually for the Create Release Pull Request
action to create the release PR.
action-create-release-pr
workflow to create the release PR.Update the changelog to move each change entry into the appropriate change category (See here for the full list of change categories, and the correct ordering), and edit them to be more easily understood by users of the package.
yarn auto-changelog validate --prettier --rc
to check that the changelog is correctly formatted.Review and QA the release.
Squash & Merge the release.
action-publish-release
workflow to tag the final release commit and publish the release on GitHub.Publish the release on npm.
publish-release
GitHub Action workflow to finish. This should trigger a second job (publish-npm
), which will wait for a run approval by the npm publishers
team.publish-npm
job (or ask somebody on the npm publishers team to approve it for you).publish-npm
job has finished, check npm to verify that it has been published.FAQs
MetaMask Keyring API
The npm package @metamask/keyring-api receives a total of 5,507 weekly downloads. As such, @metamask/keyring-api popularity was classified as popular.
We found that @metamask/keyring-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 11 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
We're introducing a new Analytics feature in the Socket dashboard so you can view changes in your organization's and repositories' alerts over time.
Security News
A new OpenSSF report uncovers critical gaps in secure software training, with 75% of new developers unfamiliar with secure practices, highlighting urgent educational needs.
Security News
The 2023 Python Developers Survey reveals key trends in packaging, web frameworks, and developer demographics, highlighting a shift toward innovative tools as the Python community diversifies and grows among less experienced developers.