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:
wallet_getSession) that doesn't require user interactionconst 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:
TransportTimeoutError or custom error type)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:
nvm install will install the latest version and running 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 --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.