UNPKG

@turnkey/core

Version:

A core JavaScript web and React Native package for interfacing with Turnkey's infrastructure.

675 lines 91.5 kB
import { TurnkeySDKClientBase } from "../__generated__/sdk-client-base"; import { type TDeleteSubOrganizationResponse, type Session, type TStampLoginResponse, type v1SignRawPayloadResult, type v1User, type ProxyTGetWalletKitConfigResponse, type v1PrivateKey, type WalletAuthResult, type BaseAuthResult, type PasskeyAuthResult, type v1BootProof, type TGetSendTransactionStatusResponse, AuthAction } from "@turnkey/sdk-types"; import { Chain, type ExportBundle, type TurnkeySDKClientConfig, type WalletAccount, type Wallet, type WalletManagerBase, type WalletProvider, type CreatePasskeyParams, type CreatePasskeyResult, type LogoutParams, type LoginWithPasskeyParams, type SignUpWithPasskeyParams, type SwitchWalletAccountChainParams, type LoginWithWalletParams, type SignUpWithWalletParams, type LoginOrSignupWithWalletParams, type InitOtpParams, type VerifyOtpParams, type VerifyOtpResult, type LoginWithOtpParams, type SignUpWithOtpParams, type CompleteOtpParams, type CompleteOauthParams, type LoginWithOauthParams, type SignUpWithOauthParams, type FetchWalletsParams, type FetchWalletAccountsParams, type FetchPrivateKeysParams, type SignMessageParams, type SignTransactionParams, type SignAndSendTransactionParams, type EthSendTransactionParams, type SolSendTransactionParams, type FetchUserParams, type FetchOrCreateP256ApiKeyUserParams, type FetchOrCreatePoliciesParams, type FetchOrCreatePoliciesResult, type UpdateUserEmailParams, type RemoveUserEmailParams, type UpdateUserPhoneNumberParams, type RemoveUserPhoneNumberParams, type UpdateUserNameParams, type AddOauthProviderParams, type RemoveOauthProvidersParams, type AddPasskeyParams, type RemovePasskeyParams, type CreateWalletParams, type CreateWalletAccountsParams, type ExportWalletParams, type ExportPrivateKeyParams, type ExportWalletAccountParams, type ImportWalletParams, type ImportPrivateKeyParams, type DeleteSubOrganizationParams, type StoreSessionParams, type ClearSessionParams, type RefreshSessionParams, type GetSessionParams, type SetActiveSessionParams, type CreateApiKeyPairParams, type FetchBootProofForAppProofParams, type CreateHttpClientParams, type BuildWalletLoginRequestResult, type BuildWalletLoginRequestParams, type VerifyAppProofsParams, type PollTransactionStatusParams } from "../__types__"; import { CrossPlatformApiKeyStamper } from "../__stampers__/api/base"; import { CrossPlatformPasskeyStamper } from "../__stampers__/passkey/base"; /** * @internal * Gathers all public methods exposed in our core client and turns it into a type that * can be used to extend clients created for other packages built off core * * Should be used to keep any packages that extend this core package in sync with each * other, meaning any new additions to core should also be reflected in those packages */ type PublicMethods<T> = { [K in keyof T as T[K] extends Function ? K : never]: T[K]; }; export type TurnkeyClientMethods = Omit<PublicMethods<TurnkeyClient>, "init" | "config" | "httpClient" | "constructor">; export declare class TurnkeyClient { config: TurnkeySDKClientConfig; httpClient: TurnkeySDKClientBase; private apiKeyStamper?; private passkeyStamper?; private walletManager?; private storageManager; constructor(config: TurnkeySDKClientConfig, apiKeyStamper?: CrossPlatformApiKeyStamper, passkeyStamper?: CrossPlatformPasskeyStamper, walletManager?: WalletManagerBase); init(): Promise<void>; /** * Creates a new TurnkeySDKClientBase instance with the provided configuration. * This method is used internally to create the HTTP client for making API requests, * but can also be used to create an additional client with different configurations if needed. * By default, it uses the configuration provided during the TurnkeyClient initialization. * * @param params - Optional configuration parameters to override the default client configuration. * @param params.apiBaseUrl - The base URL of the Turnkey API (defaults to `https://api.turnkey.com` if not provided). * @param params.organizationId - The organization ID to associate requests with. * @param params.authProxyUrl - The base URL of the Auth Proxy (defaults to `https://authproxy.turnkey.com` if not provided). * @param params.authProxyConfigId - The configuration ID to use when making Auth Proxy requests. * @param params.defaultStamperType - The default stamper type to use for signing requests * (overrides automatic detection of ApiKey, Passkey, or Wallet stampers). * * @returns A new instance of {@link TurnkeySDKClientBase} configured with the provided parameters. */ createHttpClient: (params?: CreateHttpClientParams) => TurnkeySDKClientBase; /** * Creates a new passkey authenticator for the user. * * - This function generates a new passkey attestation and challenge, suitable for registration with the user's device. * - Handles both web and React Native environments, automatically selecting the appropriate passkey creation flow. * - The resulting attestation and challenge can be used to register the passkey with Turnkey. * * @param params.name - display name for the passkey (defaults to a generated name based on the current timestamp). * @param params.challenge - challenge string to use for passkey registration. If not provided, a new challenge will be generated. * @returns A promise that resolves to {@link CreatePasskeyResult} * @throws {TurnkeyError} If there is an error during passkey creation, or if the platform is unsupported. */ createPasskey: (params: CreatePasskeyParams) => Promise<CreatePasskeyResult>; /** * Logs out the current client session. * * - This function clears the specified session and removes any associated key pairs from storage. * - If a sessionKey is provided, it logs out from that session; otherwise, it logs out from the active session. * - Cleans up any api keys associated with the session. * * @param params.sessionKey - session key to specify which session to log out from (defaults to the active session). * @returns A promise that resolves when the logout process is complete. * @throws {TurnkeyError} If there is no active session or if there is an error during the logout process. */ logout: (params?: LogoutParams) => Promise<void>; /** * Logs in a user using a passkey, optionally specifying the public key, session key, and session expiration. * * - This function initiates the login process with a passkey and handles session creation and storage. * - If a public key is not provided, a new key pair will be generated for authentication. * - If a session key is not provided, the default session key will be used. * - The session expiration can be customized via the expirationSeconds parameter. * - Handles cleanup of unused key pairs if login fails. * * @param params.publicKey - public key to use for authentication. If not provided, a new key pair will be generated. * @param params.sessionKey - session key to use for session creation (defaults to the default session key). * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default). * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID). * @returns A promise that resolves to a {@link PasskeyAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * - `credentialId`: an empty string. * @throws {TurnkeyError} If there is an error during the passkey login process or if the user cancels the passkey prompt. */ loginWithPasskey: (params?: LoginWithPasskeyParams) => Promise<PasskeyAuthResult>; /** * Signs up a user using a passkey, creating a new sub-organization and session. * * - This function creates a new passkey authenticator and uses it to register a new sub-organization for the user. * - Handles both passkey creation and sub-organization creation in a single flow. * - Optionally accepts additional sub-organization parameters, a custom session key, a custom passkey display name, and a custom session expiration. * - Automatically generates a new API key pair for authentication and session management. * - Stores the resulting session token and manages cleanup of unused key pairs. * * @param params.passkeyDisplayName - display name for the passkey (defaults to a generated name based on the current timestamp). * @param params.challenge - challenge string to use for passkey registration. If not provided, a new challenge will be generated. * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default). * @param params.createSubOrgParams - parameters for creating a sub-organization (e.g., authenticators, user metadata). * @param params.sessionKey - session key to use for storing the session (defaults to the default session key). * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID). * @returns A promise that resolves to a {@link PasskeyAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * - `credentialId`: the credential ID associated with the passkey created. * @throws {TurnkeyError} If there is an error during passkey creation, sub-organization creation, or session storage. */ signUpWithPasskey: (params?: SignUpWithPasskeyParams) => Promise<PasskeyAuthResult>; /** * Retrieves wallet providers from the initialized wallet manager. * * - Optionally filters providers by the specified blockchain chain. * - Throws an error if the wallet manager is not initialized. * * @param chain - optional blockchain chain to filter the returned providers. * @returns A promise that resolves to an array of wallet providers. * @throws {TurnkeyError} If the wallet manager is uninitialized or provider retrieval fails. */ fetchWalletProviders: (chain?: Chain) => Promise<WalletProvider[]>; /** * Connects the specified wallet account. * * - Requires the wallet manager and its connector to be initialized. * * @param walletProvider - wallet provider to connect. * @returns A promise that resolves with the connected wallet's address. * @throws {TurnkeyError} If the wallet manager is uninitialized or the connection fails. */ connectWalletAccount: (walletProvider: WalletProvider) => Promise<string>; /** * Disconnects the specified wallet account. * * - Requires the wallet manager and its connector to be initialized. * * @param walletProvider - wallet provider to disconnect. * @returns A promise that resolves once the wallet account is disconnected. * @throws {TurnkeyError} If the wallet manager is uninitialized or the disconnection fails. */ disconnectWalletAccount: (walletProvider: WalletProvider) => Promise<void>; /** * Switches the wallet provider associated with a given wallet account * to a different chain. * * - Requires the wallet manager and its connector to be initialized * - Only works for connected wallet accounts * - Looks up the provider for the given account address * - Does nothing if the provider is already on the desired chain. * * @param params.walletAccount - The wallet account whose provider should be switched. * @param params.chainOrId - The target chain, specified as a chain ID string or a SwitchableChain object. * @param params.walletProviders - Optional list of wallet providers to search; falls back to `fetchWalletProviders()` if omitted. * @returns A promise that resolves once the chain switch is complete. * * @throws {TurnkeyError} If the wallet manager is uninitialized, the provider is not connected, or the switch fails. */ switchWalletAccountChain: (params: SwitchWalletAccountChainParams) => Promise<void>; /** * Builds and signs a wallet login request without submitting it to Turnkey. * * - This function prepares a signed request for wallet authentication, which can later be used * to log in or sign up a user with Turnkey. * - It initializes the wallet stamper, ensures a valid session public key (generating one if needed), * and signs the login intent with the connected wallet. * - For Ethereum wallets, derives the public key from the stamped request header. * - For Solana wallets, retrieves the public key directly from the connected wallet. * - The signed request is not sent to Turnkey immediately; it is meant to be used in a subsequent flow * (e.g., `loginOrSignupWithWallet`) where sub-organization existence is verified or created first. * * @param params.walletProvider - the wallet provider used for authentication and signing. * @param params.publicKey - optional pre-generated session public key (auto-generated if not provided). * @param params.expirationSeconds - optional session expiration time in seconds (defaults to the configured default). * @returns A promise resolving to an object containing: * - `signedRequest`: the signed wallet login request. * - `publicKey`: the public key associated with the signed request. * @throws {TurnkeyError} If the wallet stamper is not initialized, the signing process fails, * or the public key cannot be derived or generated. */ buildWalletLoginRequest: (params: BuildWalletLoginRequestParams) => Promise<BuildWalletLoginRequestResult>; /** * Logs in a user using the specified wallet provider. * * - This function logs in a user by authenticating with the provided wallet provider via a wallet-based signature. * - If a public key is not provided, a new one will be generated for authentication. * - Optionally accepts a custom session key and session expiration time. * - Stores the resulting session token under the specified session key, or the default session key if not provided. * - Throws an error if a public key cannot be found or generated, or if the login process fails. * * @param params.walletProvider - wallet provider to use for authentication. * @param params.publicKey - optional public key to associate with the session (generated if not provided). * @param params.sessionKey - optional key to store the session under (defaults to the default session key). * @param params.expirationSeconds - optional session expiration time in seconds (defaults to the configured default). * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID). * @returns A promise that resolves to a {@link WalletAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * - `address`: the authenticated wallet address. * @throws {TurnkeyError} If the wallet stamper is uninitialized, a public key cannot be found or generated, or login fails. */ loginWithWallet: (params: LoginWithWalletParams) => Promise<WalletAuthResult>; /** * Signs up a user using a wallet, creating a new sub-organization and session. * * - This function creates a new wallet authenticator and uses it to register a new sub-organization for the user. * - Handles both wallet authentication and sub-organization creation in a single flow. * - Optionally accepts additional sub-organization parameters, a custom session key, and a custom session expiration. * - Automatically generates additional API key pairs for authentication and session management. * - Stores the resulting session token under the specified session key, or the default session key if not provided, and manages cleanup of unused key pairs. * * @param params.walletProvider - wallet provider to use for authentication. * @param params.createSubOrgParams - parameters for creating a sub-organization (e.g., authenticators, user metadata). * @param params.sessionKey - session key to use for storing the session (defaults to the default session key). * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default). * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID). * @returns A promise that resolves to a {@link WalletAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * - `address`: the authenticated wallet address. * @throws {TurnkeyError} If there is an error during wallet authentication, sub-organization creation, session storage, or cleanup. */ signUpWithWallet: (params: SignUpWithWalletParams) => Promise<WalletAuthResult>; /** * Logs in an existing user or signs up a new user using a wallet, creating a new sub-organization if needed. * * - This function attempts to log in the user by stamping a login request with the provided wallet. * - If the wallet’s public key is not associated with an existing sub-organization, a new one is created. * - Handles both wallet authentication and sub-organization creation in a single flow. * - For Ethereum wallets, derives the public key from the signed request header; for Solana wallets, retrieves it directly from the wallet. * - Optionally accepts additional sub-organization parameters, a custom session key, and a custom session expiration. * - Stores the resulting session token under the specified session key, or the default session key if not provided. * * @param params.walletProvider - wallet provider to use for authentication. * @param params.publicKey - optional public key to associate with the session (generated if not provided). * @param params.createSubOrgParams - optional parameters for creating a sub-organization (e.g., authenticators, user metadata). * @param params.sessionKey - session key to use for storing the session (defaults to the default session key). * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default). * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID). * @returns A promise that resolves to an object containing: * - `sessionToken`: the signed JWT session token. * - `address`: the authenticated wallet address. * - `action`: whether the flow resulted in a login or signup ({@link AuthAction}). * @throws {TurnkeyError} If there is an error during wallet authentication, sub-organization creation, or session storage. */ loginOrSignupWithWallet: (params: LoginOrSignupWithWalletParams) => Promise<WalletAuthResult & { action: AuthAction; }>; /** * Initializes the OTP process by sending an OTP code to the provided contact. * * - This function initiates the OTP flow by sending a one-time password (OTP) code to the user's contact information (email address or phone number) via the auth proxy. * - Supports both email and SMS OTP types. * - Returns an OTP ID that is required for subsequent OTP verification. * * @param params.otpType - type of OTP to initialize (OtpType.Email or OtpType.Sms). * @param params.contact - contact information for the user (e.g., email address or phone number). * @param params.organizationId - optional organization ID to target (defaults to the session's organization ID or the parent organization ID). * @returns A promise that resolves to the OTP ID required for verification. * @throws {TurnkeyError} If there is an error during the OTP initialization process or if the maximum number of OTPs has been reached. */ initOtp: (params: InitOtpParams) => Promise<string>; /** * Verifies the OTP code sent to the user. * * - This function verifies the OTP code entered by the user against the OTP sent to their contact information (email or phone) using the auth proxy. * - If verification is successful, it returns the sub-organization ID associated with the contact (if it exists) and a verification token. * - The verification token can be used for subsequent login or sign-up flows. * - Handles both email and SMS OTP types. * * @param params.otpId - ID of the OTP to verify (returned from `initOtp`). * @param params.otpCode - OTP code entered by the user. * @param params.contact - contact information for the user (e.g., email address or phone number). * @param params.otpType - type of OTP being verified (OtpType.Email or OtpType.Sms). * @param params.publicKey - public key the verification token is bound to for ownership verification (client signature verification during login/signup). This public key is optional; if not provided, a new key pair will be generated. * @returns A promise that resolves to an object containing: * - subOrganizationId: sub-organization ID if the contact is already associated with a sub-organization, or an empty string if not. * - verificationToken: verification token to be used for login or sign-up. * @throws {TurnkeyError} If there is an error during the OTP verification process, such as an invalid code or network failure. */ verifyOtp: (params: VerifyOtpParams) => Promise<VerifyOtpResult>; /** * Logs in a user using an OTP verification token. * * - This function logs in a user using the verification token received after OTP verification (from email or SMS). * - If a public key is not provided, a new API key pair will be generated for authentication. * - Optionally invalidates any existing sessions for the user if `invalidateExisting` is set to true. * - Stores the resulting session token under the specified session key, or the default session key if not provided. * - Handles cleanup of unused key pairs if login fails. * * @param params.verificationToken - verification token received after OTP verification. * @param params.publicKey - public key to use for authentication. If not provided, a new key pair will be generated. * @param params.organizationId - optional organization ID to target (defaults to the verified subOrg ID linked to the verification token contact). * @param params.invalidateExisting - flag to invalidate existing session for the user. * @param params.sessionKey - session key to use for session creation (defaults to the default session key). * @returns A promise that resolves to a {@link BaseAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * @throws {TurnkeyError} If there is an error during the OTP login process or if key pair cleanup fails. */ loginWithOtp: (params: LoginWithOtpParams) => Promise<BaseAuthResult>; /** * Signs up a user using an OTP verification token. * * - This function signs up a user using the verification token received after OTP verification (from email or SMS). * - Creates a new sub-organization for the user with the provided parameters and associates the contact (email or phone) with the sub-organization. * - Automatically generates a new API key pair for authentication and session management. * - Stores the resulting session token under the specified session key, or the default session key if not provided. * - Handles both email and SMS OTP types, and supports additional sub-organization creation parameters. * * @param params.verificationToken - verification token received after OTP verification. * @param params.contact - contact information for the user (e.g., email address or phone number). * @param params.otpType - type of OTP being used (OtpType.Email or OtpType.Sms). * @param params.createSubOrgParams - parameters for creating a sub-organization (e.g., authenticators, user metadata). * @param params.invalidateExisting - flag to invalidate existing session for the user. * @param params.sessionKey - session key to use for session creation (defaults to the default session key). * @returns A promise that resolves to a {@link BaseAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * @throws {TurnkeyError} If there is an error during the OTP sign-up process or session storage. */ signUpWithOtp: (params: SignUpWithOtpParams) => Promise<BaseAuthResult>; /** * Completes the OTP authentication flow by verifying the OTP code and then either signing up or logging in the user. * * - This function first verifies the OTP code for the provided contact and OTP type. * - If the contact is not associated with an existing sub-organization, it will automatically create a new sub-organization and complete the sign-up flow. * - If the contact is already associated with a sub-organization, it will complete the login flow. * - Supports passing a custom public key for authentication, invalidating existing session, specifying a session key, and providing additional sub-organization creation parameters. * - Handles both email and SMS OTP types. * * @param params.otpId - ID of the OTP to complete (returned from `initOtp`). * @param params.otpCode - OTP code entered by the user. * @param params.contact - contact information for the user (e.g., email address or phone number). * @param params.otpType - type of OTP being completed (OtpType.Email or OtpType.Sms). * @param params.publicKey - public key to use for authentication. If not provided, a new key pair may be generated. * @param params.invalidateExisting - flag to invalidate existing sessions for the user. * @param params.sessionKey - session key to use for session creation (defaults to the default session key). * @param params.createSubOrgParams - parameters for sub-organization creation (e.g., authenticators, user metadata). * @returns A promise that resolves to an object containing: * - `sessionToken`: the signed JWT session token. * - `verificationToken`: the OTP verification token. * - `action`: whether the flow resulted in a login or signup ({@link AuthAction}). * @throws {TurnkeyError} If there is an error during OTP verification, sign-up, or login. */ completeOtp: (params: CompleteOtpParams) => Promise<BaseAuthResult & { verificationToken: string; action: AuthAction; }>; /** * Completes the OAuth authentication flow by either signing up or logging in the user, depending on whether a sub-organization already exists for the provided OIDC token. * * - This function first checks if there is an existing sub-organization associated with the OIDC token. * - If a sub-organization exists, it proceeds with the OAuth login flow. * - If no sub-organization exists, it creates a new sub-organization and completes the sign-up flow. * - Optionally accepts a custom OAuth provider name, session key, and additional sub-organization creation parameters. * - Handles session storage and management, and supports invalidating existing sessions if specified. * * @param params.oidcToken - OIDC token received after successful authentication with the OAuth provider. * @param params.publicKey - public key to use for authentication. Must be generated prior to calling this function, this is because the OIDC nonce has to be set to `sha256(publicKey)`. * @param params.providerName - name of the OAuth provider (defaults to a generated name with a timestamp). * @param params.createSubOrgParams - parameters for sub-organization creation (e.g., authenticators, user metadata). * @param params.invalidateExisting - flag to invalidate existing sessions for the user. * @param params.sessionKey - session key to use for session creation (defaults to the default session key). * * @returns A promise that resolves to an object containing: * - `sessionToken`: the signed JWT session token. * - `action`: whether the flow resulted in a login or signup ({@link AuthAction}). * @throws {TurnkeyError} If there is an error during the OAuth completion process, such as account lookup, sign-up, or login. */ completeOauth: (params: CompleteOauthParams) => Promise<BaseAuthResult & { action: AuthAction; }>; /** * Logs in a user using OAuth authentication. * * - This function logs in a user using the provided OIDC token and public key. * - Optionally invalidates any existing sessions for the user if `invalidateExisting` is set to true. * - Stores the resulting session token under the specified session key, or the default session key if not provided. * - Handles cleanup of unused key pairs if login fails. * * @param params.oidcToken - OIDC token received after successful authentication with the OAuth provider. * @param params.publicKey - The public key bound to the login session. This key is required because it is directly * tied to the nonce used during OIDC token generation and must match the value * encoded in the token. * @param params.organizationId - ID of the organization to target when creating the session. * @param params.invalidateExisting - flag to invalidate existing sessions for the user. * @param params.sessionKey - session key to use for session creation (defaults to the default session key). * @returns A promise that resolves to a {@link BaseAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * @throws {TurnkeyError} If there is an error during the OAuth login process or if key pair cleanup fails. */ loginWithOauth: (params: LoginWithOauthParams) => Promise<BaseAuthResult>; /** * Signs up a user using OAuth authentication. * * - This function creates a new sub-organization for the user using the provided OIDC token, public key, and provider name. * - Handles the full OAuth sign-up flow, including sub-organization creation and session management. * - Optionally accepts additional sub-organization creation parameters and a custom session key. * - After successful sign-up, automatically logs in the user and returns a signed JWT session token. * * @param params.oidcToken - OIDC token received after successful authentication with the OAuth provider. * @param params.publicKey - public key to associate with the new sub-organization. * @param params.providerName - name of the OAuth provider (e.g., "Google", "Apple"). * @param params.createSubOrgParams - parameters for sub-organization creation (e.g., authenticators, user metadata). * @param params.sessionKey - session key to use for session creation (defaults to the default session key). * @returns A promise that resolves to a {@link BaseAuthResult}, which includes: * - `sessionToken`: the signed JWT session token. * @throws {TurnkeyError} If there is an error during the OAuth sign-up or login process. */ signUpWithOauth: (params: SignUpWithOauthParams) => Promise<BaseAuthResult>; /** * Fetches all wallets for the current user, including both embedded and connected wallets. * * - Retrieves all wallets associated with the organizationId from the current active session. * - For each embedded wallet, automatically fetches and attaches all associated wallet accounts. * - For connected wallets (e.g., browser extensions or external providers), groups providers by wallet name and attaches all connected accounts. * - Returns both embedded and connected wallets in a single array, each with their respective accounts populated. * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * * @param params.walletProviders - array of wallet providers to use for fetching wallets. * @param params.organizationId - organization ID to target (defaults to the session's organization ID). * @param params.userId - user ID to target (defaults to the session's user ID). * @param params.connectedOnly - if true, fetches only connected wallets; if false or undefined, fetches both embedded and connected wallets. * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * @returns A promise that resolves to an array of `Wallet` objects. * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallets. */ fetchWallets: (params?: FetchWalletsParams) => Promise<Wallet[]>; /** * Fetches all accounts for a specific wallet, including both embedded and connected wallet accounts. * * - For embedded wallets, retrieves accounts from the Turnkey API, supporting pagination (defaults to the first page with a limit of 100 accounts). * - For connected wallets (e.g., browser extensions or external providers), constructs account objects for each connected address from the provided or discovered wallet providers. * - Automatically determines the account type and populates relevant fields such as address, curve, and signing capability. * - Optionally allows filtering by a specific set of wallet providers and supports custom pagination options. * - Supports stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * * @param params.wallet - wallet for which to fetch accounts. * @param params.walletProviders - list of wallet providers to filter by (used for connected wallets). * @param params.paginationOptions - pagination options for embedded wallets. * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * @param params.organizationId - organization ID to target (defaults to the session's organization ID). * @param params.userId - user ID to target (defaults to the session's user ID). * @param params.authenticatorAddresses - optional authenticator addresses to avoid redundant user fetches (this is used for connected wallets to determine if a connected wallet is an authenticator) * * @returns A promise that resolves to an array of `v1WalletAccount` objects. * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallet accounts. */ fetchWalletAccounts: (params: FetchWalletAccountsParams) => Promise<WalletAccount[]>; /** * Fetches all private keys for the current user. * * - Retrieves private keys from the Turnkey API. * - Supports stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * @param params.organizationId - organization ID to target (defaults to the session's organization ID). * @returns A promise that resolves to an array of `v1PrivateKey` objects. * @throws {TurnkeyError} If no active session is found or if there is an error fetching private keys. */ fetchPrivateKeys: (params?: FetchPrivateKeysParams) => Promise<v1PrivateKey[]>; /** * Signs a message using the specified wallet account. * * Behavior differs depending on the wallet type: * * - **Connected wallets** * - Delegates signing to the wallet provider’s native signing method. * - *Ethereum*: signatures always follow [EIP-191](https://eips.ethereum.org/EIPS/eip-191). * - The wallet automatically prefixes messages with * `"\x19Ethereum Signed Message:\n" + message length` before signing. * - As a result, these signatures cannot be used as raw transaction signatures or broadcast on-chain. * - If `addEthereumPrefix` is set to `false`, an error is thrown because connected Ethereum wallets always prefix. * - *Other chains*: follows the native connected wallet behavior. * * - **Embedded wallets** * - Uses the Turnkey API to sign the message directly. * - Supports optional `addEthereumPrefix`: * - If `true` (default for Ethereum), the message is prefixed before signing. * - If `false`, the raw message is signed without any prefix. * * Additional details: * - Automatically handles encoding and hashing based on the wallet account’s address format, * unless explicitly overridden. * - Optionally allows stamping with a specific stamper * (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`). * * @param params.message - plaintext (UTF-8) message to sign. * @param params.walletAccount - wallet account to use for signing. * @param params.encoding - override for payload encoding (defaults to the encoding appropriate for the address format). * @param params.hashFunction - override for hash function (defaults to the function appropriate for the address format). * @param params.stampWith - optional stamper for the signing request. * @param params.addEthereumPrefix - whether to prefix the message with Ethereum’s * `"\x19Ethereum Signed Message:\n"` string (default: `true` for Ethereum). * @param params.organizationId - organization ID to target (defaults to the session's organization ID). * * @returns A promise that resolves to a `v1SignRawPayloadResult` containing the signature and metadata. * @throws {TurnkeyError} If signing fails, the wallet type does not support message signing, or the response is invalid. */ signMessage: (params: SignMessageParams) => Promise<v1SignRawPayloadResult>; /** * Signs a transaction using the specified wallet account. * * Behavior differs depending on the type of wallet: * * - **Connected wallets** * - Ethereum: does not support raw transaction signing. Calling this function will throw an error instructing you to use `signAndSendTransaction` instead. * - Solana: supports raw transaction signing via the connected wallet provider. * - Other chains: not supported; will throw an error. * * - **Embedded wallets** * - Delegates signing to the Turnkey API, which returns the signed transaction. * - Supports all Turnkey-supported transaction types (e.g., Ethereum, Solana, Tron). * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`). * - Note: For embedded Ethereum wallets, the returned signature doesn’t include the `0x` prefix. You should add `0x` before * broadcasting if it’s missing. It’s a good idea to check whether the signature already starts with `0x` before adding it, * since we plan to include the prefix by default in a future breaking change. * * @param params.walletAccount - wallet account to use for signing. * @param params.unsignedTransaction - unsigned transaction data as a serialized * string in the canonical encoding for the given `transactionType`. * @param params.transactionType - type of transaction (e.g., "TRANSACTION_TYPE_ETHEREUM", "TRANSACTION_TYPE_SOLANA", "TRANSACTION_TYPE_TRON"). * @param params.stampWith - stamper to use for signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`). * @param params.organizationId - organization ID to target (defaults to the session's organization ID). * @returns A promise that resolves to the signed transaction string. * @throws {TurnkeyError} If the wallet type is unsupported, signing fails, or the response is invalid. */ signTransaction: (params: SignTransactionParams) => Promise<string>; /** * Signs and broadcasts a transaction using the specified wallet account. * * Behavior differs depending on the type of wallet: * * - **Connected wallets** * - *Ethereum*: delegates to the wallet’s native `signAndSendTransaction` method. * - Does **not** require an `rpcUrl` (the wallet handles broadcasting). * - *Solana*: signs the transaction locally with the connected wallet, but requires an `rpcUrl` to broadcast it. * - Other chains: not supported; will throw an error. * * - **Embedded wallets** * - Signs the transaction using the Turnkey API. * - Requires an `rpcUrl` to broadcast the signed transaction, since Turnkey does not broadcast directly. * - Broadcasts the transaction using a JSON-RPC client and returns the resulting transaction hash/signature. * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`). * * @param params.walletAccount - wallet account to use for signing and broadcasting. * @param params.unsignedTransaction - unsigned transaction data as a serialized * string in the canonical encoding for the given `transactionType`. * @param params.transactionType - type of transaction (e.g., `"TRANSACTION_TYPE_SOLANA"`, `"TRANSACTION_TYPE_ETHEREUM"`). * @param params.rpcUrl - JSON-RPC endpoint used for broadcasting (required for Solana connected wallets and all embedded wallets). * @param params.stampWith - optional stamper to use when signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`). * @param params.organizationId - **Only for Turnkey embedded wallets**: organization ID to target (defaults to the session's organization ID). * @returns A promise that resolves to a transaction signature or hash. * @throws {TurnkeyError} If the wallet type is unsupported, or if signing/broadcasting fails. */ signAndSendTransaction: (params: SignAndSendTransactionParams) => Promise<string>; /** * @beta * * **API subject to change** * * Signs and submits an Ethereum transaction using a Turnkey-managed (embedded) wallet. * * This method performs **authorization and signing**, and submits the transaction * to Turnkey’s coordinator. It **does not perform any polling** — callers must use * `pollTransactionStatus` to obtain the final on-chain result. * * Behavior: * * - **Connected wallets** * - Connected wallets are **not supported** by this method. * - They must instead use `signAndSendTransaction`. * * - **Embedded wallets** * - Constructs the payload for Turnkey's `eth_send_transaction` endpoint. * - Fetches nonces automatically when needed (normal nonce or Gas Station nonce). * - Signs and submits the transaction through Turnkey. * - Returns a `sendTransactionStatusId`, which the caller must pass to * `pollTransactionStatus` to obtain the final result (tx hash + status). * * @param params.organizationId - Organization ID to execute the transaction under. * Defaults to the active session's organization. * * @param params.stampWith - Optional stamper to authorize signing (e.g., passkey). * * @param params.transaction - The Ethereum transaction details. * @returns A promise resolving to the `sendTransactionStatusId`. * This ID must be passed to `pollTransactionStatus`. * * @throws {TurnkeyError} If the transaction is invalid or Turnkey rejects it. */ ethSendTransaction: (params: EthSendTransactionParams) => Promise<string>; /** * @beta * * **API subject to change** * * Signs and submits a Solana transaction using a Turnkey-managed (embedded) wallet. * * This method performs **authorization and signing**, and submits the transaction * to Turnkey’s coordinator. It **does not perform any polling** — callers must use * `pollTransactionStatus` to obtain the final on-chain result. * * Behavior: * * - **Connected wallets** * - Connected wallets are **not supported** by this method. * - They must instead use `signAndSendTransaction`. * * - **Embedded wallets** * - Constructs the payload for Turnkey's `sol_send_transaction` endpoint. * - Signs and submits the transaction through Turnkey. * - Returns a `sendTransactionStatusId`, which the caller must pass to * `pollTransactionStatus` to obtain the final result (signature + status). * * @param params.organizationId - Organization ID to execute the transaction under. * Defaults to the active session's organization. * @param params.stampWith - Optional stamper to authorize signing (e.g., passkey). * @param params.transaction - The Solana transaction details. * @returns A promise resolving to the `sendTransactionStatusId`. * This ID must be passed to `pollTransactionStatus`. * @throws {TurnkeyError} If the transaction is invalid or Turnkey rejects it. */ solSendTransaction: (params: SolSendTransactionParams) => Promise<string>; /** * @beta * **API subject to change** * * Polls Turnkey for the final result of a previously submitted transaction. * * This function repeatedly calls `getSendTransactionStatus` until the transaction * reaches a terminal state. * * Terminal states: * - **COMPLETED** or **INCLUDED** → resolves with chain-specific transaction details * - **FAILED** rejects with an error * * Behavior: * * - Queries Turnkey every 500ms. * - Stops polling automatically when a terminal state is reached. * - Returns the full status payload from Turnkey. * - When available, Ethereum transaction details are exposed at `resp.eth.txHash`. * * @param params.organizationId - Organization ID under which the transaction was submitted. * @param params.sendTransactionStatusId - Status ID returned by `ethSendTransaction` or `solSendTransaction`. * @param params.pollingIntervalMs - Optional polling interval in milliseconds (default: 500ms). * @param params.stampWith - Optional stamper to use for polling. * * @returns A promise resolving to the transaction status payload if successful. * @throws {Error | string} If the transaction fails or is cancelled. */ pollTransactionStatus(params: PollTransactionStatusParams): Promise<TGetSendTransactionStatusResponse>; /** * Fetches the user details for the current session or a specified user. * * - Retrieves user details from the Turnkey API using the provided userId and organizationId, or defaults to those from the active session. * - If no userId is provided, the userId from the current session is used. * - If no organizationId is provided, the organizationId from the current session is used. * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * - Ensures that an active session exists before making the request. * * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId). * @param params.userId - user ID to fetch specific user details (defaults to the current session's userId). * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * @returns A promise that resolves to a `v1User` object containing the user details. * @throws {TurnkeyError} If there is no active session, if there is no userId, or if there is an error fetching user details. */ fetchUser: (params?: FetchUserParams) => Promise<v1User>; /** * Fetches an existing user by P-256 API key public key, or creates a new one if none exists. * * - This function is idempotent: multiple calls with the same `publicKey` will always return the same user. * - Attempts to find a user whose API keys include the given P-256 public key. * - If a matching user is found, it is returned as-is. * - If no matching user is found, a new user is created with the given public key as a P-256 API key. * * @param params.publicKey - the P-256 public key to use for lookup and creation. * @param params.createParams.userName - optional username to assign if creating a new user (defaults to `"Public Key User"`). * @param params.createParams.apiKeyName - optional API key name to assign if creating a new API key (defaults to `public-key-user-${publicKey}`). * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId). * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet). * @return