CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-orbitdb--core

Distributed p2p database on IPFS with automatic peer synchronization and conflict-free writes

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

orbitdb-factory.mddocs/

OrbitDB Factory

The OrbitDB factory creates and manages OrbitDB instances with IPFS integration and peer synchronization. It serves as the main entry point for creating distributed databases.

Capabilities

Creating OrbitDB Instances

Creates an OrbitDB instance with the provided IPFS instance and configuration.

/**
 * Creates an OrbitDB instance
 * @param params Configuration parameters
 * @param params.ipfs IPFS instance (required)
 * @param params.id Identity ID (optional, auto-generated if not provided)
 * @param params.identity Identity instance or provider configuration
 * @param params.identities Identities system instance
 * @param params.directory Storage directory (default: './orbitdb')
 * @returns Promise resolving to OrbitDB instance
 * @throws "IPFS instance is a required argument" if no IPFS instance provided
 */
function createOrbitDB(params: {
  ipfs: IPFS;
  id?: string;
  identity?: Identity | { provider: IdentityProvider };
  identities?: Identities;
  directory?: string;
}): Promise<OrbitDB>;

Usage Examples:

import { createHelia } from 'helia';
import { createOrbitDB } from '@orbitdb/core';

// Basic usage with Helia IPFS
const ipfs = await createHelia();
const orbitdb = await createOrbitDB({ ipfs });

// With custom directory
const orbitdb2 = await createOrbitDB({ 
  ipfs, 
  directory: './my-orbitdb-data' 
});

// With custom identity ID
const orbitdb3 = await createOrbitDB({ 
  ipfs, 
  id: 'my-unique-id' 
});

OrbitDB Instance Interface

The OrbitDB instance provides methods for database management and system control.

interface OrbitDB {
  /** Opens or creates a database */
  open(name: string, options?: DatabaseOptions): Promise<Database>;
  /** Stops the OrbitDB instance and cleans up resources */
  stop(): Promise<void>;
  /** The IPFS instance used by this OrbitDB */
  ipfs: IPFS;
  /** The directory where OrbitDB stores data */
  directory: string;
  /** The keystore instance for cryptographic operations */
  keystore: KeyStore;
  /** The identities system for identity management */
  identities: Identities;
  /** The current identity used by this OrbitDB instance */
  identity: Identity;
  /** The peer ID of this OrbitDB instance */
  peerId: PeerId;
}

Opening Databases

Creates or opens databases with various configuration options.

/**
 * Opens or creates a database
 * @param name Database name or address
 * @param options Database configuration options
 * @returns Promise resolving to Database instance
 */
open(name: string, options?: DatabaseOptions): Promise<Database>;

interface DatabaseOptions {
  /** Database type (default: 'events') */
  type?: string;
  /** Database constructor function */
  Database?: DatabaseConstructor;
  /** Access controller constructor */
  AccessController?: AccessControllerConstructor;
  /** Storage directory for this database */
  directory?: string;
  /** Database metadata */
  meta?: object;
  /** Storage backend for log heads */
  headsStorage?: Storage;
  /** Storage backend for log entries */
  entryStorage?: Storage;
  /** Storage backend for database index */
  indexStorage?: Storage;
  /** Maximum distance between references (default: 16) */
  referencesCount?: number;
  /** Enable automatic peer synchronization (alias: sync) */
  syncAutomatically?: boolean;
  /** Callback fired when entries are added */
  onUpdate?: (entry: Entry) => void;
  /** Encryption configuration */
  encryption?: {
    encryptFn: (data: any) => any;
    decryptFn: (data: any) => any;
  };
}

Usage Examples:

import { createHelia } from 'helia';
import { createOrbitDB, Documents, KeyValue } from '@orbitdb/core';

const ipfs = await createHelia();
const orbitdb = await createOrbitDB({ ipfs });

// Open default Events database
const events = await orbitdb.open('my-events');

// Open Documents database with custom index
const docs = await orbitdb.open('my-docs', {
  Database: Documents({ indexBy: 'id' })
});

// Open KeyValue database with custom metadata
const kv = await orbitdb.open('my-kv', {
  Database: KeyValue(),
  meta: { description: 'My key-value store' }
});

// Open database with custom access control
const privateDb = await orbitdb.open('private-db', {
  AccessController: OrbitDBAccessController({ write: ['alice', 'bob'] })
});

// Open database with automatic sync
const syncedDb = await orbitdb.open('synced-db', {
  syncAutomatically: true,
  onUpdate: (entry) => console.log('New entry:', entry)
});

Database Address Handling

OrbitDB can open databases using either names or full addresses.

// Open by name (creates new database or opens existing)
const db1 = await orbitdb.open('my-database');

// Open by full OrbitDB address
const address = '/orbitdb/zdpuAkstgbTVGHQmMi5TC84auhJ8rL5qoaNEtXo2d5PHXs2To';
const db2 = await orbitdb.open(address);

// Get database address for sharing
const dbAddress = db1.address.toString();
console.log('Share this address:', dbAddress);

Identity Configuration

OrbitDB instances can be configured with custom identities for cryptographic operations.

import { createOrbitDB, Identities, PublicKeyIdentityProvider } from '@orbitdb/core';

// Using default identity (auto-generated)
const orbitdb1 = await createOrbitDB({ ipfs });

// Using custom identity provider
const identities = await Identities({ ipfs });
const identity = await identities.createIdentity({ 
  provider: PublicKeyIdentityProvider() 
});

const orbitdb2 = await createOrbitDB({ 
  ipfs, 
  identity 
});

// Using pre-created identities instance
const orbitdb3 = await createOrbitDB({ 
  ipfs, 
  identities 
});

Storage Configuration

Configure custom storage backends for different components.

import { 
  createOrbitDB, 
  LevelStorage, 
  MemoryStorage, 
  ComposedStorage 
} from '@orbitdb/core';

const ipfs = await createHelia();
const orbitdb = await createOrbitDB({ ipfs });

// Configure storage for specific database
const db = await orbitdb.open('my-db', {
  headsStorage: await LevelStorage({ path: './heads' }),
  entryStorage: await MemoryStorage(),
  indexStorage: await ComposedStorage([
    await MemoryStorage(),
    await LevelStorage({ path: './index' })
  ])
});

Lifecycle Management

Proper lifecycle management ensures clean shutdown and resource cleanup.

const ipfs = await createHelia();
const orbitdb = await createOrbitDB({ ipfs });

try {
  // Use OrbitDB
  const db = await orbitdb.open('my-db');
  await db.add('Hello World');
  await db.close();
} finally {
  // Always clean up
  await orbitdb.stop();
  await ipfs.stop();
}

Error Handling

Common errors and how to handle them:

import { createOrbitDB } from '@orbitdb/core';

try {
  // Missing IPFS instance
  const orbitdb = await createOrbitDB({});
} catch (error) {
  console.error(error.message); // "IPFS instance is a required argument."
}

try {
  const ipfs = await createHelia();
  const orbitdb = await createOrbitDB({ ipfs });
  
  // Invalid database address
  const db = await orbitdb.open('invalid-address');
} catch (error) {
  console.error('Failed to open database:', error.message);
}

Integration with Helia and Libp2p

OrbitDB requires proper IPFS and Libp2p configuration for networking and storage:

import { createHelia } from 'helia';
import { createLibp2p } from 'libp2p';
import { gossipsub } from '@chainsafe/libp2p-gossipsub';
import { identify } from '@libp2p/identify';
import { createOrbitDB } from '@orbitdb/core';

// Configure Libp2p for OrbitDB
const libp2pOptions = {
  services: {
    pubsub: gossipsub({
      allowPublishToZeroTopicPeers: true
    }),
    identify: identify()
  }
};

const libp2p = await createLibp2p(libp2pOptions);
const ipfs = await createHelia({ libp2p });
const orbitdb = await createOrbitDB({ ipfs });

// Now OrbitDB can sync with peers
const db = await orbitdb.open('shared-db');

Install with Tessl CLI

npx tessl i tessl/npm-orbitdb--core

docs

access-controllers.md

address-management.md

database-types.md

identity-system.md

index.md

oplog-system.md

orbitdb-factory.md

storage-backends.md

tile.json