Skip to main content

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

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:

NameTypeDescription
domainStringDomain to interact with the backend and keystore.
rpcURLStringRPC (remote procedure call) URL of the blockchain network.
secureBoolPreferred protocol: true for secure wss (use in the production environment) or false for insecure wss (use in the development environment only). Defaults to true.

Methods

Main methods:

MethodDescription
.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:

MethodDescription
.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:

NameTypeDescription
accessTokenStringValid access token returned from an OAuth 2.0 provider.
timeoutNumber (optional)Timeout of the function.
trackParamsITrackParamsEnable 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:

NameTypeDescription
accessTokenStringValid access token returned from an OAuth 2.0 provider.
privateKeyShardString (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.
passwordStringRecovery 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:

NameTypeDescription
accessTokenStringValid access token returned from an OAuth 2.0 provider.
encryptedKeyStringPrivate key shard encrypted using the user's password.
passwordStringRecovery 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:

NameTypeDescription
accessTokenStringValid access token returned from an OAuth 2.0 provider.
privateKeyShardStringPrivate 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.
passwordStringRecovery 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:

NameTypeDescription
accessTokenStringValid access token returned from an OAuth 2.0 provider.
timeoutNumberOptionally, 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:

NameTypeDescription
transactionHashStringHash of the transaction on the blockchain.
maxRetriesNumberNumber of attempts to get the status of the transaction in the blockchain network.
timeoutNumberOptionally, 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:

NameTypeDescription
accessTokenStringValid 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>
}
PropertyTypeDescription
codeNumberError code triggered by the SDK.
errorMessageStringCombination of the error code and name, and information on how to address the error.
serverErrorCodeNumberError code returned from the MPC server.
closedReasonStringUsed 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.

CodeNameDefinitionGenerated by
0OKNot an error. Returned on success.Client
1CancelledThe operation is cancelled, typically by the caller.Server
2UnknownUnknown 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
3InvalidArgumentThe client specified an invalid argument.Client and server
4DeadlineExceededThe 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
5NotFoundA requested entity, such as a file or directory, is not found.Client and server
6AlreadyExistsAn attempt to create an entity failed because one already exists.Server
7PermissionDeniedThe 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
8ResourceExhaustedA resource is exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.Server
10AbortedThe operation is aborted, typically due to a concurrency issue.Server
12UnimplementedThis function or this SDK isn't implemented yet and can't be used.Client and server
13InternalSome invariants expected by the underlying system are broken.Server
14UnavailableThe data isn't ready to accept this request.Server
16UnauthenticatedThe request doesn't have valid authentication credentials for the operation.Client
20MPCInitializeProtocolFailedThe MPC protocol failed to initialize.Client and server
21MPCHandshakeProtocolFailedFailed to handshake with the other party in the MPC protocol.Client and server
22MPCBadSignatureThe resultant MPC signature is malformed.Client and server
23MPCSignatureVerifyFailedThe signature is received, but an attempt to verify the data with this signature failed.Client
24MPCServerStoreKeyFailedFailed to store the key on the keystore server.Client and server
25MPCBadResultThe MPC protocol successfully completed, but an unexpected bad result occurred.Client and server
26MPCSendTxRequestFailedFailed to send the transaction request to the server.Client
27MPCBadKeyThe user's private key shard is malformed or invalid.Client and server
28MPCSignMessageFailedThe message signing phase failed.Client and server
29MPCSendTxFailedFailed to send the transaction to RPC.Client and server
30MPCAddressAlreadyExistedThe MPC wallet address already exists.Server
31MPCChallengeFailedIn the backup flow, the MPCChallenge is a phase that verifies whether the user owns the key. This error returns when that phase failed.Server
100DialSocketFailedFailed to dial a WebSocket server.Client
101WriteDataFailedFailed to write data to a WebSocket channel.Client and server
102ReadDataFailedFailed to read data from a WebSocket channel.Client and server
103BadRPCDataReceived an invalid MPC protocol message.Client and server
104BadSignMessageDataReceived malformed or invalid message signing data.Client and server
105BadTxDataReceived malformed or invalid transaction data.Client and server
106InitHTTPFailedFailed to initialize the process of the HTTP connection, preventing the app from establishing a valid connection to the server or resource.Client
107DoHTTPFailedFailed when calling JSON-RPC API or RESTful API.Client
108BadHTTPDataReceived unexpected data from the server.Client
109DialRPCNodeFailedWhen sending a transaction or any action that requires interaction with an RPC node, the server couldn't connect to the RPC node.Server
110HitRateLimitUUIDThe rate limit exceeded, try again later (up to 60 seconds).Server
1001PolicyFailedThe 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

CodeNameDefinition
400Bad RequestThe API request itself is incorrect and contains invalid or incorrect values.
401UnauthorizedThe API request is sent with invalid authentication information (for example, bad JWT).
403ForbiddenThe API request is trying to perform something that the user is not allowed to do.
404Not FoundThe API request is trying to query a page that doesn’t exist.
429Too Many RequestsThe rate limit is exceeded. For more information, see Rate limits.
Was this helpful?
Happy React is loading...