@metamask/multichain-api-client

MetaMask MutliChain API Client

This TypeScript module is maintained in the style of the MetaMask team.

yarn add @metamask/multichain-api-client

or

`npm install @metamask/multichain-api-client``

import { getMultichainClient, getDefaultTransport } from '@metamask/multichain-api-client';

const client = getMultichainClient({ transport: getDefaultTransport() });
const session = await client.createSession({ requiredScopes: ['eip155:1'] });

const result = await client.invokeMethod({
scope: 'eip155:1',
request: {
method: 'eth_call',
params: {
to: '0x1234567890',
data: '0x1234567890',
},
},
});

await client.revokeSession();

By default, the transport has no timeout (-1) for requests. This is because most operations require user interaction (e.g., confirming transactions in the MetaMask extension), and we don't want to prematurely cancel requests while the user is reviewing them.

However, you can configure a default timeout (in milliseconds) for all requests by passing the defaultTimeout option:

const transport = getDefaultTransport({ defaultTimeout: 30000 }); // 30 seconds timeout for all requests
const client = getMultichainClient({ transport });

To explicitly disable timeouts (wait indefinitely), set the timeout to -1:

const transport = getDefaultTransport({ defaultTimeout: -1 }); // No timeout (default behavior)

The warmupTimeout is a special timeout used specifically for the first request sent immediately after the transport establishes its connection. This is useful because:

  • Some transports need a brief moment to fully initialize before they can reliably process requests
  • The initial "warmup" request is typically a lightweight check (e.g., wallet_getSession) that doesn't require user interaction
  • This timeout is usually much shorter than the regular request timeout
const transport = getDefaultTransport({
warmupTimeout: 200, // 200 ms for the initial warmup request
defaultTimeout: -1 // No timeout for subsequent requests (user interactions)
});
const client = getMultichainClient({ transport });

Key differences between warmupTimeout and defaultTimeout:

Property Purpose Typical Value When Applied
warmupTimeout Initial connection validation 200 ms Only the first request after connect()
defaultTimeout Regular request operations -1 (no timeout) All subsequent requests

## Extending RPC Types

The client's RPC requests are strongly typed, enforcing the RPC methods and params to be defined ahead of usage. The client supports extending
the default RPC API with custom methods. This is useful when working with chains that have additional RPC methods beyond
the standard ones.

### Define Custom RPC Types

```typescript
import type { RpcMethod } from '@metamask/multichain-api-client';

// Define your custom RPC structure
type MyCustomRpc = {
mychain: {
methods: {
customMethod: RpcMethod<{ param1: string; param2: number }, { result: string }>;
anotherMethod: RpcMethod<{ data: string }, boolean>;
};
events: ['customEvent'];
};
};
import { getMultichainClient, getDefaultTransport } from '@metamask/multichain-api-client';

// Create a client with extended types
const client = getMultichainClient({ transport: getDefaultTransport() })
.extendsRpcApi<MyCustomRpc>();

// Now you can use your custom methods with full type safety
const result = await client.invokeMethod({
scope: 'mychain:123', // Your custom chain scope
request: {
method: 'customMethod',
params: { param1: 'hello', param2: 42 }
}
});

Transports handle the communication layer between your application and the wallet. You can create custom transports for different environments or communication methods.

It is recommended that each custom transport implements its own request timeout mechanism rather than relying on higher layers. This ensures:

  • Transport-specific optimizations (e.g., aborting underlying network channels, clearing listeners)
  • Consistent error semantics (e.g., always throwing a dedicated TransportTimeoutError or custom error type)
  • Better resource cleanup in environments like browsers or workers

Your request implementation should accept an optional { timeout?: number } argument.

A transport must implement the following interface:

type Transport = {
warmupTimeout?: number; // Optional timeout for the initial warmup request
connect: () => Promise<void>;
disconnect: () => Promise<void>;
isConnected: () => boolean;
request: <TRequest, TResponse>(
request: TRequest,
options?: { timeout?: number }
) => Promise<TResponse>;
onNotification: (callback: (data: unknown) => void) => () => void;
};
import { TransportError, TransportTimeoutError } from '@metamask/multichain-api-client';
import type { Transport, TransportRequest, TransportResponse } from '@metamask/multichain-api-client';

type CustomTransportOptions = {
defaultTimeout?: number; // Default timeout for all requests (use -1 for no timeout)
warmupTimeout?: number; // Optional timeout for the initial warmup request
};

export function getCustomTransport(options: CustomTransportOptions = {}): Transport {
const { defaultTimeout = -1, warmupTimeout } = options; // Default: no timeout

return {
warmupTimeout, // Expose warmupTimeout for the client to use
connect: async () => { ... },
disconnect: async () => { ... },
isConnected: () => { ...},
request: async <TRequest extends TransportRequest, TResponse extends TransportResponse>(
request: TRequest,
{ timeout = defaultTimeout }: { timeout?: number } = {}
): Promise<TResponse> => {
// If timeout is -1, don't apply any timeout
if (timeout === -1) {
return performRequest(request); // Your actual request logic
}

// Otherwise, wrap the request with a timeout
return withTimeout(
performRequest(request),
timeout,
() => new TransportTimeoutError()
);
},
onNotification: (callback: (data: unknown) => void) => { ... },
};
}

// Usage examples
const transport = getCustomTransport({
warmupTimeout: 500, // 500 ms for initial connection check
defaultTimeout: -1 // No timeout for user interactions (default)
});
const client = getMultichainClient({ transport });

// Per-request timeout override
await client.invokeMethod({
scope: 'eip155:1',
request: { method: 'eth_chainId', params: [] },
{ timeout: 10000 } // 10 seconds timeout for this specific request
});

The client provides two main error types for handling different failure scenarios:

TransportError is thrown when there are issues with the transport layer communication, such as connection failures or the targeted browser extension not being installed.

import { TransportError } from '@metamask/multichain-api-client';

try {
const client = getMultichainClient({ transport: getDefaultTransport() });
await client.createSession({ optionalScopes: ['eip155:1'] });
} catch (error) {
if (error instanceof TransportError) {
console.error('Transport error:', error.message);
console.error('Original error:', error.cause);
}
}

MultichainApiError is thrown when the wallet returns an error response to API requests. This includes permission denials, invalid parameters, and other wallet-specific errors.

import { MultichainApiError } from '@metamask/multichain-api-client';

try {
const result = await client.invokeMethod({
scope: 'eip155:1',
request: {
method: 'eth_sendTransaction',
params: { to: '0x1234...', value: '0x0' }
}
});
} catch (error) {
if (error instanceof MultichainApiError) {
console.error('Multichain API error:', error.message);
console.error('Error details:', error.cause);
}
}

Both error types extend the standard Error class and may include the original error in the cause property for debugging purposes.

See our documentation:

  • Install the current LTS version of Node.js
    • If you are using nvm (recommended) running nvm install will install the latest version and running nvm use will automatically choose the right node version for you.
  • Install Yarn v4 via Corepack
  • Run yarn install to install dependencies and run any required post-install scripts

Run 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.

  1. Choose a release version.

    • The release version should be chosen according to SemVer. Analyze the changes to see whether they include any breaking changes, new features, or deprecations, then choose the appropriate SemVer version. See the SemVer specification for more information.
  2. 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).

    • The major version branch should be set to the most recent release with that major version. For example, when backporting a v1.0.2 release, you'd want to ensure there was a 1.x branch that was set to the v1.0.1 tag.
  3. Trigger the workflow_dispatch event manually for the Create Release Pull Request action to create the release PR.

    • For a backport release, the base branch should be the major version branch that you ensured existed in step 2. For a normal release, the base branch should be the main branch for that repository (which should be the default value).
    • This should trigger the action-create-release-pr workflow to create the release PR.
  4. 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.

    • Generally any changes that don't affect consumers of the package (e.g. lockfile changes or development environment changes) are omitted. Exceptions may be made for changes that might be of interest despite not having an effect upon the published package (e.g. major test improvements, security improvements, improved documentation, etc.).
    • Try to explain each change in terms that users of the package would understand (e.g. avoid referencing internal variables/concepts).
    • Consolidate related changes into one change entry if it makes it easier to explain.
    • Run yarn auto-changelog validate --rc to check that the changelog is correctly formatted.
  5. Review and QA the release.

    • If changes are made to the base branch, the release branch will need to be updated with these changes and review/QA will need to restart again. As such, it's probably best to avoid merging other PRs into the base branch while review is underway.
  6. Squash & Merge the release.

    • This should trigger the action-publish-release workflow to tag the final release commit and publish the release on GitHub.
  7. Publish the release on npm.

    • Wait for the 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.
    • Approve the publish-npm job (or ask somebody on the npm publishers team to approve it for you).
    • Once the publish-npm job has finished, check npm to verify that it has been published.