SDK Client Reference

All exports, types, and options for the HyperAuth SDK client.

SDK Client Reference

Package: @hyperauth/sdk


Factory function

createClient

async function createClient(config?: ClientConfig): Promise<HyperAuthClient>

Initializes the vault worker, loads the WASM enclave, and returns a fully initialized HyperAuthClient. Throws ClientStateError if the vault worker fails to start.

ParameterTypeDefaultDescription
configClientConfig{}Client configuration

HyperAuthClient

All operations route through the vault worker. The enclave is never called directly.

Static factory

static async create(
  plugin: WasmPlugin,
  config?: ClientConfig,
  core?: VaultWorkerCore,
): Promise<HyperAuthClient>

Constructs a client with an explicit WasmPlugin adapter. Used for testing or custom plugin topologies.


Configuration

ClientConfig

interface ClientConfig {
  wasmUrl?: string;
  wasmBytes?: Uint8Array;
  logger?: Pick<Console, 'log' | 'error' | 'warn' | 'info' | 'debug'>;
  debug?: boolean;
  autoLockTimeout?: number;
  contracts?: ContractsConfig;
}
FieldTypeDefaultDescription
wasmUrlstring'/enclave.wasm'URL to fetch the enclave WASM
wasmBytesUint8ArrayRaw WASM bytes (alternative to wasmUrl)
loggerPick<Console, ...>consoleLogger instance
debugbooleanfalseEnable debug logging
autoLockTimeoutnumber300000Milliseconds of inactivity before auto-lock. 0 disables.
contractsContractsConfigBase SepoliaOn-chain contract addresses

ContractsConfig

interface ContractsConfig {
  chainId: number;
  entryPoint: string;
  didRegistry: string;
  accountHelper: string;
  sessionSBT: string;
  hyperAuthFactory: string;
}

defaultContracts

Pre-configured addresses for Base Sepolia (chain ID 84532):

ContractAddress
entryPoint0x0000000071727De22E5E9d8BAf0edAc6f37da032
didRegistry0xd38972ffea26b66f09e2109e650887acd447e7b7
accountHelper0xd4d57cc363dd419cd95712eb5cddf1797ceb9dde
sessionSBT0x5a2822bd69aa3799232ac57decf2b07e3fed1881
hyperAuthFactory0xb797f4799d8aa218e9207f918fdea3afc76b1e18

Core methods

generate

async generate(credential: string, options?: GenerateOptions): Promise<GenerateResult>

Generates a new identity (DID + MPC key shares) from a WebAuthn credential. Resets the auto-lock timer.

Parameters

NameTypeDescription
credentialstringBase64-encoded serialized WebAuthn credential
optionsGenerateOptionsOptional generation parameters

GenerateOptions

interface GenerateOptions {
  identifier?: string;
  channel?: string;
  verification_proof?: string;
  encryptionKey?: string;
}
FieldTypeDescription
identifierstringHuman-readable identifier (alias)
channelstringChannel for credential binding
verification_proofstringVerification proof
encryptionKeystringBase64-encoded 32-byte AES-256 key for encrypting the vault database

Returns: GenerateResult

interface GenerateResult {
  success: boolean;
  did: string;
  address: string;
  shares: EncryptedShares & { enclave_id: string };
  parsed_credential: Record<string, unknown>;
}

ping

async ping(message?: string): Promise<PingResult>

Health check and echo test against the vault worker.

NameTypeDefaultDescription
messagestring'hello'Message to echo

Returns: PingResult

interface PingResult {
  success: boolean;
  message: string;
  echo?: string;
}

Cryptography methods

sign

async sign(encryptedShares: EncryptedShares, data: number[]): Promise<SignResult>

Signs raw data bytes using the MPC enclave with the given encrypted key shares.

NameTypeDescription
encryptedSharesEncryptedSharesEncrypted key shares from generate
datanumber[]Raw bytes to sign

Returns: SignResult

interface SignResult {
  signature: number[];
}

deriveAddress

async deriveAddress(publicKeyHex: string, chain: string): Promise<DeriveAddressResult>

Derives a chain address from a hex-encoded public key.

NameTypeDescription
publicKeyHexstringHex-encoded public key
chainstringChain identifier (e.g. 'ethereum')

Returns: DeriveAddressResult

interface DeriveAddressResult {
  address: string;
  chain: string;
}

mintUcan

async mintUcan(encryptedShares: EncryptedShares, ucanPayload: Record<string, unknown>): Promise<MintUcanResult>

Mints a signed UCAN token using the MPC key.

NameTypeDescription
encryptedSharesEncryptedSharesEncrypted key shares
ucanPayloadRecord<string, unknown>UCAN payload fields

Returns: MintUcanResult

interface MintUcanResult {
  signed_dag_cbor: number[];
}

parseWebAuthn

async parseWebAuthn(credential: Record<string, unknown>): Promise<ParseWebAuthnResult>

Parses a WebAuthn credential object through the enclave.

Returns: ParseWebAuthnResult

interface ParseWebAuthnResult {
  parsed: Record<string, unknown>;
}

Vault methods

load

async load(source: Uint8Array | number[]): Promise<LoadOutput>

Loads an encrypted database into the vault worker. Resets the auto-lock timer on success.

NameTypeDescription
sourceUint8Array | number[]Encrypted database bytes

Returns: LoadOutput — shape mirrors @hyperauth/schemas.


lock

async lock(): Promise<LockOutput>

Locks the vault: encrypts and serializes vault state. Clears the auto-lock timer.

Returns: LockOutput — shape mirrors @hyperauth/schemas.


unlock

async unlock(source: Uint8Array | number[], encryptionKey?: string): Promise<UnlockOutput>

Unlocks the vault from encrypted bytes. Resets the auto-lock timer on success.

NameTypeDescription
sourceUint8Array | number[]Encrypted database bytes
encryptionKeystringOptional base64-encoded AES-256 key

Returns: UnlockOutput — shape mirrors @hyperauth/schemas.


status

async status(): Promise<StatusOutput>

Returns current vault status (locked/initialized state).

Returns: StatusOutput — shape mirrors @hyperauth/schemas. Includes locked: boolean.


isLocked

async isLocked(): Promise<boolean>

Convenience accessor. Returns status().locked.


query

async query(did?: string): Promise<QueryOutput>

Queries the DID document, verification methods, accounts, and credentials for the given DID.

NameTypeDefaultDescription
didstring''DID to query; defaults to the current identity

Returns: QueryOutput

interface QueryOutput {
  did: string;
  controller: string;
  verification_methods: VerificationMethod[];
  accounts: Account[];
  credentials: Credential[];
}

Account

interface Account {
  address: string;
  chain_id: string;
  coin_type: number;
  account_index: number;
  address_index: number;
  label: string;
  is_default: boolean;
}

exportVault

async exportVault(options: VaultExportOptions): Promise<Uint8Array>

Exports the vault as a password-encrypted backup. Returns raw bytes. Throws PluginCallError on failure.

VaultExportOptions

interface VaultExportOptions {
  password: string;
}

importVault

async importVault(options: VaultImportOptions): Promise<VaultImportOutput>

Imports a vault from a password-encrypted backup.

VaultImportOptions

interface VaultImportOptions {
  data: Uint8Array | number[];
  password: string;
}

Returns: VaultImportOutput — shape mirrors @hyperauth/schemas. Includes success, did, accounts, credentials.


ERC-4337 methods

createRegistration

async createRegistration(input: CreateRegistrationInput): Promise<RegistrationResult>

Constructs a signed ERC-4337 UserOperation for DID registration. Throws PluginCallError on failure.

CreateRegistrationInput

interface CreateRegistrationInput {
  sender: string;
  alias: string;
  cid?: string;
  did?: string;
}

Returns: RegistrationResult

interface RegistrationResult {
  user_op: UserOp | null;
  did_hash: string;
  alias_hash: string;
  metadata_cid: string;
  call_data: string;
  entry_point: string;
  registry_addr: string;
}

signUserOp

async signUserOp(userOp: UserOp, token?: string): Promise<SignUserOpResult>

Signs an ERC-4337 UserOperation using the MPC enclave. Throws PluginCallError on failure.

NameTypeDescription
userOpUserOpERC-4337 v0.7 UserOperation
tokenstringOptional UCAN delegation token

Returns: SignUserOpResult

interface SignUserOpResult {
  signature: string;
  user_op_hash: string;
  enclave_id: string;
  public_key: string;
}

execute

async execute<T = unknown>(
  resource: Resource,
  action: string,
  options?: { subject?: string; token?: string },
): Promise<ExecOutput<T>>

Executes a resource-action command through the vault worker.

NameTypeDescription
resourceResourceTarget resource
actionstringAction name
options.subjectstringJSON-encoded subject parameters
options.tokenstringOptional UCAN delegation token

Resource

type Resource =
  | 'accounts'
  | 'credentials'
  | 'sessions'
  | 'grants'
  | 'enclaves'
  | 'delegations'
  | 'ucans'
  | 'verification_methods'
  | 'services'
  | 'service_configs'
  | 'tokens'
  | 'invocations'
  | 'sync'
  | 'oidc'

Returns: ExecOutput<T>

interface ExecOutput<T = unknown> {
  success: boolean;
  result?: T;
  error?: string;
}

submitPayment

async submitPayment(params: PaymentParams): Promise<PaymentResult>

Builds, signs, and submits an ERC-4337 payment UserOperation. Throws PluginCallError on failure.

PaymentParams

interface PaymentParams {
  to: string;
  amount: string;
  token: string;
  chainId: number;
  ucan?: string;
  label?: string;
}
FieldTypeDescription
tostringRecipient address or DID
amountstringAmount in wei
tokenstringERC-20 token address or 'native' for ETH
chainIdnumberTarget chain ID
ucanstringOptional UCAN delegation token for spending constraints
labelstringOptional label

Returns: PaymentResult

interface PaymentResult {
  txHash: string;
  userOpHash: string;
  chain: number;
  token: string;
  explorerUrl: string;
}

registerPaymentHandler

async registerPaymentHandler(options?: PaymentHandlerOptions): Promise<PaymentHandlerRegistration>

Registers a Payment Handler API service worker for browser-native payment flows.

PaymentHandlerOptions

interface PaymentHandlerOptions {
  swUrl?: string;
  scope?: string;
  methodUrl?: string;
}
FieldTypeDefaultDescription
swUrlstring'/pay/sw.js'Service worker URL
scopestring'/pay/'Service worker scope
methodUrlstring'https://did.run/pay'Payment method identifier URL

Returns: PaymentHandlerRegistration

interface PaymentHandlerRegistration {
  success: boolean;
  scope: string;
  error?: string;
}

Indexer methods

These are module-level functions, not methods on HyperAuthClient.

computeAliasHash

async function computeAliasHash(alias: string, keccak256?: Keccak256Fn): Promise<`0x${string}`>

Computes the on-chain alias hash: keccak256(hexEncode(utf8Bytes(alias))). Matches the Go enclave convention.

NameTypeDescription
aliasstringNormalized alias string
keccak256Keccak256FnOptional keccak256 implementation; defaults to hash-wasm
type Keccak256Fn = (value: Uint8Array | `0x${string}`) => `0x${string}`

lookupAlias

async function lookupAlias(aliasHash: string, indexerUrl?: string): Promise<IndexerAlias>

Queries the indexer for a registered alias by its hash.

Returns: IndexerAlias

interface IndexerAlias {
  found: boolean;
  alias_hash?: string;
  did_hash?: string;
  active?: boolean;
  controller?: string;
}

lookupDid

async function lookupDid(didHash: string, indexerUrl?: string): Promise<IndexerDid>

Returns: IndexerDid

interface IndexerDid {
  found: boolean;
  did_hash?: string;
  controller?: string;
  metadata_cid?: string;
  active?: boolean;
  block_number?: string;
  tx_hash?: string;
}

lookupAccount

async function lookupAccount(address: string, indexerUrl?: string): Promise<IndexerAccount>

Returns: IndexerAccount

interface IndexerAccount {
  found: boolean;
  account_address?: string;
  owner_address?: string;
  block_number?: string;
  tx_hash?: string;
}

fetchStats

async function fetchStats(indexerUrl?: string): Promise<IndexerStats>

Returns: IndexerStats

interface IndexerStats {
  total_dids: number;
  active_dids: number;
  total_aliases: number;
  total_accounts: number;
  last_block_number: number;
}

fetchHealth

async function fetchHealth(indexerUrl?: string): Promise<IndexerHealth>

Returns: IndexerHealth

interface IndexerHealth {
  ok: boolean;
  chain: number;
}

Default indexerUrl for all indexer functions: '/api/indexer'.


Passkey helpers

createPasskey

async function createPasskey(
  handle: string,
  capabilities?: DeviceCapabilities,
  options?: CreatePasskeyOptions,
): Promise<CreatePasskeyResult>

Creates a WebAuthn passkey using the ES256 (P-256) algorithm. Only ES256 is accepted; the function throws WebAuthnError if the authenticator returns a different algorithm.

CreatePasskeyOptions

interface CreatePasskeyOptions {
  rpName?: string;
  rpId?: string;
  timeout?: number;
  excludeCredentials?: { id: BufferSource; type: 'public-key'; transports?: AuthenticatorTransport[] }[];
}
FieldTypeDefaultDescription
rpNamestring'HyperAuth'Relying party name
rpIdstring'did.run'Relying party ID
timeoutnumber60000Ceremony timeout in ms
excludeCredentialsarrayCredentials to exclude

Returns: CreatePasskeyResult

interface CreatePasskeyResult {
  credential: string;
  credentialId: string;
}

authenticatePasskey

async function authenticatePasskey(rpId?: string): Promise<string>

Triggers a WebAuthn assertion ceremony. Returns the credential ID string. Throws WebAuthnError if unsupported or cancelled.

NameTypeDefault
rpIdstring'did.run'

DeviceCapabilities

interface DeviceCapabilities {
  webAuthnSupported: boolean;
  platformAuthAvailable: boolean;
  conditionalMediationAvailable: boolean;
}

Device sync methods

syncInit

async syncInit(label?: string, expiresIn?: number): Promise<SyncInitResult>

Initiates a device-to-device vault sync session. Returns a session ID and public key for the initiating device. Throws PluginCallError on failure.

NameTypeDefaultDescription
labelstring''Label for the sync session
expiresInnumber0Expiration in seconds

Returns: SyncInitResult — shape mirrors @hyperauth/schemas. Includes success, session_id, public_key, error?.


syncRespond

async syncRespond(sessionId: string, remotePublicKey: string): Promise<SyncRespondResult>

Responds to a sync request from a remote device. Throws PluginCallError on failure.

Returns: SyncRespondResult — shape mirrors @hyperauth/schemas.


syncComplete

async syncComplete(sessionId: string, remotePublicKey?: string): Promise<SyncCompleteResult>

Completes the sync handshake and merges vault state. Throws PluginCallError on failure.

Returns: SyncCompleteResult — shape mirrors @hyperauth/schemas.


UCAN delegation methods

delegate

async delegate(options: DelegationOptions): Promise<ExecOutput<void>>

Creates a UCAN delegation to another DID. Throws PluginCallError on failure.

DelegationOptions

interface DelegationOptions {
  to: string;
  command: string;
  expiration?: number;
  caveats?: Record<string, unknown>;
}
FieldTypeDescription
tostringDID of the delegate (audience)
commandstringUCAN command path, e.g. '/vault/read'
expirationnumberExpiration timestamp (seconds since epoch)
caveatsRecord<string, unknown>Optional attenuation caveats

createInvocation

async createInvocation(options: InvocationOptions): Promise<ExecOutput<void>>

Creates a UCAN invocation. Throws PluginCallError on failure.

InvocationOptions

interface InvocationOptions {
  command: string;
  args?: Record<string, unknown>;
  token?: string;
}

Persistence methods

These methods require the VaultWorkerCore bridge (available when using createClient).

getBootStatus

async getBootStatus(): Promise<BootStatus>

Returns boot status of the enclave and supporting services. Returns all-false if no core bridge is available.

interface BootStatus {
  enclave: boolean;
  helia: boolean;
  libp2p: boolean;
  ready: boolean;
}

hasPersistedVault

async hasPersistedVault(): Promise<boolean>

Returns true if a persisted vault state is available for restore.


snapshotVault

async snapshotVault(): Promise<{ cid: string } | { error: string }>

Takes a content-addressed snapshot of current vault state via Helia (IPFS). Returns { error } if no core bridge is available.


persistNow

async persistNow(): Promise<{ success: boolean; error?: string }>

Triggers an immediate persistence flush. Returns { success: false, error } if no core bridge is available.


hasCorebridge

get hasCorebridge(): boolean

true when the client was created with createClient and has access to the vault worker core bridge.


Auto-lock methods

setAutoLockCallback

setAutoLockCallback(callback: (database: number[]) => void): void

Registers a callback invoked with the encrypted database bytes when the auto-lock timer fires.


setAutoLockTimeout

setAutoLockTimeout(ms: number): void

Updates the auto-lock inactivity timeout in milliseconds. Resets the current timer. 0 disables auto-lock.


Lifecycle methods

reset

async reset(): Promise<void>

Resets the plugin state and clears the activity timer.


close

async close(): Promise<void>

Closes the plugin and clears the activity timer.


Wallet pipeline functions

Module-level functions for ERC-4337 UserOperation handling.

sendUserOp

async function sendUserOp(
  userOp: UserOp,
  entryPoint?: string,
  bundlerUrl?: string,
): Promise<string>

Submits a UserOperation to the bundler via eth_sendUserOperation. Returns the userOpHash.

Default bundlerUrl: '/api/bundler'.


getUserOpReceipt

async function getUserOpReceipt(
  userOpHash: string,
  bundlerUrl?: string,
): Promise<UserOpReceipt | null>

Fetches a UserOperation receipt. Returns null if not yet confirmed.

UserOpReceipt

interface UserOpReceipt {
  userOpHash: string;
  sender: string;
  nonce: string;
  success: boolean;
  actualGasCost: string;
  actualGasUsed: string;
  receipt: {
    transactionHash: string;
    blockNumber: string;
    status: string;
  };
}

waitForReceipt

async function waitForReceipt(
  userOpHash: string,
  options?: { timeout?: number; interval?: number; bundlerUrl?: string },
): Promise<UserOpReceipt>

Polls for a UserOperation receipt until confirmed or timeout. Throws NetworkError on timeout.

OptionTypeDefault
timeoutnumber120000
intervalnumber3000
bundlerUrlstring'/api/bundler'

getSupportedEntryPoints

async function getSupportedEntryPoints(bundlerUrl?: string): Promise<string[]>

Returns supported entry point addresses from the bundler.


estimateUserOpGas

async function estimateUserOpGas(
  userOp: UserOp,
  entryPoint?: string,
  bundlerUrl?: string,
): Promise<GasEstimate>

Estimates gas for a UserOperation via eth_estimateUserOperationGas.


sponsorUserOp

async function sponsorUserOp(
  userOp: UserOp,
  entryPoint?: string,
  bundlerUrl?: string,
): Promise<UserOp>

Sponsors a UserOperation via pm_sponsorUserOperation. Returns the UserOperation with paymaster fields populated.


getSmartAccountAddress

async function getSmartAccountAddress(input: GetSmartAccountAddressInput): Promise<string>

Predicts the smart account address from public key coordinates via the vault API.

interface GetSmartAccountAddressInput {
  pubKeyX: string;
  pubKeyY: string;
  salt?: string | number | bigint;
  vaultUrl?: string;
}

Default vaultUrl: '/api'.


getAccountState

async function getAccountState(input: GetAccountStateInput): Promise<AccountState>

Fetches on-chain account state from the vault API.

interface GetAccountStateInput {
  account: string;
  vaultUrl?: string;
}

Returns: AccountState

interface AccountState {
  nonce: string;
  did: string;
  isActive: boolean;
  pubKeyX: string;
  pubKeyY: string;
}

computeUserOpHash

async function computeUserOpHash(
  userOp: UserOp,
  entryPoint: string,
  chainId: number,
): Promise<`0x${string}`>

Computes the ERC-4337 v0.7 UserOperation hash client-side. Matches on-chain hash derivation.


Hex utilities

function binaryToBytes(value: BinaryPayload): Uint8Array
function normalizeHex(hex: string): `0x${string}`
function hexToBytes(hex: string): Uint8Array
function bytesToHex(bytes: Uint8Array): `0x${string}`
type BinaryPayload = number[] | string

Error classes

All errors extend HyperAuthError extends Error.

ClassnameDescription
HyperAuthError'HyperAuthError'Base class
WasmLoadError'WasmLoadError'WASM plugin failed to load or initialize
PluginCallError'PluginCallError'A vault worker function call failed. Has functionName: string.
ClientStateError'ClientStateError'Client used before initialization or after close
WebAuthnError'WebAuthnError'WebAuthn unsupported, cancelled, or wrong algorithm
NetworkError'NetworkError'HTTP or RPC network failure
StorageError'StorageError'Secure storage operation failure

Shared types

EncryptedShares

interface EncryptedShares {
  public_key: BinaryPayload;
  public_key_hex?: string;
  val_share: BinaryPayload;
  user_share: BinaryPayload;
  nonce: BinaryPayload;
  curve: string;
  pubkey_x?: string;
  pubkey_y?: string;
}

UserOp

ERC-4337 v0.7 packed UserOperation. Shape mirrors @hyperauth/schemas.

FieldType
senderstring
noncestring
factory`0x${string}` | null
factoryDatastring | null
callDatastring
callGasLimitstring
verificationGasLimitstring
preVerificationGasstring
maxFeePerGasstring
maxPriorityFeePerGasstring
paymasterstring | null
paymasterVerificationGasLimitstring | null
paymasterPostOpGasLimitstring | null
paymasterDatastring | null
signaturestring

On this page