@enc-protocol/client
v0.9.0
Published
ENC Protocol client — HTTP, WebSocket, unified facade, session, wallet. Generated from Lean 4 DSL (unified.js is hand-authored above the spec primitives).
Readme
@enc-protocol/client
HTTP + WebSocket client for ENC protocol nodes. Provides identity management, commit submission, encrypted queries, session handling, and registry lookups.
Install
npm install @enc-protocol/clientAPI
Core Identity & Cryptography
createIdentity(seed?: Uint8Array | string): { privateKey, publicKey, publicKeyHex }— Generate or derive an identity keypair.loadIdentity(privateKey: Uint8Array): { privateKey, publicKey, publicKeyHex }— Reconstruct identity from a private key.signWithIdentity(identity: object, data: Uint8Array | string): Uint8Array— Sign data with an identity (Schnorr).generateKeypair(): { privateKey, publicKey }— Generate a random keypair.derivePublicKey(privateKey: Uint8Array): Uint8Array— Derive public key from private key.bytesToHex(bytes: Uint8Array): string— Encode bytes as hex string.hexToBytes(hex: string): Uint8Array— Decode hex string to bytes.sha256Hash(data: Uint8Array | string): Uint8Array— Compute SHA-256 hash.taggedHash(tag: string, data: Uint8Array): Uint8Array— Compute tagged hash.ecdh(privKey: Uint8Array, pubBytes: Uint8Array): Uint8Array— ECDH key agreement.deriveKey(shared: Uint8Array, label: string): Uint8Array— Derive encryption key from shared secret.encrypt(key: Uint8Array, plaintext: string): string— Encrypt plaintext to ciphertext (base64).decrypt(key: Uint8Array, ciphertext: string): string— Decrypt ciphertext to plaintext.
Commits & Events
createCommit(identity, enclave, type, content, exp?, tags?): object(async-capable) — Sign a commit to an enclave. Auto-expiry 5 minutes ifexpomitted.createManifestCommit(identity, manifestContent, exp?, tags?): object— Sign a manifest commit (enclave registration).buildRegEnclaveContent(manifestEvent, opts?): string— Build JSON-encoded registry content from manifest event.computeCommitHash(commit: object): Uint8Array— Hash a commit.computeContentHash(content: string): Uint8Array— Hash content string.
HTTP Client (NodeClient)
High-level HTTP API to an ENC node. Supports plaintext and ECDH-encrypted queries.
new NodeClient(baseUrl, opts?): NodeClient— Create an HTTP client.opts:{ enclaveId, identityPubHex, seqPubHex, sessionManager }.pingLiveness(): Promise<boolean>— Check if node is alive.submitCommit(commit): Promise<object>— Submit a signed commit; returns receipt.getSTH(enclaveId?): Promise<object>— Fetch Signed Tree Head.query(filter, auth?): Promise<object>(async) — Query events from an enclave (supports encrypted filter).pull(afterSeq, opts?): Promise<object>(async) — Fetch events after a sequence number.info(): Promise<object>(async) — Get enclave info (requires encryption credentials).getInclusion(leafIndex): Promise<object>(async) — Fetch inclusion proof for an event.getState(key): Promise<object>(async) — Fetch state proof for a key.encrypted: boolean— True if credentials are configured for encrypted requests.
WebSocket Client (NodeWebSocket)
Real-time event streaming via WebSocket.
new NodeWebSocket(url): NodeWebSocket— Create WebSocket client.connect(): NodeWebSocket— Open connection.close(): void— Close connection.connected: boolean— True if socket is open.on(event, handler): NodeWebSocket— Register event handler ('open','close','error','event','eose','receipt','closed','notice').subscribe(enclave, from?, session?, filter?): null— Subscribe to enclave events.unsubscribe(subId): void— Unsubscribe from a subscription.commit(commit): void— Submit a commit via WebSocket.
Unified HTTP + WebSocket Client (EncClient)
Combines HTTP and WebSocket in one facade. Auto-derives WS URL from HTTP URL and vice versa.
new EncClient(url, opts?): EncClient— Create unified client.url: http://, https://, ws://, or wss://; other scheme auto-derived.optspassed to NodeClient.async connect(): Promise<NodeWebSocket>— Open WebSocket (idempotent).close(): void— Close WebSocket.connected: boolean— True if WebSocket is open.submitCommit(commit): Promise<object>(async) — HTTP POST commit.query(filter, auth?): Promise<object>(async) — HTTP POST query.pull(afterSeq, opts?): Promise<object>(async) — HTTP POST pull.info(): Promise<object>(async) — HTTP GET enclave info.getSTH(enclaveId?): Promise<object>(async) — HTTP GET Signed Tree Head.getInclusion(leafIndex): Promise<object>(async) — HTTP POST inclusion proof.getState(key): Promise<object>(async) — HTTP POST state proof.on(event, handler): EncClient— Register WS event handler (buffered until connect).async subscribe(enclave, from?, session?, filter?): Promise<null>(async) — Subscribe via WS (auto-connects).unsubscribe(subId): void— Unsubscribe from WS subscription.async commitWS(commit): Promise<void>(async) — Submit commit via WS (auto-connects).createEncClient(url, opts?): EncClient— Factory function.
Session Management (SessionManager)
Handles ECDH session tokens for encrypted queries.
new SessionManager(identityPriv, opts?): SessionManager— Create session manager.opts:{ duration, refreshBefore }.getSession(): { session, sessionPriv, expires }— Get current session token; auto-refreshes if near expiry.token: string— Current session token.valid: boolean— True if session is not expired.refresh(): void— Manually refresh session.
Registry Client (RegistryClient)
Query an ENC registry service for nodes and enclaves.
new RegistryClient(registryUrl): RegistryClient— Create registry client.lookupNode(seqPub): Promise<object | null>— Fetch node by sequencer pubkey.lookupEnclave(enclaveId): Promise<object | null>— Fetch enclave metadata.resolveEnclave(enclaveId): Promise<object | null>— Resolve enclave (alias for lookupEnclave).listNodes(): Promise<Array>(async) — List all registered nodes.lookupIdentity(pubkey): Promise<object | null>— Fetch identity record by pubkey.listIdentities(): Promise<Array>(async) — List all registered identities.connectToEnclave(enclaveId): Promise<NodeClient | null>— Resolve enclave and return connected HTTP client.pingLiveness(): Promise<boolean>— Check registry health.submitCommit(commit): Promise<object>— Submit commit to registry.query(filter): Promise<object>— Query via registry.
Wallet & EVM Integration
encPubToEvmAddress(encPubHex): [string, string]— Derive two possible EVM addresses from ENC public key (even and odd Y prefixes).async resolveEvmAddress(encPubHex, rpcUrl): Promise<string>(async) — Resolve which EVM address has a balance (even or odd prefix).
Network Adapter (NetworkAdapter)
Transport layer for per-app SDKs (internal use).
new NetworkAdapter(nodeUrl, enclaveId, identity, seqPubHex): NetworkAdapter— Create adapter.async createEnclave(manifest): Promise<{ enclave_id, sequencer }>(async) — Create a new enclave.async submit(type, content): Promise<object>(async) — Submit signed content.async query(type?, opts?): Promise<Array>(async) — Query events by type.as(identity): NetworkAdapter— Create new adapter with different identity (for delegation).
Constants
ConnectionStatus—{ disconnected, connecting, connected, error }SubmitResult—{ success, notConnected, error }SDKInterface—{ node_api, registry_api, local_api }SDKOperation—{ createIdentity, loadIdentity, derivePublicKey, generatePrivateKey, signWithIdentity, createCommit, submitCommit, queryEvents, verifyNodeReceipt, verifyLogInclusion, verifyLogConsistency, cacheSTH, healthCheck, lookupNode, lookupEnclave, resolveEnclave }allSDKOperations— Array of allSDKOperationvalues.
Low-Level Connection & Verification Utilities
createConnection(host, port, nodePubHex): object— Build connection object.connect(conn): object— Mark connection as connected.disconnect(conn): object— Mark connection as disconnected.isConnected(conn): boolean— Check if connection is live.verifyNodeReceipt(receipt, nodePubHex): boolean— Verify receipt signature against node public key.healthCheck(state): object | null— Basic health check from client state.sdkOperationInterface(op): string | null— Get which interface (node_api, registry_api, or local_api) an operation uses.initClient(identity): object— Initialize client state.connectClient(state, host, port, nodePubHex): object— Update state with connection.disconnectClient(state): object— Update state to disconnected.clientIsConnected(state): boolean— Check if state.connection is live.getCachedSTH(state): object | null— Retrieve cached Signed Tree Head.cacheSTH(state, sth, timestamp): object— Update state with cached STH.createNodeClient(url): NodeClient— Factory for NodeClient.createRegistryClient(url): RegistryClient— Factory for RegistryClient.createWebSocket(url, opts): NodeWebSocket— Factory for NodeWebSocket.createSessionManager(identityPriv, opts): SessionManager— Factory for SessionManager.
Example
import { EncClient, createIdentity, createCommit } from '@enc-protocol/client'
// Create identity
const identity = createIdentity()
// Connect to node
const client = new EncClient('https://node.example.com')
// Submit a commit
const commit = createCommit(
identity,
'enclave-123',
'post',
JSON.stringify({ text: 'Hello' })
)
const receipt = await client.submitCommit(commit)
// Query events via HTTP
const events = await client.query({ enclave: 'enclave-123', type: 'post' })
// Subscribe to live events
client.on('event', (event, subId) => {
console.log('New event:', event)
})
client.on('eose', (subId) => {
console.log('End of stored events')
})
await client.subscribe('enclave-123', identity.publicKeyHex)
// Cleanup
client.close()