Skip to main content

API Reference

Complete API documentation with TypeScript types for all exports from @uppzen/midnight-auth.

Provider

MidnightAuthProvider

The root provider component that wraps your application and manages wallet state.

Props

interface MidnightAuthProviderProps {
children: React.ReactNode
sessionTimeout?: number
autoConnect?: boolean
onConnect?: (walletState: WalletState) => void
onDisconnect?: () => void
onError?: (error: Error) => void
}
PropTypeDefaultDescription
childrenReactNodeRequiredChild components
sessionTimeoutnumber86400000 (24h)Session duration in milliseconds
autoConnectbooleantrueAuto-reconnect on mount if previously connected
onConnect(walletState: WalletState) => void-Callback fired when wallet connects
onDisconnect() => void-Callback fired when wallet disconnects
onError(error: Error) => void-Callback fired on errors

Example

<MidnightAuthProvider
sessionTimeout={60 * 60 * 1000} // 1 hour
autoConnect={true}
onConnect={(walletState) => {
console.log('Connected:', walletState.address)
}}
onError={(error) => {
console.error('Error:', error)
}}
>
{children}
</MidnightAuthProvider>

Core Types

WalletState

Complete wallet state returned by the Midnight provider.

interface WalletState {
// Address fields
address?: string
shieldAddress?: string
addressLegacy?: string
legacyAddress?: string

// Balance
balance?: string
balances?: BalanceBreakdown

// Provider info
provider?: string
providerName?: string

// Cryptographic keys
coinPublicKey?: string
coinPublicKeyLegacy?: string
encryptionPublicKey?: string
encryptionPublicKeyLegacy?: string

// Versioning
apiVersion?: string

// Extensible
[key: string]: any
}

BalanceBreakdown

Detailed breakdown of wallet balances.

interface BalanceBreakdown {
unshielded: string // Unshielded balance (public)
shielded: string // Shielded balance (private)
total: string // Total balance (sum of both)
}

Session

Session object tracking the current wallet connection session.

interface Session {
address: string // Connected wallet address
connectedAt: number // Timestamp when connected
expiresAt?: number // Optional expiration timestamp
metadata?: Record<string, any> // Custom session metadata
}

API Types

MidnightWalletAPI

The wallet API interface exposed by the Midnight provider.

interface MidnightWalletAPI {
// Core state method (required)
state: () => Promise<WalletState>

// Balance methods (optional)
balances?: () => Promise<{
unshielded: bigint
shielded: bigint
}>
getBalance?: () => Promise<string>

// Transaction methods (optional)
signData?: (
address: string,
payload: string
) => Promise<SignDataResult>

submitTx?: (tx: any) => Promise<TransactionResult>

// Extensible for additional methods
[key: string]: any
}

SignDataResult

Result object returned when signing data with the wallet.

interface SignDataResult {
signature: string // Cryptographic signature
key: string // Public key used for signing
}

TransactionResult

Result object returned after submitting a transaction.

interface TransactionResult {
txHash: string // Transaction hash identifier
success: boolean // Whether transaction was successful
}

Context Value

MidnightAuthContextValue

The complete context value provided by useMidnightAuth hook.

interface MidnightAuthContextValue {
// Connection state
isConnected: boolean
isConnecting: boolean
walletState: WalletState | null
error: string | null

// Session state
session: Session | null

// Core methods
connect: () => Promise<void>
disconnect: () => void
clearError: () => void

// Session methods
refreshSession: () => Promise<void>
updateSessionMetadata: (metadata: Record<string, any>) => void

// Wallet API access
getWalletAPI: () => any | null

// Transaction methods
signData?: (address: string, payload: string) => Promise<SignDataResult>
submitTransaction?: (tx: any) => Promise<TransactionResult>
}

Component Props

MidnightConnectButtonProps

interface MidnightConnectButtonProps {
className?: string
connectText?: string
connectingText?: string
disconnectText?: string
onConnectSuccess?: () => void
onDisconnectSuccess?: () => void
variant?: "default" | "outline" | "ghost"
size?: "sm" | "md" | "lg"
}

MidnightWalletInfoProps

interface MidnightWalletInfoProps {
className?: string
showBalance?: boolean
showProvider?: boolean
addressFormat?: "short" | "full"
variant?: "card" | "compact" | "inline"
}

MidnightSessionTimerProps

interface MidnightSessionTimerProps {
className?: string
showRefreshButton?: boolean
autoRefreshThreshold?: number
variant?: "default" | "compact" | "minimal"
}

ProtectedRouteProps

interface ProtectedRouteProps {
children: ReactNode
fallback?: ReactNode
}

Methods

connect()

Initiates wallet connection.

const { connect } = useMidnightAuth()

await connect()

Returns: Promise<void>

Throws: Error if connection fails

disconnect()

Disconnects the wallet and clears session.

const { disconnect } = useMidnightAuth()

disconnect()

Returns: void

refreshSession()

Refreshes the current session, extending its expiration.

const { refreshSession } = useMidnightAuth()

await refreshSession()

Returns: Promise<void>

signData()

Signs data with the connected wallet.

const { signData } = useMidnightWallet()

const result = await signData(address, 'Message to sign')
console.log(result.signature)
console.log(result.key)

Parameters:

  • address: string - Wallet address to sign with
  • payload: string - Data to sign

Returns: Promise<SignDataResult>

submitTransaction()

Submits a transaction to the Midnight Network.

const { submitTransaction } = useMidnightWallet()

const result = await submitTransaction(tx)
if (result.success) {
console.log('Transaction hash:', result.txHash)
}

Parameters:

  • tx: any - Transaction object

Returns: Promise<TransactionResult>

updateSessionMetadata()

Updates session metadata with custom data.

const { updateSessionMetadata } = useMidnightAuth()

updateSessionMetadata({
lastActivity: Date.now(),
preferences: { theme: 'dark' }
})

Parameters:

  • metadata: Record<string, any> - Custom metadata object

Returns: void

clearError()

Clears the current error state.

const { clearError } = useMidnightAuth()

clearError()

Returns: void

getWalletAPI()

Returns the raw wallet API object.

const { getWalletAPI } = useMidnightAuth()

const api = getWalletAPI()
if (api) {
const state = await api.state()
}

Returns: any | null

Importing Types

All types are exported from the main package:

import type {
// Core Types
WalletState,
BalanceBreakdown,
Session,

// API Types
MidnightWalletAPI,
SignDataResult,
TransactionResult,

// Context & Provider Types
MidnightAuthContextValue,
MidnightAuthProviderProps,

// Component Props
MidnightConnectButtonProps,
MidnightWalletInfoProps,
MidnightSessionTimerProps,
ProtectedRouteProps
} from '@uppzen/midnight-auth'

Error Handling

All async methods can throw errors. Always wrap in try-catch:

try {
await connect()
} catch (error) {
console.error('Connection failed:', error)
}

Common error scenarios:

  • Wallet extension not installed
  • User rejected connection
  • Network errors
  • Invalid transaction data

Next Steps