@fordefi/web-sdk
Version:
Fordefi MPC Web SDK
564 lines (554 loc) • 24.7 kB
TypeScript
/* eslint-disable */
declare namespace fordefiWebSDK {
// Generated by dts-bundle v0.7.3
/**
* @description Error codes returned by the Fordefi SDK.
*
* Each code corresponds to a specific error condition that may occur during various operations within the SDK.
* These codes are used to identify and handle errors programmatically.
* Some codes are used for general issues, while others are specific to certain scenarios.
*
*/
export enum FordefiErrorCode {
/** An unspecified internal error occurred. */
InternalError = 1000,
/** A request to the Fordefi API failed. */
NetworkRequestFailed = 1001,
/** Authentication or authorization failed. */
Unauthorized = 1002,
/** The authentication token has expired. */
ExpiredAuthToken = 1003,
/** The specified user was not found. */
UserNotFound = 1004,
/** A condition required to perform is action was not met. */
PreconditionError = 1005,
/** The specified transaction was not found. */
TransactionNotFound = 1006,
/** User's key shares are not provisioned on the current device. */
KeysAreNotSynced = 1007,
/** Invalid arguments were provided. */
InvalidArgs = 1008,
/** Key shares are not provisioned on this device, is it necessary to recover them from a backup. */
KeysRecoveryIsNeeded = 1009,
/** User's key shares do not have a backup yet, which stores an encrypted copy of the user's key shares. */
KeysAreNotBackedUpWithEncryptionKey = 1010,
/** Configuration settings could not be applied. */
SetConfigurationFailed = 1011,
/** A provider required to perform this operation is missing. */
MissingProvider = 1012,
/** Failed to sign in to Google in order to back up or recover from Google Drive. */
GoogleSignInFailed = 1013,
/** Unexpected failure during the interaction with Google Drive API. */
GoogleDriveQueryExecutionFailed = 1014,
/** Failed to retrieve the decryption file from backup. */
DecryptionInfoRestoreFailed = 1015,
/** The decryption file retrieved from backup is corrupted. */
CorruptedDecryptionFile = 1016,
/** Failed to save the decryption key to the cloud provider. */
FailedSavingDecryptionKey = 1017,
/** @private */
ICloudDisabled = 1018,
/** @private */
ICloudNotSynchronized = 1019
}
/**
* @description Lets you receive errors encountered in the SDK and handle them.
* Alternatively, if you need to handle an error from a specific method call, catch the rejected promise and inspect the {@link FordefiError}` object.
* @interface
*/
export interface IFordefiErrorHandler {
/**
* @description Handle an error encountered in the SDK.
* @param {FordefiError} error Reported error.
*/
handleError: (error: FordefiError) => void;
}
/**
* @description Log level.
* @enum
*/
export enum FordefiLogLevel {
Verbose = "verbose",
Info = "info",
Warning = "warning",
Error = "error"
}
/**
* @description Logger interface. This interface gives a generic way to receive logs in the SDK and handle them.
* @interface
*/
export interface IFordefiLogger {
/**
* @description Log message of the SDK.
* @param {FordefiLogLevel} logLevel level.
* @param {string} message message.
*/
log: (logLevel: FordefiLogLevel, message: string) => void;
}
/**
* @description Fordefi backup option type.
* @enum
* Options are:
*
* - **ExternalEncryption**
* Allows a user to provide an external AES 256-bit symmetric key to the {@link Fordefi.backupKeys} function.
* Once the function is executed, an encrypted version of the user's key shares will be uploaded to the Fordefi platform.
* To recover the key shares user must provide the symmetric key to successfully decrypt the backup file.
*
* - **CloudProvider**
* Cloud backup provider to encrypt the share on the user's mobile device. Can be either iCloud or GoogleDrive.
*/
export enum FordefiBackupOptionType {
ExternalEncryption = "externalEncryption",
CloudProvider = "cloudProvider"
}
/**
* @description An AES-256 key to encrypt user's mobile device share.
* @enum
*/
export enum FordefiExternalEncryptionKeyType {
AES256 = "aes256"
}
/**
* @description External encryption information
* @interface
*/
export interface FordefiExternalEncryption {
key: string;
type: FordefiExternalEncryptionKeyType;
}
/**
* @description Backup providers. Can be either Google Drive or iCloud.
* @enum
*/
export enum FordefiBackupCloudProvider {
GoogleDrive = "googleDrive"
}
/**
* @description External key to encrypt the share on the user's mobile device.
* @interface
*/
export interface FordefiBackupOptionExternalEncryption {
type: FordefiBackupOptionType.ExternalEncryption;
encryption: FordefiExternalEncryption;
}
/**
* @description Cloud backup provider to encrypt the share on the user's mobile device. Can be either `iCloud` or `GoogleDrive`.
* @interface
* */
export interface FordefiBackupOptionCloudProvider {
type: FordefiBackupOptionType.CloudProvider;
provider: FordefiBackupCloudProvider;
}
/**
* @description Backup options
* @type
* Options are **FordefiBackupOptionExternalEncryption** or **FordefiBackupOptionCloudProvider**
*/
export type FordefiBackupOptions = FordefiBackupOptionExternalEncryption | FordefiBackupOptionCloudProvider;
/**
* @description Key types
* @enum
*/
export enum FordefiKeyType {
EDDSA = "eddsa",
STARK = "ecdsa_stark",
ECDSA = "ecdsa"
}
/**
* Detailed information about an error in the Fordefi SDK.
* @property code The error code associated with the error.
*/
export interface FordefiErrorDetails {
/**
* The error code associated with the error.
*/
code: FordefiErrorCode;
/**
* A descriptive message providing general information about the error.
*/
text: string;
/**
* Additional details about the error.
* Can include any extra information relevant to the error.
*/
details: AnyRecord & {
/**
* An optional internal error code for more granular error tracking and debugging.
* This code is used within the platform and is not designed for use by SDK clients.
*/
internal_error_code?: string;
};
}
/**
* @description Represents configuration for initializing the SDK.
* @interface
* @property {string} baseURL Base URL of the Fordefi server (backend). Use the default value: https://api.fordefi.com. In the event that you need to connect to a different Fordefi environment, consult with Technical Support.
*/
export interface FordefiConfiguration {
baseURL: string;
skipFordefiVerification?: boolean;
}
/**
* @description
* Indicates whether the user's key shares are provisioned on the current device,
* and whether the device is ready to perform MPC operations, such as signing transactions.
* States other than {@link DeviceState.NoOperationRequired} indicate that an additional operation is required.
*
* @enum
* @property NoOperationRequired Key shares on this device have a backup and are provisioned on the current device.
* @property DeviceStateBackupRequired Key shares on this device were not backed up yet. Backup is mandatory to enable MPC operations.
* @property DeviceStateRecoveryRequired Key shares are not provisioned on the current device. Recover the keys into the current device from a backup.
* @property DeviceStateError Current device is in unexpected error state.
*/
export enum DeviceState {
NoOperationRequired = "NO_OPERATION_REQUIRED",
DeviceStateBackupRequired = "BACKUP_REQUIRED",
DeviceStateRecoveryRequired = "RECOVERY_REQUIRED",
DeviceStateError = "ERROR"
}
/**
* @description The response from the login.
* @interface
* @property {string} userID The userId of the logged-in user.
* @property {DeviceState} deviceState Indicates if and what manual operation is required after performing the login.
* @property {string} keysetID The ID of the user's keyset.
*/
export interface LoginResponse {
userID: string;
deviceState: DeviceState;
keysetID: string;
}
/**
* @description A record of an exported vault
* @interface
* @property {string} vault_id ID of the vault
* @property {string} private_key_hex the private key encoded as a hex string
* @property {string} address the vault address
*/
export interface ExportedVault {
vault_id: string;
private_key_hex: string;
address: string;
}
/**
* @description The result of exporting the user private keys.
* @interface
* @property {ExportedVault[]} keys List of vaults.
*/
export interface ExportEndUserKeysResponse {
vaults: ExportedVault[];
}
/**
* @description An SDK error.
* @type
*/
export interface FordefiError {
code: FordefiErrorCode;
details: FordefiErrorDetails;
}
/**
* @description Fordefi SDK API. Used as a singleton by calling the static method `getInstance()`.
* @class
*/
export class Fordefi {
/**
* @description Initialize a Fordefi SDK instance using the given configuration.
* @param {FordefiConfiguration} configuration The configuration to connect to at client load.
* @returns {Fordefi} A singleton instance of the API.
*/
static getInstance(configuration: FordefiConfiguration): Fordefi;
/**
* @description Log into the Fordefi client using the given auth token.
*
* The auth token is acquired using a call to the [Issue Authorization Token](https://docs.fordefi.com/reference/issue_authorization_token_api_v1_authorization_tokens_post) REST API.
* @param {string} authToken The auth token to use for login.
* @param {FordefiKeyType[]} keyTypes The key types required to sign transactions. Any key type that doesn't yet exist will be generated during login. Use only the key types you need to reduce the time spent on key generation.
* @returns {Promise<LoginResponse>} A Promise that resolves when the login operation is successful.
* Notice that in order to perform any further interactions with the SDK, the `deviceState` that returns must be `NO_OPERATION_REQUIRED`,
* otherwise an action is required based on the current device state.
*/
login(authToken: string, keyTypes?: FordefiKeyType[]): Promise<LoginResponse>;
/**
* @description Create a backup for key shares located on your device. If a backup already exists, the new backup replaces it.
* @param {FordefiBackupOptions} options Backup options. Specify either an external backup or a cloud backup.
* @returns {Promise<void>} A Promise that resolves when the backup operation is successful.
*/
backupKeys(options: FordefiBackupOptions): Promise<void>;
/**
* @description Retrieve the encrypted shares, decrypt, and "load" them to the SDK to be used as part of the recovery for users.
*
* For more information, see [End User Backup and Recovery](https://docs.fordefi.com/reference/end-user-backup-and-recovery).
*
* @param {FordefiBackupOptions} options The backup options.
* @returns {Promise<void>} A Promise that resolves when the recover operation is successful.
*/
recoverKeys(options: FordefiBackupOptions): Promise<void>;
/**
* @description Export all user's private keys.
*
* @returns {Promise<ExportEndUserKeysResponse>} A Promise that resolves with a list of all vaults, each having its private key along with additional vault details.
*/
exportKeys(): Promise<ExportEndUserKeysResponse>;
/**
* @description Sign a transaction using the given transaction ID.
*
* As part of this process, the mobile app and Fordefi servers run an MPC protocol that signs the transaction. The transaction must have been previously created using a call to the [Create Transaction](https://docs.fordefi.com/reference/create_transaction_api_v1_transactions_post-1) REST API.
* @param {string} transactionID The ID of the transaction to sign.
* @returns {Promise<void>} A Promise that resolves when the signing operation is successful.
*/
signTransaction(transactionID: string): Promise<void>;
/**
* @description Set error handler.
*
* Error events that the client or application can receive after a call to `setErrorHandler()`
*
* For more information, see [Add error handling](https://docs.fordefi.com/reference/react-native#add-error-handling).
*/
setErrorHandler(errorHandler: IFordefiErrorHandler): void;
/**
* @description Set logger.
*
* Fordefi does not print logs to the console.
* If the application (client) wants to receive logs, it must call the `setLogger`
* with the desired log level.
*
* For more information, see [Add logging](https://docs.fordefi.com/reference/react-native#add-logging).
*/
setLogger(logger: IFordefiLogger): void;
}
/**
* @description Represents the configuration for initializing backup cloud providers.
* @interface
* @property {} googleDrive Google drive configuration: client ID and API key.
*/
export interface FordefiBackupCloudProvidersConfiguration {
googleDrive?: {
clientID: string;
apiKey: string;
};
}
/**
* @description Fordefi backup cloud providers API. Used as a singleton by calling the static method `getInstance()`.
* @class
*/
export class FordefiBackupCloudProviders {
static getInstance(): FordefiBackupCloudProviders;
/**
* @description Initialize the Fordefi backup cloud providers API .
*
* @param {FordefiBackupCloudProvidersConfiguration} configuration Backup providers configuration.
* @returns {Promise<void>} A Promise that resolves when the initialization operation is successful.
*/
initialize(configuration: FordefiBackupCloudProvidersConfiguration): Promise<void>;
}
export type MPCWorkerOutMessage = MPCWorkerOutMPCCallbackMessage | MPCWorkerOutConfigurationMessage | MPCWorkerOutAuthTokenMessage | MPCWorkerOutListAllKeysMessage | MPCWorkerOutGetKeysMessage | MPCWorkerOutStoreKeysMessage | MPCWorkerOutLogMessage | MPCWorkerOutReportErrorMessage;
export interface MPCWorkerInMPCRequestMessage {
type: MPCWorkerInMessageType.MPCRequest;
payload: LibInRequest;
}
export interface MPCWorkerInConfigurationMessage {
type: MPCWorkerInMessageType.ConfigurationResult;
contextId: string;
payload?: FordefiConfiguration;
}
export interface MPCWorkerInAuthTokenMessage {
type: MPCWorkerInMessageType.AuthTokenResult;
contextId: string;
payload?: string;
}
export interface MPCWorkerInListAllKeysResultMessage {
type: MPCWorkerInMessageType.ListAllKeysResult;
contextId: string;
payload: Map<string, string>;
}
export interface MPCWorkerInGetKeysResultMessage {
type: MPCWorkerInMessageType.GetKeysResult;
contextId: string;
payload: Array<string | undefined>;
}
export interface MPCWorkerInStoreKeysResultMessage {
type: MPCWorkerInMessageType.StoreKeysResult;
contextId: string;
payload: undefined;
}
export type MPCWorkerInInternalMessage = MPCWorkerInConfigurationMessage | MPCWorkerInAuthTokenMessage | MPCWorkerInListAllKeysResultMessage | MPCWorkerInGetKeysResultMessage | MPCWorkerInStoreKeysResultMessage;
export type MPCWorkerInMessage = MPCWorkerInMPCRequestMessage | MPCWorkerInInternalMessage;
export type AnyRecord = Record<string, any>;
export enum MPCWorkerOutMessageType {
MPCCallback = "mpcCallback",
Configuration = "configuration",
AuthToken = "authToken",
ListAllKeys = "listAllKeys",
GetKeys = "getKeys",
StoreKeys = "StoreKeys",
Log = "log",
ReportError = "reportError"
}
export enum MPCInvocationStatus {
Completed = "completed",
Failed = "failed",
Progress = "progress"
}
export enum MPCWorkerInMessageType {
MPCRequest = "mpcRequest",
ConfigurationResult = "configurationResult",
AuthTokenResult = "authTokenResult",
ListAllKeysResult = "listAllKeysResult",
GetKeysResult = "getKeysResult",
StoreKeysResult = "StoreKeysResult"
}
export enum SdkComponent {
Page = "page",
Worker = "worker",
Lib = "lib"
}
/**
* Error code returned in lib errors
*/
export enum InternalErrorCode {
InvalidArgs = "invalid_args",
ApiRequestError = "api_request_error",
InternalError = "internal_error",
InvalidAuthToken = "invalid_auth_token",
UnauthorizedRequest = "unauthorized_request",
UserNotFound = "user_not_found",
PreconditionError = "precondition_error",
KeysAreNotSynced = "keys_are_not_synced",
KeysRecoveryIsNeeded = "keys_recovery_is_needed",
KeyDecryptFailed = "key_decrypt_failed",
KeysAreNotBackedUpWithEncryptionKey = "keys_are_not_backed_up_with_encryption_key",
TransactionNotFound = "transaction_not_found"
}
export interface MPCWorkerOutConfigurationMessage {
type: MPCWorkerOutMessageType.Configuration;
contextId: string;
}
export interface MPCWorkerOutAuthTokenMessage {
type: MPCWorkerOutMessageType.AuthToken;
contextId: string;
}
export interface MPCWorkerOutListAllKeysMessage {
type: MPCWorkerOutMessageType.ListAllKeys;
contextId: string;
}
export interface MPCWorkerOutGetKeysMessage {
type: MPCWorkerOutMessageType.GetKeys;
contextId: string;
names: string[];
}
export interface MPCWorkerOutStoreKeysMessage {
type: MPCWorkerOutMessageType.StoreKeys;
contextId: string;
keys: Map<string, string>;
}
export interface MPCWorkerOutLogMessage {
type: MPCWorkerOutMessageType.Log;
logLevel: FordefiLogLevel;
message: string;
}
export interface MPCWorkerOutReportErrorMessage {
type: MPCWorkerOutMessageType.ReportError;
error: FordefiError;
}
export interface MPCWorkerOutMPCCallbackMessageSuccess<T extends AnyRecord = AnyRecord> {
type: MPCWorkerOutMessageType.MPCCallback;
contextId: string;
status: MPCInvocationStatus.Completed;
data: {
status: MPCInvocationStatus.Completed;
info?: string;
result: T;
};
}
export interface MPCWorkerOutMPCCallbackMessageFailure {
type: MPCWorkerOutMessageType.MPCCallback;
contextId: string;
status: MPCInvocationStatus.Failed;
data: {
status: MPCInvocationStatus.Failed;
error: string;
};
}
export interface MPCWorkerOutMPCCallbackMessageProgress {
type: MPCWorkerOutMessageType.MPCCallback;
contextId: string;
status: MPCInvocationStatus.Progress;
data: {
status: MPCInvocationStatus.Progress;
info?: string;
result?: AnyRecord;
};
}
export type MPCWorkerOutMPCCallbackMessage = MPCWorkerOutMPCCallbackMessageSuccess | MPCWorkerOutMPCCallbackMessageFailure | MPCWorkerOutMPCCallbackMessageProgress;
interface APIErrorDetails {
detail: string;
request_id: string;
title: string;
status_code: number;
}
interface AnyMpcError {
internalErrorCode: InternalErrorCode;
message: string;
details?: AnyRecord;
}
export type LibError = AnyMpcError & ({
internalErrorCode: InternalErrorCode.ApiRequestError;
details: APIErrorDetails;
} | {
internalErrorCode: Exclude<InternalErrorCode, InternalErrorCode.ApiRequestError>;
details?: AnyRecord;
});
export type LibApiRequestError = LibError & {
internalErrorCode: InternalErrorCode.ApiRequestError;
};
export {};
/**
* Incoming messages to the mpc lib (wasm).
* The request can either be triggered by the worker (as in worker --> lib),
* or by the page and be passed-through to the lib (as in page --> worker --> lib).
*/
export interface LibInRequest {
function_name: string;
function_args: AnyRecord;
context_id?: string;
metadata?: AnyRecord;
}
/**
* Dispatcher worker <--> lib that responds asynchronously to a request with a callback
*/
export interface LibDispatcherCallback {
callback: (contextId: string, status: MPCInvocationStatus, data: AnyRecord) => void;
}
export type LibRequestPayload = AnyRecord & {
id: string;
args: AnyRecord;
};
/**
* @description Custom error class for the SDK.
* Notice this class is not public, the error object clients get matches {@link PublicFordefiError}.
* @class
*/
export class FordefiError extends Error implements PublicFordefiError {
_code: FordefiErrorCode;
_details: FordefiErrorDetails['details'];
_component: SdkComponent;
/**
* @description Initialize a new error instance.
* @param {SdkComponent} component originating component who threw the error
* @param {FordefiErrorCode} code The error code
* @param {LibError | string} error The error message as a plain string or stringified MpcError
*/
constructor(component: SdkComponent, code: FordefiErrorCode, error: LibError | string);
/**
* @description Returns an error code representing a specific reason for the error.
* @returns {FordefiErrorCode} The error code
*/
get code(): FordefiErrorCode;
/**
* @description The details regarding the error.
* @returns {FordefiErrorDetails} details about the error.
*/
get details(): FordefiErrorDetails;
}
}