JavaScript SDK reference
Overview
To facilitate integration for developers of varying backgrounds, the MPC JavaScript SDK offers two distinct provider options:
mpcCore
is designed for developers with little web3 experience. It offers essential methods for main operations, such as creating wallets and signing transactions and messages through MPC.mpcProvider
offers familiar methods for experienced developers that have already used libraries, such as Ethers.js or Web3.js, and offers some other benefits:- Seamless integration with existing projects built on Web3Provider, Ethers.js, or custom EIP-1193 providers.
- Minimum syntax changes: Retain your current syntax as
mpcProvider
automatically handles logic conversion for default methods.
This page organizes the requests and responses for each provider—Core and Provider—on dedicated tabs.
Requirements
- Node.js v18.16 or later
- npm or yarn for package installation
Installation
npm:
npm install @axieinfinity/mpcjs
yarn:
yarn add @axieinfinity/mpcjs
Initialization
- Core
- Providers
Import the MpcCore
package:
import { MpcCore } from "@axieinfinity/mpcjs";
Initialize MpcCore
:
import { MpcCore } from "@axieinfinity/mpcjs";
const mpcCore = MpcCore.init({
domain: `${YOUR_SERVER_DOMAIN}`, // "project-x.skymavis.one",
rpcURL: `${NETWORK_RPC}`, // "https://saigon-testnet.roninchain.com/rpc"
secure: `${boolean}`, // true (default)
});
//...
Parameters:
Name | Type | Description |
---|---|---|
domain | String | Domain to interact with the backend and keystore. |
rpcURL | String | RPC (remote procedure call) URL of the blockchain network. |
secure | Bool | Preferred protocol: true for secure wss (use in the production environment) or false for insecure wss (use in the development environment only). Defaults to true . |
Import the MpcProviders
package:
import { MpcProviders } from "@axieinfinity/mpcjs";
Initialize MpcProviders
:
import { MpcProviders } from "@axieinfinity/mpcjs";
const mpcProvider = MpcProviders.create(
domain: `${YOUR_SERVER_DOMAIN}`, // "project-x.skymavis.one"
rpcURL: `${NETWORK_RPC}`, // "https://saigon-testnet.roninchain.com/rpc"
chainID: `${YOUR_CHAIN_ID}` // 2021
);
//...
Parameters:
Name | Type | Description |
---|---|---|
domain | String | Domain to interact with the backend and keystore. |
rpcURL | String | RPC (remote procedure call) URL of the blockchain network. |
chainID | Int | Identitifier or numeric code associated with the blockchain network. |
After initializing the MPC provider, connect it to the MPC service:
connect(accessToken, password): Promise<string>
Parameters:
Name | Type | Description |
---|---|---|
accessToken | String | Valid access token returned from an OAuth 2.0 provider. |
password | String | Recovery password set by the user to protect privateKeyShard . Only the user with the correct password can access the private key. |
With mpcProvider
, you can import other providers that comply with EIP-1193, and providers that inherit from JsonRpcProvider.
Add an external provider:
// Create Infura as external provider
const externalProvider = new ethers.providers.JsonRpcProvider(
"https://arbitrum-goerli.infura.io/v3/${YOUR_API_KEY}",
);
// Add Infura to mpcProvider
mpcProvider.addProvider(externalProvider);
Methods
Main methods:
Method | Description |
---|---|
.init() | Initializes the MPC SDK. All other SDK functions must be called after this one. |
.generateMPCKey() | Generates an MPC private key. |
.encryptKey() | Encrypts the user's private key shard. |
.decryptKey() | Descrypts the user's private key shard. |
.createBackupKey() | Creates a backup copy of the user's encrypted private key shard on the Sky Mavis backup server. |
.getBackupKey() | Retrieves the backup copy of the user's encrypted private key shard from the Sky Mavis backup server. |
Utilities:
Method | Description |
---|---|
.getTransactionStatus() | Returns the status of the specified transaction. |
.getCurrentUserProfile() | Returns the user's public wallet address from the server. |
.convertAmount() | Convert an amount of tokens to HexString to use in a transaction's input data. |
Generate MPC key
generateMPCKey(accessToken: string): Promise<IMpcClientKey>
Parameters:
Name | Type | Description |
---|---|---|
accessToken | String | Valid access token returned from an OAuth 2.0 provider. |
timeout | Number (optional) | Timeout of the function. |
trackParams | ITrackParams | Enable or disable tracking. |
Example:
const accessToken = `${ACCESS_TOKEN}`;
const response = await mpcCore.generateMPCKey(accessToken);
console.log(response.data.key);
Return:
IMpcClientKey
data: {
key: string;
};
meta: {
requestId: string;
uuid: string;
}
Encrypt private key shard
encryptKey(accessToken: string, privateKeyShard: string, password: string): Promise<IEncryptedKeyResult>
Parameters:
Name | Type | Description |
---|---|---|
accessToken | String | Valid access token returned from an OAuth 2.0 provider. |
privateKeyShard | String (HexString) | Private key generated after completing the key generation process, exclusively owned by the user. This key participates in all transaction signing processes along with the key stored in the Sky Mavis backend. |
password | String | Recovery password set by the user to protect privateKeyShard . Only the user with the correct password can access the private key. |
Example:
const encryptedKey = await mpcCore.encryptKey(
`${ACCESS_TOKEN}`,
`${PRIVATE_KEY}`,
`${RECOVERY_PASSWORD}`
);
console.log(encryptedKey.data);
Return:
IEncryptedKeyResult
{
data: string
}
Decrypt private key shard
decryptKey(accessToken: string, encryptedKey: string, password: string): Promise<IDecryptedKeyResult>
Parameters:
Name | Type | Description |
---|---|---|
accessToken | String | Valid access token returned from an OAuth 2.0 provider. |
encryptedKey | String | Private key shard encrypted using the user's password. |
password | String | Recovery password set by the user to protect privateKeyShard . Only the user with the correct password can access the private key. |
Example:
...
const accessToken = `${ACCESS_TOKEN}`;
const encryptedKey = `${PRIVATE_KEY}`;
const password = `${RECOVERY_PASSWORD}`;
const decryptKey = await mpcCore.decryptKey(accessToken, encryptedKey, password);
console.log(decryptKey.data);
...
Return:
IDecryptedKeyResult
{
data: string
}
Back up private key shard
createBackupKey(accessToken: string, privateKeyShard: string, password: string): Promise<IBackupKey>
Parameters:
Name | Type | Description |
---|---|---|
accessToken | String | Valid access token returned from an OAuth 2.0 provider. |
privateKeyShard | String | Private key generated after completing the key generation process, exclusively owned by the user. This key participates in all transaction signing processes along with the key stored in the Sky Mavis backend. |
password | String | Recovery password set by the user to protect privateKeyShard . Only the user with the correct password can access the private key. |
Example:
...
const accessToken = `${ACCESS_TOKEN}`;
const privateKeyShard = `${PRIVATE_KEY}`;
const password = `${RECOVERY_PASSWORD}`;
const encryptedKey = await mpcCore.createBackupKey(accessToken, privateKeyShard, password);
...
Return:
IBackupKey
data: {
encryptedKey: string;
meta: {
requestId: string;
uuid: string;
};
};
Get backup of private key shard
getBackupKey(accessToken: string, timeout?: number): Promise<IBackupKey>
Parameters:
Name | Type | Description |
---|---|---|
accessToken | String | Valid access token returned from an OAuth 2.0 provider. |
timeout | Number | Optionally, time to wait for the server's response. Defaults to 10 seconds. |
Example:
...
const accessToken = `${ACCESS_TOKEN}`;
const timeout = 20000; // 20 seconds
const encryptedKey = await mpcCore.getBackupKey(accessToken, timeout);
...
Return:
IBackupKey
data: {
encryptedKey: string;
meta: {
requestId: string;
uuid: string;
};
};
Get transaction status
getTransactionStatus(transactionHash: string, maxRetries: number, timeout: number): Promise<TransactionStatus>
Parameters:
Name | Type | Description |
---|---|---|
transactionHash | String | Hash of the transaction on the blockchain. |
maxRetries | Number | Number of attempts to get the status of the transaction in the blockchain network. |
timeout | Number | Optionally, time to wait for the server's response. Defaults to 10 seconds. |
Example:
...
const txStatus = await mpcCore.getTransactionStatus(`${TRANSACTION_HASH}`, 3, 20000);
...
Return:
TransactionStatus
0 // Failed
1 // Successful
-1 //MaxRetriesExceeded
Get user profile
getCurrentUserProfile(accessToken: string): Promise<IUserProfile>
Parameters:
Name | Type | Description |
---|---|---|
accessToken | String | Valid access token returned from an OAuth 2.0 provider. |
Example:
const accessToken = `${ACCESS_TOKEN}`;
const profile = await mpcCore.getCurrentUserProfile(accessToken);
console.log(profile.data.address);
Return:
IUserProfile
data: {
address: string;
updatedAt: number;
};
Convert amount
When transferring tokens, you need to specify a HexString representation of the token amount within the transaction request.
After determining the amount of tokens to transfer, convert the amount to a BigNumber type for precision:
import { BigNumber, parseFixed } from "@ethersproject/bignumber";
const convertAmount = (fracAmount: string, decimals: number): BigNumber => {
const rawAmount = parseFixed(fracAmount , decimals)
return rawAmount
};
Then, convert the BigNumber representation to a HexString before including it in the transaction request.
This example converts 10 RON to a BigNumber, and then converts the BigNumber to a HexString:
const amount = "10";
const rawAmount: BigNumber = convertAmount(amount, 18);
const hexAmount: string = ethers.utils.hexValue(rawAmount);
Error handling
When making requests to our APIs, you may encounter two types of errors: SDK errors and server errors.
- SDK errors are static, client-side errors that typically arise from issues in the syntax or semantics of your code using the MPC SDK.
- Server errors are dynamic errors that occur on the MPC server itself.
When a user encounters an error, the system's response may include an SDK error code and a server error code. SDK errors occur before the user interacts with the Sky Mavis server, while server errors indicate issues with the server itself. The error response may also contain a 4xx HTTP status code, which points to a problem with the request sent by your game to Sky Mavis, such as an invalid format or missing information.
Error response syntax
{
"code": <CODE>,
"errorMessage": <MESSAGE>,
"serverErrorCode": <SERVER_ERROR_CODE>,
"closedReason": <SOCKET_CLOSED_REASON>
}
Property | Type | Description |
---|---|---|
code | Number | Error code triggered by the SDK. |
errorMessage | String | Combination of the error code and name, and information on how to address the error. |
serverErrorCode | Number | Error code returned from the MPC server. |
closedReason | String | Used for server-side errors when the server closes the socket abruptly. Contains the name of the error and information on how to address it. |
Sample response:
{
code: 20,
errorMessage: "error: code=110 message=hit ratelimit, retry later in 60.000000 seconds",
serverErrorCode: 110,
closedReason: "hit ratelimit, retry later in 60.000000 seconds"
}
Error codes
SDK error codes and server error codes have the same definitions. You can find these definitions in the following table.
Code | Name | Definition | Generated by |
---|---|---|---|
0 | OK | Not an error. Returned on success. | Client |
1 | Cancelled | The operation is cancelled, typically by the caller. | Server |
2 | Unknown | Unknown error. An example of where this error may be returned is if a status value received from another address space belongs to an error-space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error. | Client and server |
3 | InvalidArgument | The client specified an invalid argument. | Client and server |
4 | DeadlineExceeded | The operation expired before completion. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from the server could have been delayed long enough for the deadline to expire. | Client |
5 | NotFound | A requested entity, such as a file or directory, is not found. | Client and server |
6 | AlreadyExists | An attempt to create an entity failed because one already exists. | Server |
7 | PermissionDenied | The caller doesn't have the permission to execute the specified operation. Don't use this for rejections caused by exhausting some resource—use ResourceExhausted instead. Also don't use if the caller can't be identified—use Unauthenticated instead. | Server |
8 | ResourceExhausted | A resource is exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. | Server |
10 | Aborted | The operation is aborted, typically due to a concurrency issue. | Server |
12 | Unimplemented | This function or this SDK isn't implemented yet and can't be used. | Client and server |
13 | Internal | Some invariants expected by the underlying system are broken. | Server |
14 | Unavailable | The data isn't ready to accept this request. | Server |
16 | Unauthenticated | The request doesn't have valid authentication credentials for the operation. | Client |
20 | MPCInitializeProtocolFailed | The MPC protocol failed to initialize. | Client and server |
21 | MPCHandshakeProtocolFailed | Failed to handshake with the other party in the MPC protocol. | Client and server |
22 | MPCBadSignature | The resultant MPC signature is malformed. | Client and server |
23 | MPCSignatureVerifyFailed | The signature is received, but an attempt to verify the data with this signature failed. | Client |
24 | MPCServerStoreKeyFailed | Failed to store the key on the keystore server. | Client and server |
25 | MPCBadResult | The MPC protocol successfully completed, but an unexpected bad result occurred. | Client and server |
26 | MPCSendTxRequestFailed | Failed to send the transaction request to the server. | Client |
27 | MPCBadKey | The user's private key shard is malformed or invalid. | Client and server |
28 | MPCSignMessageFailed | The message signing phase failed. | Client and server |
29 | MPCSendTxFailed | Failed to send the transaction to RPC. | Client and server |
30 | MPCAddressAlreadyExisted | The MPC wallet address already exists. | Server |
31 | MPCChallengeFailed | In the backup flow, the MPCChallenge is a phase that verifies whether the user owns the key. This error returns when that phase failed. | Server |
100 | DialSocketFailed | Failed to dial a WebSocket server. | Client |
101 | WriteDataFailed | Failed to write data to a WebSocket channel. | Client and server |
102 | ReadDataFailed | Failed to read data from a WebSocket channel. | Client and server |
103 | BadRPCData | Received an invalid MPC protocol message. | Client and server |
104 | BadSignMessageData | Received malformed or invalid message signing data. | Client and server |
105 | BadTxData | Received malformed or invalid transaction data. | Client and server |
106 | InitHTTPFailed | Failed to initialize the process of the HTTP connection, preventing the app from establishing a valid connection to the server or resource. | Client |
107 | DoHTTPFailed | Failed when calling JSON-RPC API or RESTful API. | Client |
108 | BadHTTPData | Received unexpected data from the server. | Client |
109 | DialRPCNodeFailed | When sending a transaction or any action that requires interaction with an RPC node, the server couldn't connect to the RPC node. | Server |
110 | HitRateLimitUUID | The rate limit exceeded, try again later (up to 60 seconds). | Server |
1001 | PolicyFailed | The user exceeded the limit set by a transaction policy. For example, exceeded the limit of RON transfers or tried to call a smart contract that isn't allowlisted. | Server |
HTTP status codes
Code | Name | Definition |
---|---|---|
400 | Bad Request | The API request itself is incorrect and contains invalid or incorrect values. |
401 | Unauthorized | The API request is sent with invalid authentication information (for example, bad JWT). |
403 | Forbidden | The API request is trying to perform something that the user is not allowed to do. |
404 | Not Found | The API request is trying to query a page that doesn’t exist. |
429 | Too Many Requests | The rate limit is exceeded. For more information, see Rate limits. |