import { EcdsaSignature, MessageHash, type EcdsaPublicKey } from '#internal/web';
import { AuthMode, BackupLocation, DynamicApiClient, BusinessAccountClient, type TargetSignerIdentity, type BusinessAccountSignerType, ThresholdSignatureScheme, WalletOperation, type Argon2idRebackupTarget, type BackupLocationWithExternalKeyShareId, type BitcoinConfig, type DynamicWalletClientProps, type FeatureFlags, type GetWalletResponse, type ILogger, type InitializeResult, type KeyShareBackupInfo, type SecureStorageAdapter, type ShareSet, type ShareSetType, type TraceContext, type WalletRecoveryState, type CreateWaasSDKContainer } from '@dynamic-labs-wallet/core';
import { RoomTypeEnum, type SignMessageContext } from '@dynamic-labs/sdk-api-core';
import { EncryptionVersion } from './backup/encryption/constants.js';
import type { DerivationInputFingerprint } from './backup/encryption/types.js';
import type { ClientInitKeygenResult, ClientKeyShare, MPCSigner } from './mpc/types.js';
import { type SupportedStorage } from './services/localStorage.js';
import { OperationSource, type Room, type ShareDistribution, type WalletProperties } from './types.js';
type MessageToSign = string | Uint8Array | MessageHash;
/**
 * Internal options for DynamicWalletClient constructor.
 * This is NOT part of the public API.
 */
export interface DynamicWalletClientInternalOptions {
    secureStorage?: SecureStorageAdapter;
    /**
     * Callback to lazily retrieve a signed session ID via the host reverse channel.
     * When provided, it is called instead of using a pre-computed signedSessionId string
     * at the point where the backup API call is made.
     */
    getSignedSessionId?: () => Promise<string>;
    createWaasSDKContainer?: CreateWaasSDKContainer;
    /**
     * Invoked when a backend call returns 401. Passed via internalOptions (not
     * props) because the per-chain wallet clients forward internalOptions to
     * `super` verbatim, whereas they only forward an explicit subset of props.
     */
    onUnauthorized?: () => void;
}
export declare class DynamicWalletClient {
    environmentId: string;
    storageKey: string;
    debug: boolean;
    protected userId: string | undefined;
    protected sessionId: string | undefined;
    protected initializePromise: Promise<InitializeResult> | null;
    protected logger: ILogger;
    protected apiClient: DynamicApiClient;
    /** Business-account orchestration (create/list/get + member/signer ops). */
    readonly businessAccounts: BusinessAccountClient;
    protected walletMap: Record<string, WalletProperties>;
    protected storage: SupportedStorage;
    protected memoryStorage: {
        [key: string]: string;
    } | null;
    protected baseMPCRelayApiUrl?: string;
    protected iframe: HTMLIFrameElement | null;
    protected forwardMPCEnabled: boolean;
    readonly instanceId: string;
    readonly iframeDomain: string;
    readonly featureFlags: FeatureFlags;
    /** Targets for the one-off Argon2id (v3) re-backup; see {@link maybeRunArgon2idRebackup}. */
    protected readonly argon2idRebackupTargets: Argon2idRebackupTarget[];
    /** Guards the one-off Argon2id re-backup so it runs at most once per client instance. */
    private argon2idRebackupAttempted;
    protected authMode: AuthMode;
    protected sdkVersion?: string;
    protected baseClientKeysharesRelayApiUrl?: string;
    protected static rooms: Record<number, Room[]>;
    protected static roomsInitializing: Record<number, boolean>;
    private static roomsPersistChain;
    private static roomsGeneration;
    /**
     * Internal secure storage adapter for mobile TEE-backed storage.
     * When set, all key share operations use this instead of localStorage.
     * This is NOT part of the public API.
     */
    private readonly secureStorage?;
    /**
     * Lazy callback to retrieve a signed session ID from the host via reverse channel.
     * Used in backupToDynamicBackend when signedSessionId is not pre-computed.
     * This is NOT part of the public API.
     */
    private readonly getSignedSessionIdCallback?;
    /** Owns signed-session resolution, version-gating, and nonce-refresh retries. */
    private readonly signedSession;
    constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, storageKey, debug, featureFlags, argon2idRebackupTargets, authMode, authToken, backupServiceAuthToken, sdkVersion, forwardMPCClient, baseClientKeysharesRelayApiUrl, iCloudConfig, logger, }: DynamicWalletClientProps, internalOptions?: DynamicWalletClientInternalOptions);
    /**
     * Check if wallet has heavy operations in progress
     */
    static isHeavyOpInProgress(accountAddress: string): boolean;
    /**
     * Check if wallet has operations in any queue (heavy or sign)
     */
    static isWalletBusy(accountAddress: string): boolean;
    /**
     * Check if recovery is in progress for a wallet
     */
    static isRecoveryInProgress(accountAddress: string): boolean;
    /**
     * Clear the in-memory MPC room pool.
     *
     * Rooms are cached in process-global static state and are pre-created without
     * being bound to a wallet or user. They must be cleared whenever iframe
     * storage is cleared on a user switch, otherwise a room created during one
     * user's session can be reused in another user's signing ceremony, pairing a
     * shared server key share with the wrong client key share.
     */
    static clearRoomPool(): void;
    /**
     * Reset static state for testing purposes.
     * This clears all wallet queues, in-flight recovery tracking, and the room pool.
     * @internal For testing only
     */
    static resetStaticState(): void;
    /**
     * Get wallet properties from the wallet map using normalized address.
     * Normalizes the address to lowercase for consistent lookups regardless of input casing.
     */
    protected getWalletFromMap(accountAddress: string): WalletProperties | undefined;
    /**
     * Get wallet properties from the map, refetching once if not found.
     * Uses getWallet (with NO_OPERATION) when signedSessionId is available for a
     * more robust fetch, otherwise falls back to getWallets().
     */
    protected requireWalletFromMap(accountAddress: string, signedSessionId?: string): Promise<WalletProperties>;
    /**
     * Update wallet properties in the wallet map using normalized address.
     * Normalizes the address to lowercase for consistent storage regardless of input casing.
     */
    protected updateWalletMap(accountAddress: string, updates: Partial<WalletProperties>): void;
    getAuthMode(): AuthMode;
    /**
     * Get environment settings from the API client.
     * Used to retrieve configuration like iCloud settings.
     */
    getEnvironmentSettings(): Promise<any>;
    /**
     * Check if the SDK version meets the requirement for signed session ID
     * Uses namespace-specific version requirements when available
     * @returns boolean indicating if requireSignedSessionId should be set to true
     */
    /** @see SignedSessionManager.isRequired */
    private requiresSignedSessionId;
    initLoggerContext(authToken: string): Promise<void>;
    initialize(traceContext?: TraceContext): Promise<InitializeResult>;
    /**
     * Client initialization logic
     */
    protected _initialize(traceContext?: TraceContext): Promise<InitializeResult>;
    serverInitializeKeyGen({ chainName, clientKeygenIds, dynamicRequestId, thresholdSignatureScheme, bitcoinConfig, businessAccountId, onError, onCeremonyComplete, }: {
        chainName: string;
        clientKeygenIds: string[];
        dynamicRequestId: string;
        thresholdSignatureScheme: ThresholdSignatureScheme;
        bitcoinConfig?: BitcoinConfig;
        businessAccountId?: string;
        onError?: (error: Error) => void;
        onCeremonyComplete?: (accountAddress: string, walletId: string, shareSetId?: string) => void;
    }): Promise<import("@dynamic-labs-wallet/core").KeygenCompleteResponse>;
    clientInitializeKeyGen({ chainName, thresholdSignatureScheme, bitcoinConfig, }: {
        chainName: string;
        thresholdSignatureScheme: ThresholdSignatureScheme;
        bitcoinConfig?: BitcoinConfig;
    }): Promise<ClientInitKeygenResult[]>;
    derivePublicKey({ chainName, keyShare, derivationPath, bitcoinConfig, }: {
        chainName: string;
        keyShare: ClientKeyShare;
        derivationPath: Uint32Array | undefined;
        bitcoinConfig?: BitcoinConfig;
    }): Promise<EcdsaPublicKey | Uint8Array | string | undefined>;
    /**
     * Drop-in replacement for clientKeygen that routes to forwardMPC keygen or receiveKey as appropriate,
     * using identical params and matching clientKeygen toggling logic based on the chain.
     * Returns both the raw public key and the array of new client key shares.
     *
     * @param chainName The blockchain chain name (e.g., EVM, SVM).
     * @param roomId The keygen "room" identifier (usually created by the server).
     * @param serverKeygenIds The keygen IDs from server parties.
     * @param clientKeygenInitResults The array of initial keygen values from the MPC library.
     * @param thresholdSignatureScheme The signature threshold scheme to use for keygen.
     * @param bitcoinConfig Optional config for bitcoin keygen.
     * @param dynamicRequestId Used for tracing/logging.
     * @param traceContext Additional tracing context.
     * @returns An object containing the derived rawPublicKey and all clientKeygenResults.
     */
    forwardMPCClientKeygen({ chainName, roomId, serverKeygenIds, clientKeygenInitResults, thresholdSignatureScheme, bitcoinConfig, dynamicRequestId, traceContext, }: {
        chainName: string;
        roomId: string;
        serverKeygenIds: string[];
        clientKeygenInitResults: ClientInitKeygenResult[];
        thresholdSignatureScheme: ThresholdSignatureScheme;
        bitcoinConfig?: BitcoinConfig;
        dynamicRequestId?: string;
        traceContext?: TraceContext;
    }): Promise<{
        rawPublicKey: EcdsaPublicKey | Uint8Array | string | undefined;
        clientKeygenResults: ClientKeyShare[];
        operationSource: OperationSource;
    }>;
    /** Forward MPC does not support Aleo yet; use relay MPC until it does. */
    private shouldSkipForwardMPC;
    clientKeyGen({ chainName, roomId: initialRoomId, serverKeygenIds: initialServerKeygenIds, clientKeygenInitResults, thresholdSignatureScheme, bitcoinConfig, dynamicRequestId, traceContext, refreshRoom, }: {
        chainName: string;
        roomId: string;
        serverKeygenIds: string[];
        clientKeygenInitResults: ClientInitKeygenResult[];
        thresholdSignatureScheme: ThresholdSignatureScheme;
        bitcoinConfig?: BitcoinConfig;
        dynamicRequestId?: string;
        traceContext?: TraceContext;
        /**
         * Mints a fresh, server-joined room (and its server keygen ids). Called
         * before falling back from forward MPC to relay-based keygen so the relay
         * ceremony does not reuse the room the forward enclave already joined.
         */
        refreshRoom?: () => Promise<{
            roomId: string;
            serverKeygenIds: string[];
        }>;
    }): Promise<{
        rawPublicKey: EcdsaPublicKey | Uint8Array | string | undefined;
        clientKeygenResults: ClientKeyShare[];
        operationSource: OperationSource;
    }>;
    keyGen(args: {
        chainName: string;
        thresholdSignatureScheme: ThresholdSignatureScheme;
        bitcoinConfig?: BitcoinConfig;
        businessAccountId?: string;
        onError?: (error: Error) => void;
        onCeremonyComplete?: (accountAddress: string, walletId: string) => void;
        traceContext?: TraceContext;
        password?: string;
        signedSessionId: string;
    }): Promise<{
        rawPublicKey: EcdsaPublicKey | Uint8Array | string | undefined;
        clientKeyShares: ClientKeyShare[];
    }>;
    private runKeyGenAttempt;
    importRawPrivateKey(args: {
        chainName: string;
        privateKey: string;
        thresholdSignatureScheme: ThresholdSignatureScheme;
        bitcoinConfig?: BitcoinConfig;
        onError?: (error: Error) => void;
        onCeremonyComplete?: (accountAddress: string, walletId: string) => void;
        traceContext?: TraceContext;
        /** ID of the legacy embedded wallet being upgraded to v3 */
        legacyWalletId?: string;
        password?: string;
        signedSessionId: string;
    }): Promise<{
        rawPublicKey: EcdsaPublicKey | Uint8Array | string | undefined;
        clientKeyShares: ClientKeyShare[];
    }>;
    private runImportRawPrivateKeyAttempt;
    serverSign({ walletId, shareSetId, message, isFormatted, mfaToken, elevatedAccessToken, roomId, context, onError, dynamicRequestId, traceContext, bitcoinConfig, }: {
        walletId: string;
        shareSetId?: string;
        message: string | Uint8Array;
        dynamicRequestId: string;
        isFormatted?: boolean;
        mfaToken?: string;
        elevatedAccessToken?: string;
        roomId?: string;
        context?: SignMessageContext;
        onError?: (error: Error) => void;
        traceContext?: TraceContext;
        bitcoinConfig?: BitcoinConfig;
    }): Promise<import("@dynamic-labs-wallet/core").OpenRoomResponse>;
    private prepareMessageForForwardMPC;
    private convertTweakForBIP340;
    private processForwardMPCSignature;
    forwardMPCClientSign({ chainName, message, roomId, keyShare, derivationPath, formattedMessage, dynamicRequestId, isFormatted, traceContext, bitcoinConfig, }: {
        chainName: string;
        message: string | Uint8Array;
        roomId: string;
        keyShare: ClientKeyShare;
        derivationPath: Uint32Array | undefined;
        formattedMessage: MessageToSign;
        dynamicRequestId: string;
        isFormatted?: boolean;
        traceContext?: TraceContext;
        bitcoinConfig?: BitcoinConfig;
    }): Promise<Uint8Array | EcdsaSignature>;
    clientSign({ chainName, message, roomId: initialRoomId, keyShare, derivationPath, isFormatted, dynamicRequestId, traceContext, bitcoinConfig, refreshRoom, }: {
        chainName: string;
        message: string | Uint8Array;
        roomId: string;
        dynamicRequestId: string;
        keyShare: ClientKeyShare;
        derivationPath: Uint32Array | undefined;
        isFormatted?: boolean;
        traceContext?: TraceContext;
        bitcoinConfig?: BitcoinConfig;
        /**
         * Mints a fresh, server-joined room. Called before falling back from
         * forward MPC to relay-based signing so the relay ceremony does not reuse
         * the room the forward enclave already joined (which made the client join
         * the same room twice).
         */
        refreshRoom?: () => Promise<string>;
    }): Promise<Uint8Array | EcdsaSignature>;
    /**
     * On public-key mismatch, restore local shares from backup and rethrow so
     * the caller's next call (with refreshed shares) succeeds. Auto-retry was
     * removed because in the iframe transport the error response is already
     * posted to the host before any retry can resolve.
     * Passthrough for non-mismatch errors.
     */
    private recoverKeySharesOnMismatch;
    sign({ accountAddress, message, chainName, password, isFormatted, signedSessionId, mfaToken, elevatedAccessToken, context, onError, traceContext, bitcoinConfig, }: {
        accountAddress: string;
        message: string | Uint8Array;
        chainName: string;
        password?: string;
        isFormatted?: boolean;
        signedSessionId: string;
        mfaToken?: string;
        elevatedAccessToken?: string;
        context?: SignMessageContext;
        onError?: (error: Error) => void;
        traceContext?: TraceContext;
        bitcoinConfig?: BitcoinConfig;
    }): Promise<Uint8Array | EcdsaSignature>;
    private internalSign;
    refreshWalletAccountShares({ accountAddress, chainName, password, signedSessionId, mfaToken, elevatedAccessToken, traceContext, }: {
        accountAddress: string;
        chainName: string;
        password?: string;
        signedSessionId: string;
        mfaToken?: string;
        elevatedAccessToken?: string;
        traceContext?: TraceContext;
    }): Promise<void>;
    /**
     * Resolves backup locations for a reshare operation.
     *
     * When reshareOnNextSignOn triggers (e.g., after Google OAuth refresh), the caller
     * doesn't pass backup parameters. This method detects that case and preserves the
     * wallet's existing backup locations (Google Drive, iCloud, delegation) instead of
     * proceeding with empty backup locations.
     *
     * @returns The backup locations to use for the reshare operation
     */
    private resolveBackupLocationsForReshare;
    /**
     * Gets the Bitcoin config for MPC operations by looking up addressType
     * from walletMap, with fallback to deriving it from derivationPath.
     */
    private getBitcoinConfigForChain;
    private internalRefreshWalletAccountShares;
    private getKeygenIdForShare;
    getExportId({ chainName, clientKeyShare, bitcoinConfig, }: {
        chainName: string;
        clientKeyShare: ClientKeyShare;
        bitcoinConfig?: BitcoinConfig;
    }): Promise<string>;
    /**
     * Helper function to create client shares required to complete a reshare ceremony.
     * @param {string} chainName - The chain to create shares for
     * @param {WalletProperties} wallet - The wallet to reshare
     * @param {ThresholdSignatureScheme} oldThresholdSignatureScheme - The current threshold signature scheme
     * @param {ThresholdSignatureScheme} newThresholdSignatureScheme - The target threshold signature scheme
     * @returns {Promise<{
     *   newClientInitKeygenResults: ClientInitKeygenResult[],
     *   newClientKeygenIds: string[],
     *   existingClientKeygenIds: string[],
     *   existingClientKeyShares: ClientKeyShare[]
     * }>} Object containing new and existing client keygen results, IDs and shares
     * @todo Support higher to lower reshare strategies
     */
    reshareStrategy({ chainName, wallet, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, delegateToProjectEnvironment, }: {
        chainName: string;
        wallet: WalletProperties;
        accountAddress: string;
        oldThresholdSignatureScheme: ThresholdSignatureScheme;
        newThresholdSignatureScheme: ThresholdSignatureScheme;
        delegateToProjectEnvironment?: boolean;
    }): Promise<{
        newClientInitKeygenResults: ClientInitKeygenResult[];
        newClientKeygenIds: string[];
        existingClientKeygenIds: string[];
        existingClientKeyShares: ClientKeyShare[];
    }>;
    reshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password, signedSessionId, cloudProviders, delegateToProjectEnvironment, mfaToken, elevatedAccessToken, revokeDelegation, googleDriveAccessToken, googleDriveTokenSource, }: {
        chainName: string;
        accountAddress: string;
        oldThresholdSignatureScheme: ThresholdSignatureScheme;
        newThresholdSignatureScheme: ThresholdSignatureScheme;
        password?: string;
        signedSessionId: string;
        cloudProviders?: BackupLocation[];
        delegateToProjectEnvironment?: boolean;
        mfaToken?: string;
        elevatedAccessToken?: string;
        revokeDelegation?: boolean;
        googleDriveAccessToken?: string;
        googleDriveTokenSource?: 'external' | 'stored_oauth';
    }): Promise<void>;
    /** Reshare into a new 2/2 share set for the target signer; seed it to CKS
     *  on their behalf via a single-use grant. Does not touch the caller's set. */
    reshareToNewSignerShareSet({ chainName, accountAddress, businessAccountId, signerType, targetSignerIdentity, password, signedSessionId, }: {
        chainName: string;
        accountAddress: string;
        businessAccountId: string;
        signerType?: BusinessAccountSignerType;
        targetSignerIdentity: TargetSignerIdentity;
        password?: string;
        signedSessionId: string;
    }): Promise<{
        shareSetId: string;
    }>;
    private logOnMalformedCeremonyPayload;
    /**
     * Ceremony-complete payload — typed object so addSigner-only fields are
     * namespaced and `clientKeyshareBackupGrant` never sits in a positional slot.
     */
    private createCeremonyTerminalGate;
    private runBackupWithRotationRollback;
    private rotateRootUserShareSetIdIfChanged;
    private recordDelegatedShareSet;
    private removeDelegatedShareSetFromWalletMap;
    private internalReshare;
    private performDelegationOperation;
    delegateKeyShares({ accountAddress, password, signedSessionId, mfaToken, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
        mfaToken?: string;
    }): Promise<BackupLocationWithExternalKeyShareId[]>;
    revokeDelegation({ accountAddress, password, signedSessionId, mfaToken, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
        mfaToken?: string;
    }): Promise<void>;
    private createKeygenResult;
    exportKey({ accountAddress, chainName, bitcoinConfig, password, signedSessionId, mfaToken, elevatedAccessToken, traceContext, }: {
        accountAddress: string;
        chainName: string;
        bitcoinConfig?: BitcoinConfig;
        password?: string;
        signedSessionId: string;
        mfaToken?: string;
        elevatedAccessToken?: string;
        traceContext?: TraceContext;
    }): Promise<{
        derivedPrivateKey: string | undefined;
    }>;
    protected getReconstructedKeyShare(accountAddress: string, mpcSigner: MPCSigner): Promise<ClientKeyShare>;
    protected performMPCExport(mpcSigner: MPCSigner, reconstructedKeyShare: ClientKeyShare, roomId: string, exportId: string, accountAddress: string, chainName: string): Promise<string>;
    protected derivePrivateKeyFromExport(mpcSigner: MPCSigner, keyExportRaw: string, wallet: WalletProperties): Promise<string | undefined>;
    offlineExportKey({ chainName, keyShares, derivationPath, }: {
        chainName: string;
        keyShares: ClientKeyShare[];
        derivationPath?: string;
    }): Promise<{
        derivedPrivateKey: string | undefined;
        rawPublicKey: EcdsaPublicKey | Uint8Array | string | undefined;
    }>;
    private assertEncryptionRoundTrip;
    /**
     * Diagnostics for backup self-test failures. ONLY runs on the envId-default
     * path (no user password): envId is public, so the salt/iv/version emitted
     * here are non-secret.
     *
     * Reuses the encrypt- and decrypt-side keys that the backup already derived
     * (no extra Argon2 work — important, since the failing clients are the
     * memory-constrained ones) and logs the byte-wise XOR of the two: equal keys
     * give an all-zero diff, any non-zero byte localises the Argon2id drift that
     * broke this round-trip. The XOR of two unknown keys is not usable key
     * material, and the raw keys are never logged.
     */
    private logSelfTestDiagnostics;
    /**
     * Post-backup recoverability check (feature-flagged). Where
     * `assertEncryptionRoundTrip` only proves the cipher decrypts in-process,
     * this fetches the just-stored share back from the keyshare service and
     * confirms it decrypts to the same secret we hold in memory — exercising the
     * real store → fetch → decrypt path the user will rely on to recover.
     *
     * The local share is never deleted: a failed/flaky fetch must not be able to
     * lose the only client copy. A genuine decrypt failure or a value mismatch is
     * terminal (`EncryptionSelfTestFailedError`, aborting the backup). A transient
     * fetch failure means the check couldn't run — it is rethrown as-is so it
     * stays visible and retryable rather than masquerading as "unrecoverable".
     */
    private assertServerCopyRecoverable;
    encryptKeyShare({ keyShare, password, onRawKey, version, }: {
        keyShare: ClientKeyShare;
        password?: string;
        /** In-process hook receiving the raw derived key bytes (key material, never log) + input fingerprint. */
        onRawKey?: (rawKey: Uint8Array, inputFingerprint: DerivationInputFingerprint) => void;
        /** Encryption version to use. Defaults to the current default (v3) when omitted. */
        version?: EncryptionVersion;
    }): Promise<string>;
    /**
     * helper function to store encrypted backup by wallet from iframe local storage
     */
    private getClientKeySharesFromLocalStorage;
    /**
     * Helper function to get client key shares from storage.
     * Uses secureStorage when available (mobile), otherwise falls back to localStorage (browser).
     */
    getClientKeySharesFromStorage({ accountAddress }: {
        accountAddress: string;
    }): Promise<ClientKeyShare[]>;
    /**
     * Helper function to initialize a wallet map entry during onCeremonyComplete.
     * This is called before any backup has happened, so it initializes with empty backup info.
     * The backup info gets updated later in storeEncryptedBackupByWallet.
     *
     * @param accountAddress - The wallet address
     * @param walletId - The wallet ID from the server
     * @param chainName - The chain name (e.g., 'EVM', 'SVM', 'BTC')
     * @param thresholdSignatureScheme - The TSS scheme used
     * @param derivationPath - Optional derivation path (will be computed from chainConfig if not provided)
     * @param additionalProps - Any chain-specific additional properties to merge
     */
    protected initializeWalletMapEntry({ accountAddress, walletId, chainName, thresholdSignatureScheme, derivationPath, shareSetId, shareSetType, otherShareSets, additionalProps, }: {
        accountAddress: string;
        walletId: string;
        chainName: string;
        thresholdSignatureScheme: ThresholdSignatureScheme;
        derivationPath?: string;
        shareSetId?: string;
        shareSetType?: ShareSetType;
        otherShareSets?: ShareSet[];
        additionalProps?: Record<string, unknown>;
    }): void;
    /**
     * Helper function to store client key shares in storage.
     * Uses secureStorage when available (mobile), otherwise falls back to localStorage (browser).
     */
    /**
     * Emits a persistence-info log so storage writes are auditable from traces.
     */
    private logSharePersistence;
    private setClientKeySharesToLocalStorage;
    /**
     * Replaces the client key shares stored for `accountAddress` with `clientKeyShares`.
     * Uses secureStorage when available (mobile), otherwise falls back to localStorage (browser).
     *
     * A WaaS wallet holds exactly one client share per device (see share-distribution
     * factories in types.ts), so writes are always a full replacement — there is no
     * merge mode. Callers that need to clear local shares pass `clientKeyShares: []`.
     */
    setClientKeySharesToStorage({ accountAddress, clientKeyShares, }: {
        accountAddress: string;
        clientKeyShares: ClientKeyShare[];
    }): Promise<void>;
    /**
     * Ensures that client key shares exist for the given account address.
     * Throws an error if no shares are found.
     *
     * Note: This method only checks for existing shares in storage.
     * Auto-recovery logic has been removed in favor of the queue pattern.
     * Callers should handle recovery explicitly if needed.
     */
    private ensureClientShare;
    private backupToDynamicBackend;
    private updateEncryptedSharesCache;
    /**
     * Promotes all pending encrypted-shares cache entries to active.
     * Called once the server confirms that a password-update batch is fully activated
     * (i.e. markKeySharesAsBackedUp returns passwordUpdateStatus !== 'pending').
     * Each wallet wrote its new-password shares to a -pending key during upload;
     * this method atomically moves them to the active key so the next unlock/validate
     * call finds the correct ciphertext.
     */
    private promoteEncryptedSharesCaches;
    private backupToCloudProvider;
    private publishDelegatedShare;
    private createPreservedDelegatedLocation;
    backupSharesWithDistribution({ accountAddress, password, signedSessionId, distribution, preserveDelegatedLocation, passwordUpdateBatchId, googleDriveAccessToken, googleDriveTokenSource, businessAccountId, encryptionVersion, }: {
        accountAddress: string;
        password?: string;
        signedSessionId?: string;
        distribution: ShareDistribution;
        preserveDelegatedLocation?: boolean;
        passwordUpdateBatchId?: string;
        googleDriveAccessToken?: string;
        googleDriveTokenSource?: 'external' | 'stored_oauth';
        businessAccountId?: string;
        /** Version the shares are encrypted with. Defaults to the current default (v3) when omitted. */
        encryptionVersion?: EncryptionVersion;
    }): Promise<{
        message: string;
        walletId: string;
        passwordUpdateStatus?: "pending" | "activated";
        locationsWithKeyShares: {
            location: BackupLocation;
            id: string;
            keygenId: string;
            externalKeyShareId?: string;
        }[];
    }>;
    private ensureLocalSharesAreFresh;
    /**
     * Central backup orchestrator that encrypts and stores wallet key shares.
     *
     * This method serves as the main backup coordinator, handling the distribution of encrypted
     * key shares between Dynamic's backend and Google Drive based on the wallet's threshold scheme.
     * It is used by multiple operations including reshare, refresh, and manual backup requests.
     *
     * **Backup Distribution Strategy:**
     * - **Single share wallets**: All shares stored on Dynamic's backend only
     * - **Multi-share wallets (2+)**: When backing up to Google Drive, N-1 shares on Dynamic's backend, 1 share on Google Drive
     * - **Multi-share wallets (2+)**: When not backing up to Google Drive, all shares on Dynamic's backend
     *
     * **Process Flow:**
     * 1. Encrypts all client key shares with the provided password (or environment ID if no password)
     * 2. For multi-share wallets (2+): conditionally distributes N-1 to backend, 1 to Google Drive
     * 3. For other configurations: stores all shares on Dynamic's backend
     * 4. Updates backup metadata and synchronizes wallet state
     * 5. Persists the updated wallet map to local storage
     *
     * **Delegated Key Shares:**
     * - When delegatedKeyshare is provided, the method will not store the delegated key share but it will mark the delegated share as backed up on Dynamic's backend
     * - and encrypt the delegated key share to publish it to the webhook
     *
     * @param params - The backup operation parameters
     * @param params.accountAddress - The account address of the wallet to backup
     * @param params.clientKeyShares - Optional specific key shares to backup (uses localStorage if not provided)
     * @param params.password - Optional password for encryption (uses environment ID if not provided)
     * @param params.signedSessionId - Optional signed session ID for authentication
     * @param params.backupToGoogleDrive - Whether to backup to Google Drive (defaults to false)
     * @returns Promise with backup metadata including share locations and IDs
     */
    storeEncryptedBackupByWallet({ accountAddress, clientKeyShares, password, signedSessionId, cloudProviders, delegatedKeyshare, passwordUpdateBatchId, googleDriveAccessToken, googleDriveTokenSource, businessAccountId, encryptionVersion, }: {
        accountAddress: string;
        clientKeyShares?: ClientKeyShare[];
        password?: string;
        signedSessionId?: string;
        cloudProviders?: BackupLocation[];
        delegatedKeyshare?: ClientKeyShare;
        passwordUpdateBatchId?: string;
        googleDriveAccessToken?: string;
        googleDriveTokenSource?: 'external' | 'stored_oauth';
        businessAccountId?: string;
        /** Version the shares are encrypted with. Defaults to the current default (v3) when omitted. */
        encryptionVersion?: EncryptionVersion;
    }): Promise<{
        keyShareIds: string[];
        keygenIds: string[];
        message: string;
        walletId: string;
        passwordUpdateStatus?: "pending" | "activated";
        locationsWithKeyShares: {
            location: BackupLocation;
            id: string;
            keygenId: string;
            externalKeyShareId?: string;
        }[];
    }>;
    private getUserWithEnvCheck;
    private logPasswordSharePresence;
    private logPasswordOperationSuccess;
    private logPasswordOperationFailure;
    updatePassword({ accountAddress, existingPassword, newPassword, signedSessionId, passwordUpdateBatchId, }: {
        accountAddress: string;
        existingPassword?: string;
        newPassword?: string;
        signedSessionId: string;
        passwordUpdateBatchId?: string;
    }): Promise<void>;
    setPassword({ accountAddress, newPassword, signedSessionId, passwordUpdateBatchId, }: {
        accountAddress: string;
        newPassword: string;
        signedSessionId: string;
        passwordUpdateBatchId?: string;
    }): Promise<void>;
    decryptKeyShare({ keyShare, password, onRawKey, }: {
        keyShare: string;
        password?: string;
        /** In-process hook receiving the raw derived key bytes (key material, never log) + input fingerprint. */
        onRawKey?: (rawKey: Uint8Array, inputFingerprint: DerivationInputFingerprint) => void;
    }): Promise<ClientKeyShare>;
    /**
     * Validates that the provided password is consistent with existing encrypted wallets.
     * This prevents users from creating multiple wallets with different passwords.
     *
     * @param password - User-provided password (optional)
     * @param signedSessionId - Signed session ID for API calls
     * @throws Error with ERROR_PASSWORD_MISMATCH if password doesn't match existing wallets
     */
    /**
     * Shared helper: fetches encrypted shares (from storage or API) and validates
     * the provided password by attempting to decrypt the first credential.
     * Throws ERROR_PASSWORD_MISMATCH if the password is incorrect.
     */
    private validatePasswordAgainstEncryptedShares;
    private isPasswordRequired;
    private assertPasswordRequired;
    protected validatePasswordConsistencyForNewWallet({ password, signedSessionId, }: {
        password?: string;
        signedSessionId: string;
    }): Promise<void>;
    /**
     * Validates that the provided password matches the existing encryption for
     * a password-encrypted wallet. Must be called before refresh/reshare ceremonies.
     * Throws if the wallet is password-encrypted but no password (or wrong password) is provided.
     */
    protected validatePasswordForExistingWallet({ accountAddress, password, signedSessionId, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
    }): Promise<void>;
    /**
     * Helper function to get Google OAuth Account ID or throw an error if not found.
     * @param accountAddress - The account address for logging purposes
     * @returns The Google OAuth Account ID
     * @throws Error if no Google OAuth account ID is found
     */
    private getGoogleOauthAccountIdOrThrow;
    private fetchGoogleDriveAccessToken;
    /**
     * Helper function to determine keyshare recovery strategy for dynamic shares.
     * For REFRESH operations, retrieves enough shares to meet the client threshold.
     * For all other operations, retrieves just 1 share.
     *
     * @param clientKeyShareBackupInfo - Information about backed up key shares
     * @param thresholdSignatureScheme - The signature scheme being used (2-of-2, 2-of-3, etc)
     * @param walletOperation - The operation being performed (REFRESH, SIGN_MESSAGE, etc)
     * @param shareCount - The number of shares to recover if specified for reshare operations
     * @returns @shares: Object mapping backup locations to arrays of share IDs to recover
     * @returns @requiredShareCount: The number of shares required to recover
     */
    recoverStrategy({ clientKeyShareBackupInfo, thresholdSignatureScheme, walletOperation, shareCount, }: {
        clientKeyShareBackupInfo: KeyShareBackupInfo;
        thresholdSignatureScheme: ThresholdSignatureScheme;
        walletOperation: WalletOperation;
        shareCount?: number;
    }): {
        shares: Partial<Record<BackupLocation, string[]>>;
        requiredShareCount: number;
    };
    recoverEncryptedBackupByWallet({ accountAddress, password, walletOperation, signedSessionId, shareCount, storeRecoveredShares, mfaToken, }: {
        accountAddress: string;
        password?: string;
        walletOperation: WalletOperation;
        signedSessionId: string;
        shareCount?: number;
        storeRecoveredShares?: boolean;
        mfaToken?: string;
    }): Promise<ClientKeyShare[]>;
    /**
     * Fetches encrypted backup shares from the server, transparently refreshing
     * the signed session on a single-use-nonce rejection. Recovery is otherwise
     * non-retrying, so other errors surface immediately. When no reverse channel
     * is configured the provided session is used unchanged.
     */
    private recoverEncryptedSharesWithNonceRetry;
    private internalRecoverEncryptedBackupByWallet;
    restoreWallets(): Promise<void>;
    /**
     * Internal helper method that handles the complete flow for ensuring wallet key shares are backed up to a cloud provider.
     * - For 2-of-2 wallets: Automatically reshares to 2-of-3 threshold, then distributes shares (1 to backend, 1 to cloud)
     * - For 2-of-3 wallets: Call storeEncryptedBackupByWallet to backup for backend and cloud
     */
    private backupKeySharesToCloudProvider;
    /**
     * This method handles the complete flow for ensuring wallet key shares are backed up to Google Drive:
     * - For 2-of-2 wallets: Automatically reshares to 2-of-3 threshold, then distributes shares (1 to backend, 1 to Google Drive)
     * - For 2-of-3 wallets: Call storeEncryptedBackupByWallet to backup for backend and Google Drive
     *
     * @param params - The backup parameters
     * @param params.accountAddress - The wallet account address to backup
     * @param params.password - Optional password for encryption (uses environment ID if not provided)
     * @param params.signedSessionId - Optional signed session ID for authentication
     * @param params.googleDriveAccessToken - Optional Google OAuth access token. When provided, the SDK uses it directly
     *   instead of looking up the user's linked Google account and exchanging it for a token via the Dynamic backend.
     */
    backupKeySharesToGoogleDrive({ accountAddress, password, signedSessionId, googleDriveAccessToken, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
        googleDriveAccessToken?: string;
    }): Promise<void>;
    /**
     * Resolve the Google Drive OAuth access token (lazy-fetch via
     * `fetchGoogleDriveAccessToken` if the caller didn't pass one explicitly),
     * run scope + quota probes against it, and either return the resolved
     * token or throw a classified `createGoogleDriveError` so the reshare
     * ceremony is short-circuited. The blocking log mirrors the upload-path
     * shape in `backup/utils.ts` so the same Datadog dashboard panels and
     * monitor pick up preflight events.
     */
    private preflightGoogleDriveBackup;
    /**
     * This method handles the complete flow for ensuring wallet key shares are backed up to iCloud:
     * - For 2-of-2 wallets: Automatically reshares to 2-of-3 threshold, then distributes shares (1 to backend, 1 to iCloud)
     * - For 2-of-3 wallets: Call storeEncryptedBackupByWallet to backup for backend and iCloud
     *
     * @param params - The backup parameters
     * @param params.accountAddress - The wallet account address to backup
     * @param params.password - Optional password for encryption (uses environment ID if not provided)
     * @param params.signedSessionId - Optional signed session ID for authentication
     */
    backupKeySharesToICloud({ accountAddress, password, signedSessionId, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
    }): Promise<void>;
    /**
     * Generic router method that uploads encrypted key shares to the specified cloud provider
     * @param provider - The cloud backup provider (GOOGLE_DRIVE, ICLOUD, etc.)
     * @param accountAddress - Wallet account address
     * @param encryptedKeyShares - Already encrypted key shares to upload
     * @param googleDriveAccessToken - Optional Google OAuth access token used when provider is GOOGLE_DRIVE
     * @returns Promise<void>
     */
    private uploadToCloudProvider;
    /**
     * This method handles only the Google Drive upload mechanics without any reshare logic.
     * It encrypts the provided key shares, uploads them to Google Drive, and updates the
     * backup metadata. This method is intended for internal use by storeEncryptedBackupByWallet
     * and should not be called directly from external code.
     *
     * @param params - The upload parameters
     * @param params.accountAddress - The wallet account address
     * @param params.password - Optional password for encryption (uses environment ID if not provided)
     * @param params.encryptedKeyShares - The specific key shares to upload to Google Drive
     * @param params.googleDriveAccessToken - Google OAuth access token. Required; resolved upstream by `backupKeySharesToGoogleDrive` so the preflight can run on it.
     * @returns Promise<string[]> - Array of Google Drive key share IDs that were uploaded
     */
    private uploadKeySharesToGoogleDrive;
    /**
     * Private method that handles only the iCloud upload mechanics without any reshare logic.
     * It takes already encrypted key shares and uploads them to iCloud.
     * @param accountAddress - The wallet account address
     * @param encryptedKeyShares - Already encrypted key shares to upload
     * @returns Promise<void>
     */
    private uploadKeySharesToICloud;
    exportClientKeysharesFromGoogleDrive({ accountAddress, password, signedSessionId, googleDriveAccessToken, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
        googleDriveAccessToken?: string;
    }): Promise<void>;
    exportClientKeyshares({ accountAddress, password, signedSessionId, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
    }): Promise<void>;
    getClientKeyShares({ accountAddress, password, signedSessionId, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
    }): Promise<ClientKeyShare[]>;
    /**
     * Helper function to check if the required wallet fields are present and valid
     * @param accountAddress - The account address of the wallet to check
     * @param walletOperation - The wallet operation that determines required fields
     * @returns boolean indicating if wallet needs to be re-fetched and restored from server
     */
    private checkWalletFields;
    /**
     * verifyPassword attempts to recover and decrypt a single client key share using the provided password.
     * If successful, the key share is encrypted with the new password. This method solely performs the recovery
     * and decryption without storing the restored key shares. If unsuccessful, it throws an error.
     */
    verifyPassword({ accountAddress, password, signedSessionId, }: {
        accountAddress: string;
        password?: string;
        signedSessionId: string;
    }): Promise<void>;
    isPasswordEncrypted({ accountAddress }: {
        accountAddress: string;
    }): Promise<boolean>;
    /**
     * check if the operation requires a password
     */
    requiresPasswordForOperation({ accountAddress, walletOperation, }: {
        accountAddress: string;
        walletOperation?: WalletOperation;
    }): Promise<boolean>;
    /**
     * check if the operation requires restoring backup shares
     */
    requiresRestoreBackupSharesForOperation({ accountAddress, walletOperation, }: {
        accountAddress: string;
        walletOperation?: WalletOperation;
    }): Promise<boolean>;
    private fetchWalletBackupInfoFromServer;
    getWalletClientKeyShareBackupInfo({ accountAddress }: {
        accountAddress: string;
    }): Promise<KeyShareBackupInfo>;
    private fetchFreshWalletBackupInfo;
    getWallet({ accountAddress, walletOperation, shareCount, password, signedSessionId, }: {
        accountAddress: string;
        walletOperation?: WalletOperation;
        shareCount?: number;
        password?: string;
        signedSessionId: string;
    }): Promise<WalletProperties>;
    /**
     * Gets the recovery state of a wallet, optionally recovering shares if not available.
     * This method is useful for detecting if a wallet is password-encrypted
     * and needs unlocking before use.
     *
     * If shares are not available locally and recovery parameters are provided,
     * this method will call getWallet with RECOVER operation to fetch shares.
     * The underlying recoverEncryptedBackupByWallet handles deduplication via
     * inFlightRecovery, so concurrent calls won't start multiple recoveries.
     *
     * @param accountAddress - The account address of the wallet
     * @param signedSessionId - Optional signed session ID for triggering recovery if shares not available
     * @param password - Optional password for decrypting recovered shares
     * @returns WalletRecoveryState indicating the wallet's lock state and share availability
     * @throws Error if recovery fails or no shares available after recovery
     */
    getWalletRecoveryState({ accountAddress, signedSessionId, password, }: {
        accountAddress: string;
        signedSessionId?: string;
        password?: string;
    }): Promise<WalletRecoveryState>;
    /**
     * Fetches the encrypted-shares blob from the server and caches it in this.storage.
     * Returns the serialized blob, or null if the wallet is unknown or the API returns
     * no data. Does not decrypt — callers (e.g. unlockWallet, getWallet eager-load)
     * own the decrypt step.
     */
    private fetchAndCacheEncryptedShares;
    /**
     * Unlocks a password-encrypted wallet by decrypting cached encrypted shares.
     * This method should be called after getWalletRecoveryState returns LOCKED state.
     *
     * @param accountAddress - The account address of the wallet
     * @param password - The password to decrypt the shares
     * @param signedSessionId - The signed session ID for authentication
     * @returns The unlocked wallet properties
     */
    unlockWallet({ accountAddress, password, signedSessionId, mfaToken, }: {
        accountAddress: string;
        password: string;
        signedSessionId: string;
        mfaToken?: string;
    }): Promise<WalletProperties>;
    /**
     * Decrypts cached encrypted key shares for a wallet and stores them locally.
     */
    private decryptAndStoreWalletShares;
    getAllWallets(): Promise<GetWalletResponse[]>;
    getWallets(): Promise<any>;
    /**
     * One-off re-backup for users whose Argon2id (v3) Dynamic backup can no longer be
     * decrypted (DYNT-1112). The v3 derived key is only deterministic within a specific
     * environment/setup; when that environment or its parameters change the derived key
     * no longer matches and the blob fails to decrypt — even though the local client
     * shares are still readable. While those local shares are still present we re-upload
     * them, re-encrypted with v2 (PBKDF2), whose derivation is stable across
     * environments, overwriting the no-longer-decryptable copy.
     *
     * Targets come from the `argon2id-rebackup-targets` LaunchDarkly flag. Idempotency
     * is keyed on the `externalKeyShareId`: re-backing up produces a new id, so once
     * the known-bad id is gone the wallet is skipped. The shares are read from local
     * storage only — this never refetches shares from the server. The backup path runs
     * its own encryption round-trip self-test before uploading, so a blob that can't be
     * decrypted is never pushed.
     */
    private maybeRunArgon2idRebackup;
    /**
     * sync auth token with api client
     * @param authToken - auth token to sync
     */
    syncAuthToken(authToken: string): void;
    createRooms({ roomType, thresholdSignatureScheme, roomCount, }: {
        roomType: RoomTypeEnum;
        thresholdSignatureScheme: ThresholdSignatureScheme;
        roomCount?: number;
    }): Promise<void>;
    restoreRooms(): Promise<Record<number, Room[]>>;
    getRooms(roomType?: RoomTypeEnum, thresholdSignatureScheme?: ThresholdSignatureScheme): Promise<Room[] | Record<number, Room[]>>;
    setRooms(numberOfParties: number, rooms: Room[]): Promise<void>;
    /**
     * Chain localStorage writes sequentially so each write serializes the latest
     * in-memory state at execution time, preventing earlier stale snapshots from
     * overwriting fresher data when concurrent setRooms calls race.
     */
    private persistRooms;
    getNumberOfParties(roomType: RoomTypeEnum, thresholdSignatureScheme: ThresholdSignatureScheme): number;
    getRoom(roomType: RoomTypeEnum, thresholdSignatureScheme: ThresholdSignatureScheme): Promise<Room | undefined>;
    getTraceContext(traceContext?: TraceContext): TraceContext & {
        now: number;
        time: number;
    };
}
export {};
//# sourceMappingURL=client.d.ts.map