Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SDK: New Docs #1766

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ To contribute changes:

> **Notes:**
>
> - All documentation content is located in the `wallet`, `snaps`, `services`, and
> - All documentation content is located in the `wallet`, `sdk`, `snaps`, `services`, and
> `developer-tools` directories.
> - If you add a new documentation page, edit `wallet-sidebar.js`, `snaps-sidebar.js`,
> - If you add a new documentation page, edit `wallet-sidebar.js`, `sdk-sidebar.js`, `snaps-sidebar.js`,
> `services-sidebar.js`, or `dashboard-sidebar.js` to add the page to the
> [sidebar](https://docs-template.consensys.io/create/configure-docusaurus#sidebar).
> - If you delete, rename, or move a documentation file, add a
Expand Down Expand Up @@ -120,7 +120,7 @@ Refer to the [Consensys documentation style guide](https://docs-template.consens

## Add images

All images are located in the `wallet/assets`, `snaps/assets`, `services/images`, and
All images are located in the `wallet/assets`, `sdk/_assets`, `snaps/assets`, `services/images`, and
`developer-tools/images` directories.
When adding a new image, such as a screenshot or diagram, make sure the image has a white or
`#1b1b1d` color background in order for it to be compatible with the site's light and dark modes.
Expand Down
7 changes: 6 additions & 1 deletion docs/whats-new.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ The latest major MetaMask documentation updates are listed by the month they wer
For a comprehensive list of recent product changes, visit the "Release Notes" section at the bottom
of the [MetaMask developer page](https://metamask.io/developer/).

## January 2025

- Added new [MetaMask SDK documentation section](/sdk).
([#1766](https://github.com/MetaMask/metamask-docs/pull/1766))

## December 2024

- Documented [Swellchain](/services/reference/swellchain) support. ([#1776](https://github.com/MetaMask/metamask-docs/pull/1776))
Expand All @@ -21,7 +26,7 @@ of the [MetaMask developer page](https://metamask.io/developer/).

- Documented [updated error responses](/services/reference/ethereum/json-rpc-methods) when rate-limiting Infura JSON-RPC API calls. ([#1749](https://github.com/MetaMask/metamask-docs/pull/1749))
- Documented [Unichain Sepolia](/services/reference/unichain) support. ([#1725](https://github.com/MetaMask/metamask-docs/pull/1725))
- Updated Snaps [Custom UI documentation](/snaps/features/custom-ui/) for MetaMask Extension version 12.6.
- Updated Snaps [custom UI documentation](/snaps/features/custom-ui/) for MetaMask Extension version 12.6.
([#1715](https://github.com/MetaMask/metamask-docs/pull/1715))
- Added tutorial for
[creating a simple Starknet dapp](/wallet/how-to/use-non-evm-networks/starknet/create-a-simple-starknet-dapp).
Expand Down
21 changes: 20 additions & 1 deletion docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,17 @@ const config = {
}
},
],
[
"@docusaurus/plugin-content-docs",
{
id: "sdk",
path: "sdk",
routeBasePath: "sdk",
editUrl: "https://github.com/MetaMask/metamask-docs/edit/main/",
sidebarPath: require.resolve("./sdk-sidebar.js"),
breadcrumbs: false,
},
],
"./src/plugins/plugin-json-rpc.ts",
isProd
? [
Expand Down Expand Up @@ -178,9 +189,13 @@ const config = {
width: 150,
},
items: [
{
to: "sdk",
label: "SDK",
},
{
to: "wallet",
label: "Wallet",
label: "Wallet API",
},
{
to: "snaps",
Expand Down Expand Up @@ -248,6 +263,10 @@ const config = {
label: "Wallet",
to: "/wallet",
},
{
label: "SDK",
to: "/sdk",
},
{
label: "Snaps",
to: "/snaps",
Expand Down
68 changes: 68 additions & 0 deletions sdk-sidebar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// @ts-check

/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebar = {
sdkSidebar: [
{
type: 'category',
label: 'Introduction',
collapsible: false,
collapsed: false,
items: [
'introduction/welcome',
'introduction/supported-platforms',
'introduction/supported-networks',
'introduction/llm-prompt',
{
type: 'link',
label: 'Try demo dapp',
href: 'https://metamask-sdk-examples-relink.vercel.app/',
},
],
},
{
type: 'category',
label: 'Quickstart',
collapsible: false,
collapsed: false,
items: [
'quickstart/javascript-wagmi',
'quickstart/javascript',
'quickstart/react-native',
],
},
{
type: 'category',
label: 'Guides',
collapsible: false,
collapsed: false,
items: [
'guides/authenticate-users',
'guides/manage-networks',
'guides/handle-transactions',
'guides/interact-with-contracts',
{
type: 'category',
label: 'Advanced',
collapsible: true,
collapsed: true,
items: [
'guides/advanced/connect-and-sign',
'guides/advanced/batch-requests',
],
},
],
},
{
type: 'category',
label: 'Reference',
collapsible: false,
collapsed: false,
items: [
'reference/sdk-options'
],
}
],
};

module.exports = sidebar;
Binary file added sdk/_assets/connect.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added sdk/_assets/network.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added sdk/_assets/quickstart.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
132 changes: 132 additions & 0 deletions sdk/guides/advanced/batch-requests.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
---
description: Batch multiple JSON-RPC requests.
---

# Batch requests

You can batch multiple JSON-RPC requests in your JavaScript dapp.

The SDK's `metamask_batch` method enables you to batch multiple JSON-RPC requests in a single call,
providing a streamlined approach for dapps to interact with EVM networks, and enabling complex
sequences of actions.
This method enhances performance, usability, and efficiency by reducing the number of network calls
made to MetaMask.

Use cases include:

- **Batching multiple signatures** - Send multiple signing requests in one batch.

- **Switching networks** - Switch the EVM network, perform an action such as sending a transaction,
and switch back, all in one batch.

- **Mixed transactions and signatures** - Combine transaction sending and signing requests in one batch.

`metamask_batch` opens up additional possibilities for sophisticated transaction flows in dapps,
enhancing the user experience and operational efficiency.

## Prerequisites

Set up MetaMask SDK in your JavaScript dapp.

## Use the `metamask_batch` method

`metamask_batch` takes an array of JSON-RPC requests (`ChainRPC[]`) as its parameter.

Each request in the batch is independent.
The user receives a prompt for each action within the batch, allowing them to approve or reject
individual requests.
If any request is rejected, the entire batch fails and an error is returned, ensuring integrity in
transactional operations.

The method returns an array of results corresponding to each request.

### React / Next.js / React Native example

The following is an example of using `metamask_batch` to batch
[`personal_sign`](/wallet/reference/json-rpc-methods/personal_sign) and
[`eth_sendTransaction`](/wallet/reference/json-rpc-methods/eth_sendtransaction) in React, Next.js, or React Native/Expo:

```javascript title="index.js"
import { metamask_batch } from "metamask-sdk"

function MyComponent() {
const handleBatchRequest = async () => {
const batchRequests = [
{ method: "personal_sign", params: ["message", "address"] },
{
method: "eth_sendTransaction",
params: [
{
/* Transaction parameters */
},
],
},
]

try {
const results = await metamask_batch(batchRequests)
console.log(results) // Process results.
} catch (error) {
console.error("Batch request failed", error)
}
}

return <button onClick={handleBatchRequest}>Send Batch Request</button>
}
```

### Vue.js example

The following is an example of using `metamask_batch` to batch
[`personal_sign`](/wallet/reference/json-rpc-methods/personal_sign) and
[`eth_sendTransaction`](/wallet/reference/json-rpc-methods/eth_sendtransaction) in Vue.js:

```javascript title="App.vue"
<script>
import { metamask_batch } from "metamask-sdk";

export default {
methods: {
async sendBatchRequest() {
const batchRequests = [
{ method: "personal_sign", params: ["message", "address"] },
{
method: "eth_sendTransaction",
params: [
{
/* Transaction parameters */
},
],
},
];

try {
const results = await metamask_batch(batchRequests);
console.log(results);
} catch (error) {
console.error("Error in batch request", error);
}
}
}
}
</script>
```

### Best practices

Follow these best practices when using `metamask_batch`:

- **Ensure each request in the batch is properly formatted** according to the JSON-RPC specifications.

- **Handle errors appropriately**, especially when a batch request is partially approved.

- **Test batch operations** to ensure consistent behavior across different networks and accounts.

- **Be aware of the dependencies between chained requests.**
Avoid creating a dependency where the outcome of one request directly influences the context or
validity of a subsequent request within the same batch.
For example, avoid chaining a [`wallet_switchEthereumChain`](/wallet/reference/json-rpc-methods/wallet_switchethereumchain)
request with [`eth_signTypedData_v4`](/wallet/reference/json-rpc-methods/eth_signtypeddata_v4), because
`eth_signTypedData_v4` relies on the current chain ID, which would be altered by `wallet_switchEthereumChain`.
This approach ensures that each request in the batch operates independently and maintains its
integrity, regardless of changes introduced by preceding requests in the batch.
92 changes: 92 additions & 0 deletions sdk/guides/advanced/connect-and-sign.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
---
description: Connect and sign in a single interaction.
---

# Connect and sign

You can connect to MetaMask and sign data in a single interaction from your JavaScript dapp.

The SDK's `connectAndSign` method provides a streamlined approach for dapps to interact with MetaMask.
This method combines the [`eth_requestAccounts`](/wallet/reference/json-rpc-methods/eth_requestaccounts)
and [`personal_sign`](/wallet/reference/json-rpc-methods/personal_sign) RPC methods, executing them sequentially.
`connectAndSign` takes one parameter, the message string to be signed, and passes the message and
the output of `eth_requestAccounts` directly to `personal_sign`.

This method enhances dapp user experience, especially on mobile platforms, by allowing users to
connect to MetaMask and sign a message in a single interaction, requiring only one switch between
the mobile dapp and MetaMask Mobile.
This is useful for various purposes such as authentication and transaction verification.

<p align="center">
<video width="350" controls>
<source src="/connect-and-sign.mp4" type="video/mp4" />
</video>
</p>

## Prerequisites

- MetaMask SDK set up in your JavaScript dapp.

- MetaMask Mobile version 7.10 or later.
Your users must have an updated version of MetaMask Mobile for this feature to work correctly.
For older versions of MetaMask, this function may not work as expected.

## Use the `connectAndSign` method

Use the `connectAndSign` method as follows:

```javascript
const connectAndSign = async () => {
try {
const signResult = await sdk?.connectAndSign({
msg: "Connect + Sign message",
})
setResponse(signResult)
} catch (err) {
console.warn("failed to connect..", err)
}
}
```

To invoke `connectAndSign`:

1. Ensure the `MetaMaskSDK` instance (`sdk` in this context) is properly initialized and available.
2. Call `connectAndSign` with the message to be signed.
3. Handle the promise to process the response or catch any errors.

## Examples

The following is an example of using the `connectAndSign` method in a React dapp, integrating it
into a functional component:

```javascript
import React, { useState } from "react"
import { useSDK } from "@metamask/sdk-react"

function MyComponent() {
const { sdk } = useSDK()
const [signedMessage, setSignedMessage] = useState("")

const handleConnectAndSign = async () => {
try {
const message = "Your message here"
const signature = await sdk.connectAndSign({ msg: message })
setSignedMessage(signature)
} catch (error) {
console.error("Error in signing:", error)
}
}

return (
<div>
<button onClick={handleConnectAndSign}>Connect and Sign</button>
{signedMessage && <p>Signed Message: {signedMessage}</p>}
</div>
)
}
```

For examples of using the `connectAndSign` function in Next.js and Vue.js, see the
[example Next.js dapp](https://github.com/MetaMask/metamask-sdk/tree/main/packages/examples/nextjs-demo)
and [example Vue.js dapp](https://github.com/MetaMask/metamask-sdk/tree/main/packages/examples/vuejs)
on GitHub.
Loading
Loading