# IAVL-TS API Reference

This document provides comprehensive API documentation for IAVL-TS, a TypeScript implementation of the IAVL (Immutable AVL Tree) data structure.

## Table of Contents

- [Core Classes](#core-classes)
  - [MutableTree](#mutabletree)
  - [ImmutableTree](#immutabletree)
  - [Node](#node)
  - [NodeKey](#nodekey)
- [Storage Layer](#storage-layer)
  - [NodeDB](#nodedb)
  - [FastNode](#fastnode)
  - [Database](#database)
  - [MemDB](#memdb)
- [Iteration](#iteration)
  - [TreeIterator](#treeiterator)
  - [FastIterator](#fastiterator)
- [Import/Export](#importexport)
  - [Exporter](#exporter)
  - [Importer](#importer)
- [Proofs](#proofs)
  - [Proof Generation](#proof-generation)
  - [Proof Verification](#proof-verification)
- [Types & Interfaces](#types--interfaces)
  - [Options](#options)
  - [Statistics](#statistics)
  - [ExportNode](#exportnode)

---

## Core Classes

### MutableTree

The `MutableTree` class provides a mutable interface for modifying the IAVL tree. It supports set, remove, and version management operations.

#### Constructor

```typescript
constructor(
  ndb: NodeDB,
  workingTree: ImmutableTree,
  skipFastStorageUpgrade?: boolean
)
```

**Parameters:**
- `ndb`: NodeDB instance for storage
- `workingTree`: Initial immutable tree state
- `skipFastStorageUpgrade`: Optional flag to skip fast storage (default: false)

#### Static Methods

##### `create(ndb: NodeDB, skipFastStorageUpgrade?: boolean): Promise<MutableTree>`

Creates a new mutable tree, initializing from the latest version in the database.

**Example:**
```typescript
const tree = await MutableTree.create(nodeDB);
```

---

#### Tree State Methods

##### `getWorkingTree(): ImmutableTree`

Returns the current working tree (before saving).

##### `getRoot(): Node | null`

Returns the root node of the working tree.

##### `getVersion(): bigint`

Returns the version of the last saved tree.

##### `getWorkingVersion(): bigint`

Returns the version that will be assigned on the next save (current version + 1).

##### `getHash(): Uint8Array | null`

Returns the Merkle root hash of the last saved version.

##### `getWorkingHash(): Uint8Array | null`

Returns the Merkle root hash of the current working tree.

##### `getSize(): bigint`

Returns the number of keys in the tree.

##### `getNodeDB(): NodeDB`

Returns the NodeDB instance used by this tree.

---

#### Data Operations

##### `get(key: Uint8Array): Promise<Uint8Array | null>`

Retrieves the value for a given key from the working tree.

**Parameters:**
- `key`: Key to retrieve

**Returns:** Value if found, null otherwise

**Example:**
```typescript
const value = await tree.get(Buffer.from("mykey"));
```

##### `set(key: Uint8Array, value: Uint8Array): Promise<boolean>`

Sets a key-value pair in the working tree.

**Parameters:**
- `key`: Key to set
- `value`: Value to set

**Returns:** `true` if a new key was added, `false` if existing key was updated

**Example:**
```typescript
const isNew = await tree.set(Buffer.from("key"), Buffer.from("value"));
```

##### `remove(key: Uint8Array): Promise<{ value: Uint8Array | null, removed: boolean }>`

Removes a key from the working tree.

**Parameters:**
- `key`: Key to remove

**Returns:** Object with `value` (the removed value) and `removed` (whether removal occurred)

**Example:**
```typescript
const { value, removed } = await tree.remove(Buffer.from("key"));
if (removed) {
  console.log("Removed value:", value);
}
```

---

#### Version Management

##### `saveVersion(): Promise<{ hash: Uint8Array, version: bigint }>`

Saves the current working tree as a new version.

**Returns:** Object with `hash` (Merkle root) and `version` (new version number)

**Example:**
```typescript
const { hash, version } = await tree.saveVersion();
console.log(`Saved version ${version}`);
```

##### `loadVersion(targetVersion: bigint): Promise<bigint>`

Loads a specific version into the working tree.

**Parameters:**
- `targetVersion`: Version number to load

**Returns:** The latest version in the database (not the loaded version)

**Example:**
```typescript
await tree.loadVersion(5n);
// Working tree now contains state at version 5
```

##### `getImmutable(version: bigint): Promise<ImmutableTree>`

Gets an immutable snapshot of a specific version without affecting the working tree.

**Parameters:**
- `version`: Version number to retrieve

**Returns:** ImmutableTree instance for that version

**Example:**
```typescript
const v1 = await tree.getImmutable(1n);
const value = await v1.get(Buffer.from("key"));
```

##### `getVersioned(key: Uint8Array, version: bigint): Promise<Uint8Array | null>`

Retrieves a value for a key at a specific historical version.

**Parameters:**
- `key`: Key to retrieve
- `version`: Version to query

**Returns:** Value at that version, or null if not found

**Example:**
```typescript
const oldValue = await tree.getVersioned(Buffer.from("key"), 3n);
```

##### `rollback(): void`

Discards all uncommitted changes and restores the working tree to the last saved state.

**Example:**
```typescript
await tree.set(Buffer.from("key"), Buffer.from("value"));
tree.rollback(); // Changes discarded
```

---

#### Version Deletion

##### `deleteVersion(version: bigint): Promise<void>`

Deletes a specific version and its orphaned nodes.

**Parameters:**
- `version`: Version to delete (cannot be the latest version)

**Example:**
```typescript
await tree.deleteVersion(1n);
```

##### `deleteVersionsTo(toVersion: bigint): Promise<void>`

Deletes all versions from the first version up to (and including) `toVersion`.

**Parameters:**
- `toVersion`: Delete versions up to and including this version

**Example:**
```typescript
await tree.deleteVersionsTo(5n); // Deletes versions 1-5
```

##### `deleteVersionsFrom(fromVersion: bigint): Promise<void>`

Deletes all versions from `fromVersion` onwards (inclusive).

**Parameters:**
- `fromVersion`: Delete from this version onwards

**Example:**
```typescript
await tree.deleteVersionsFrom(10n); // Deletes versions 10 onwards
```

---

#### Proofs

##### `getVersionedProof(key: Uint8Array, version: bigint): Promise<CommitmentProof>`

Generates a membership or non-membership proof for a key at a specific version.

**Parameters:**
- `key`: Key to prove
- `version`: Version to generate proof for

**Returns:** ICS23 CommitmentProof

**Example:**
```typescript
const proof = await tree.getVersionedProof(Buffer.from("key"), 5n);
```

---

#### Import/Export

##### `import(exporter: AsyncIterableIterator<ExportNode>, version: bigint): Promise<void>`

Imports tree data from an exporter.

**Parameters:**
- `exporter`: Async iterator yielding ExportNode objects
- `version`: Version number to assign to imported tree

**Example:**
```typescript
const exporter = oldTree.getWorkingTree().export();
await newTree.import(exporter, 1n);
```

---

### ImmutableTree

The `ImmutableTree` class provides a read-only view of the tree at a specific version. All ImmutableTree instances are frozen and cannot be modified.

#### Constructor

```typescript
constructor(
  root: Node | null,
  ndb: NodeGetter,
  version: bigint,
  skipFastStorageUpgrade?: boolean,
  logger?: Logger | null
)
```

---

#### Tree State Methods

##### `getVersion(): bigint`

Returns the version of this tree.

##### `getRoot(): Node | null`

Returns the root node of this tree.

##### `isEmpty(): boolean`

Returns true if the tree is empty (no keys).

##### `size(): bigint`

Returns the number of keys in the tree.

##### `height(): number`

Returns the height of the tree.

##### `hash(): Uint8Array | null`

Returns the Merkle root hash of the tree.

---

#### Data Operations

##### `has(key: Uint8Array): Promise<boolean>`

Checks if a key exists in the tree.

**Parameters:**
- `key`: Key to check

**Returns:** `true` if key exists

**Example:**
```typescript
const exists = await immutableTree.has(Buffer.from("key"));
```

##### `get(key: Uint8Array): Promise<Uint8Array | null>`

Retrieves the value for a key.

**Parameters:**
- `key`: Key to retrieve

**Returns:** Value if found, null otherwise

##### `getWithIndex(key: Uint8Array): Promise<{ index: bigint, value: Uint8Array | null }>`

Retrieves the value and index position for a key.

**Parameters:**
- `key`: Key to retrieve

**Returns:** Object with `index` (position in sorted order) and `value`

**Example:**
```typescript
const { index, value } = await tree.getWithIndex(Buffer.from("key"));
console.log(`Key is at position ${index}`);
```

##### `getByIndex(index: bigint): Promise<{ key: Uint8Array, value: Uint8Array } | null>`

Retrieves the key-value pair at a specific index position.

**Parameters:**
- `index`: Index position (0-based)

**Returns:** Object with `key` and `value`, or null if index out of bounds

**Example:**
```typescript
const pair = await tree.getByIndex(0n); // Get first key-value pair
if (pair) {
  console.log(`First key: ${pair.key}`);
}
```

---

#### Iteration

##### `iterator(start?: Uint8Array, end?: Uint8Array): TreeIterator`

Creates an iterator for forward (ascending) iteration.

**Parameters:**
- `start`: Optional start key (inclusive)
- `end`: Optional end key (exclusive)

**Returns:** TreeIterator instance

**Example:**
```typescript
const iter = tree.iterator();
await iter.next(); // Position at first element

while (iter.valid()) {
  console.log(iter.key(), iter.value());
  await iter.next();
}
iter.close();
```

##### `reverseIterator(start?: Uint8Array, end?: Uint8Array): TreeIterator`

Creates an iterator for reverse (descending) iteration.

**Parameters:**
- `start`: Optional start key (inclusive, greater bound)
- `end`: Optional end key (exclusive, lesser bound)

**Returns:** TreeIterator instance

**Example:**
```typescript
const iter = tree.reverseIterator();
await iter.next();
while (iter.valid()) {
  console.log(iter.key(), iter.value());
  await iter.next();
}
iter.close();
```

##### `iterateRange(start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, callback: (key: Uint8Array, value: Uint8Array) => boolean): Promise<void>`

Iterates over a range and calls a callback for each key-value pair.

**Parameters:**
- `start`: Start key (null for beginning)
- `end`: End key (null for end)
- `ascending`: Direction of iteration
- `callback`: Function called for each pair, return false to stop

**Example:**
```typescript
await tree.iterateRange(
  Buffer.from("a"),
  Buffer.from("z"),
  true,
  (key, value) => {
    console.log(key, value);
    return true; // Continue iteration
  }
);
```

---

#### Proofs

##### `getMembershipProof(key: Uint8Array): Promise<CommitmentProof>`

Generates a membership proof for a key that exists in the tree.

**Parameters:**
- `key`: Key to prove (must exist)

**Returns:** ICS23 CommitmentProof

**Throws:** Error if key does not exist

##### `getNonMembershipProof(key: Uint8Array): Promise<CommitmentProof>`

Generates a non-membership proof for a key that does NOT exist in the tree.

**Parameters:**
- `key`: Key to prove absence of (must not exist)

**Returns:** ICS23 CommitmentProof

**Throws:** Error if key exists

##### `getProof(key: Uint8Array): Promise<CommitmentProof>`

Automatically generates either a membership or non-membership proof.

**Parameters:**
- `key`: Key to prove

**Returns:** ICS23 CommitmentProof (membership or non-membership)

##### `verifyMembership(proof: CommitmentProof, key: Uint8Array): Promise<boolean>`

Verifies a membership proof against this tree.

**Parameters:**
- `proof`: CommitmentProof to verify
- `key`: Key being proved

**Returns:** `true` if proof is valid

##### `verifyNonMembership(proof: CommitmentProof, key: Uint8Array): boolean`

Verifies a non-membership proof against this tree.

**Parameters:**
- `proof`: CommitmentProof to verify
- `key`: Key being proved absent

**Returns:** `true` if proof is valid

##### `verifyProof(proof: CommitmentProof, key: Uint8Array): Promise<boolean>`

Automatically verifies either a membership or non-membership proof.

**Parameters:**
- `proof`: CommitmentProof to verify
- `key`: Key being proved

**Returns:** `true` if proof is valid

---

#### Export

##### `export(): Exporter`

Creates an exporter for this tree.

**Returns:** Exporter instance that yields ExportNode objects

**Example:**
```typescript
const exporter = tree.export();
for await (const node of exporter) {
  console.log(node.key, node.value, node.version);
}
```

---

### Node

The `Node` class represents a single node in the AVL tree. Nodes can be either leaf nodes (storing key-value pairs) or branch nodes (internal nodes).

#### Static Methods

##### `newLeafNode(key: Uint8Array, value: Uint8Array, version: bigint): Node`

Creates a new leaf node.

**Parameters:**
- `key`: Key for this leaf
- `value`: Value for this leaf
- `version`: Version when this node was created

##### `newBranchNode(left: Node, right: Node, version: bigint): Node`

Creates a new branch node.

**Parameters:**
- `left`: Left child node
- `right`: Right child node
- `version`: Version when this node was created

##### `fromBytes(nodeKey: Uint8Array, bytes: Uint8Array): Node`

Deserializes a node from bytes.

**Parameters:**
- `nodeKey`: NodeKey identifying this node
- `bytes`: Serialized node data

**Returns:** Deserialized Node

---

#### Properties

- `key: Uint8Array | null` - Key (for leaf nodes) or separator key (for branch nodes)
- `value: Uint8Array | null` - Value (only for leaf nodes)
- `hash: Uint8Array | null` - Cached Merkle hash
- `nodeKey: Uint8Array | null` - Unique identifier (version + nonce)
- `leftNode: Node | null` - Left child (branch nodes only)
- `rightNode: Node | null` - Right child (branch nodes only)
- `size: bigint` - Number of leaves in subtree
- `leftNodeKey: Uint8Array | null` - Reference to left child
- `rightNodeKey: Uint8Array | null` - Reference to right child
- `height: number` - Height of node in tree
- `version: bigint` - Version when node was created

---

#### Methods

##### `isLeaf(): boolean`

Returns true if this is a leaf node.

##### `computeHash(): Uint8Array`

Computes and caches the Merkle hash for this node.

**Returns:** 32-byte hash

##### `toBytes(): Uint8Array`

Serializes the node to bytes.

**Returns:** Serialized node data

##### `validate(): void`

Validates node invariants.

**Throws:** Error if node is invalid

##### `getBalanceFactor(): number`

Returns the balance factor (left height - right height).

**Returns:** Balance factor (-2 to +2 for valid AVL trees)

---

### NodeKey

The `NodeKey` class represents a unique identifier for a node, consisting of a version and a nonce.

#### Constructor

```typescript
constructor(version: bigint, nonce: number)
```

---

#### Static Methods

##### `fromBytes(bytes: Uint8Array): NodeKey`

Deserializes a NodeKey from bytes.

**Parameters:**
- `bytes`: 12-byte NodeKey (8 bytes version + 4 bytes nonce)

**Returns:** NodeKey instance

##### `getRootKey(version: bigint): Uint8Array`

Gets the database key for a root reference.

**Parameters:**
- `version`: Version number

**Returns:** Database key for root

---

#### Methods

##### `toBytes(): Uint8Array`

Serializes the NodeKey to 12 bytes (8 bytes version + 4 bytes nonce, big-endian).

**Returns:** Serialized NodeKey

##### `equals(other: NodeKey): boolean`

Checks equality with another NodeKey.

##### `compare(other: NodeKey): number`

Compares with another NodeKey for ordering.

**Returns:** -1, 0, or 1

---

## Storage Layer

### NodeDB

The `NodeDB` class manages node persistence, caching, and version tracking.

#### Constructor

```typescript
constructor(
  db: Database,
  cacheSize: number,
  opts: Partial<Options>,
  logger?: Logger | null
)
```

**Parameters:**
- `db`: Database instance for persistence
- `cacheSize`: Size of LRU cache for nodes
- `opts`: Configuration options
- `logger`: Optional logger instance

---

#### Initialization

##### `initialize(): Promise<void>`

Initializes the NodeDB by loading metadata from the database. Must be called before use.

**Example:**
```typescript
const ndb = new NodeDB(db, 10000, {});
await ndb.initialize();
```

---

#### Node Operations

##### `getNode(nodeKey: Uint8Array): Promise<Node | null>`

Retrieves a node by its NodeKey.

**Parameters:**
- `nodeKey`: NodeKey to retrieve

**Returns:** Node if found, null otherwise

##### `saveNode(node: Node): Promise<void>`

Persists a node to storage.

**Parameters:**
- `node`: Node to save

---

#### Fast Storage

##### `getFastNode(key: Uint8Array): Promise<FastNode | null>`

Retrieves a FastNode (optimized leaf storage).

**Parameters:**
- `key`: Key to retrieve

**Returns:** FastNode if found, null otherwise

##### `saveFastNode(fastNode: FastNode): Promise<void>`

Saves a FastNode.

**Parameters:**
- `fastNode`: FastNode to save

##### `deleteFastNode(key: Uint8Array): Promise<void>`

Deletes a FastNode.

**Parameters:**
- `key`: Key to delete

##### `getFastIterator(start?: Uint8Array, end?: Uint8Array, ascending?: boolean): FastIterator | null`

Creates a FastIterator over fast storage.

**Parameters:**
- `start`: Optional start key
- `end`: Optional end key
- `ascending`: Direction (default: true)

**Returns:** FastIterator or null if fast storage not available

##### `hasUpgradedToFastStorage(): boolean`

Checks if fast storage is enabled.

**Returns:** `true` if fast storage is available

---

#### Version Management

##### `getFirstVersion(): bigint`

Returns the oldest version available.

##### `getLatestVersion(): bigint`

Returns the newest version available.

##### `getRoot(version: bigint): Promise<Uint8Array | null>`

Gets the root NodeKey for a specific version.

**Parameters:**
- `version`: Version to query

**Returns:** Root NodeKey, or null if version doesn't exist

##### `saveRoot(version: bigint, nodeKey: Uint8Array): Promise<void>`

Saves a root reference for a version.

**Parameters:**
- `version`: Version number
- `nodeKey`: Root node's NodeKey

##### `saveEmptyRoot(version: bigint): Promise<void>`

Saves a marker for an empty tree at a version.

**Parameters:**
- `version`: Version number

##### `deleteVersion(version: bigint): Promise<void>`

Deletes a version and its orphaned nodes.

**Parameters:**
- `version`: Version to delete

##### `deleteVersionsTo(toVersion: bigint): Promise<void>`

Deletes versions from first to `toVersion` (inclusive).

**Parameters:**
- `toVersion`: Delete up to and including this version

##### `deleteVersionsFrom(fromVersion: bigint): Promise<void>`

Deletes versions from `fromVersion` onwards.

**Parameters:**
- `fromVersion`: Delete from this version onwards

---

#### Metadata

##### `getStorageVersion(): string`

Returns the storage format version (e.g., "1.1.0" for fast storage).

##### `getOptions(): Options`

Returns the options used to create this NodeDB.

##### `getStatistics(): Statistics | undefined`

Returns cache hit/miss statistics if enabled.

**Returns:** Statistics object with cache counters

---

#### Cleanup

##### `commit(): Promise<void>`

Commits any pending writes (no-op in current implementation).

##### `close(): Promise<void>`

Closes the NodeDB and releases resources.

---

### FastNode

The `FastNode` class represents an optimized storage format for leaf nodes.

#### Constructor

```typescript
constructor(
  key: Uint8Array,
  value: Uint8Array,
  versionLastUpdatedAt: bigint
)
```

---

#### Static Methods

##### `fromBytes(bytes: Uint8Array): FastNode`

Deserializes a FastNode from bytes.

**Parameters:**
- `bytes`: Serialized FastNode

**Returns:** FastNode instance

---

#### Methods

##### `toBytes(): Uint8Array`

Serializes the FastNode to bytes.

**Returns:** Serialized data

##### `encodedSize(): number`

Calculates the encoded size in bytes.

**Returns:** Size in bytes

---

### Database

The `Database` interface defines the contract for key-value storage backends.

#### Methods

##### `get(key: Uint8Array): Promise<Uint8Array | null>`

Retrieves a value for a key.

##### `has(key: Uint8Array): Promise<boolean>`

Checks if a key exists.

##### `set(key: Uint8Array, value: Uint8Array): Promise<void>`

Sets a key-value pair.

##### `delete(key: Uint8Array): Promise<void>`

Deletes a key.

##### `iterator(start?: Uint8Array, end?: Uint8Array): Iterator`

Creates an iterator over a key range.

##### `reverseIterator(start?: Uint8Array, end?: Uint8Array): Iterator`

Creates a reverse iterator.

##### `batch(): Batch`

Creates a batch for atomic operations.

##### `close(): Promise<void>`

Closes the database.

---

### MemDB

The `MemDB` class provides an in-memory Database implementation for testing.

#### Constructor

```typescript
constructor()
```

**Example:**
```typescript
import { MemDB, NodeDB, MutableTree } from "iavl-ts";

const db = new MemDB();
const ndb = new NodeDB(db, 10000, {});
await ndb.initialize();
const tree = await MutableTree.create(ndb);
```

---

## Iteration

### TreeIterator

The `TreeIterator` class provides in-order traversal of tree nodes.

#### Methods

##### `key(): Uint8Array`

Returns the current key. Only valid when `valid()` is true.

##### `value(): Uint8Array`

Returns the current value. Only valid when `valid()` is true.

##### `valid(): boolean`

Returns true if the iterator is positioned at a valid element.

##### `next(): Promise<void>`

Advances the iterator to the next element.

##### `close(): void`

Releases resources held by the iterator.

##### `domain(): [Uint8Array | null, Uint8Array | null]`

Returns the iteration bounds [start, end].

---

### FastIterator

The `FastIterator` class provides high-performance sequential access using fast storage.

#### Static Methods

##### `create(start: Uint8Array | undefined, ndb: NodeDB, ascending?: boolean): FastIterator`

Creates a FastIterator.

**Parameters:**
- `start`: Optional start key
- `ndb`: NodeDB instance
- `ascending`: Direction (default: true)

**Returns:** FastIterator instance

---

#### Methods

##### `key(): Uint8Array`

Returns the current key.

##### `value(): Uint8Array`

Returns the current value.

##### `valid(): boolean`

Returns true if positioned at a valid element.

##### `next(): void`

Advances to the next element.

##### `close(): void`

Releases iterator resources.

##### `domain(): [Uint8Array | null, Uint8Array | null]`

Returns iteration bounds.

---

## Import/Export

### Exporter

The `Exporter` class exports tree nodes in post-order (LRN) traversal.

#### Constructor

```typescript
constructor(tree: ImmutableTree)
```

---

#### Methods

##### `[Symbol.asyncIterator](): AsyncIterableIterator<ExportNode>`

Yields nodes for export.

**Example:**
```typescript
const exporter = new Exporter(tree);
for await (const node of exporter) {
  console.log(node.key, node.value, node.version, node.height);
}
```

---

### Importer

The `Importer` class imports tree nodes from an exporter.

#### Constructor

```typescript
constructor(tree: MutableTree, version: bigint)
```

---

#### Methods

##### `add(exportNode: ExportNode): Promise<void>`

Adds an exported node to the tree being built.

**Parameters:**
- `exportNode`: Node to import

##### `commit(): Promise<void>`

Finalizes the import and saves the tree.

##### `close(): void`

Releases resources.

**Example:**
```typescript
const importer = new Importer(newTree, 1n);
for await (const node of exporter) {
  await importer.add(node);
}
await importer.commit();
```

---

## Proofs

### Proof Generation

Proofs are generated using ICS23 (Inter-Chain Standards 23) format, which is compatible with Cosmos SDK and CometBFT.

#### Membership Proofs

Generated for keys that exist in the tree:

```typescript
const proof = await tree.getMembershipProof(Buffer.from("key"));
```

#### Non-Membership Proofs

Generated for keys that do NOT exist in the tree:

```typescript
const proof = await tree.getNonMembershipProof(Buffer.from("missing-key"));
```

#### Automatic Proof Selection

```typescript
const proof = await tree.getProof(Buffer.from("key"));
// Automatically generates membership or non-membership proof
```

---

### Proof Verification

Proofs can be verified against a tree's root hash:

```typescript
// Verify membership
const isValid = await tree.verifyMembership(proof, Buffer.from("key"));

// Verify non-membership
const isValid = tree.verifyNonMembership(proof, Buffer.from("missing-key"));

// Automatic verification
const isValid = await tree.verifyProof(proof, Buffer.from("key"));
```

---

## Types & Interfaces

### Options

Configuration options for NodeDB and tree operations.

```typescript
interface Options {
  // Initial version number for new trees (default: 1)
  initialVersion?: bigint;

  // Enable async pruning for background deletion
  asyncPruning?: boolean;

  // Cache statistics tracking
  statistics?: Statistics;

  // Cache size for nodes
  cacheSize?: number;

  // Additional options...
}
```

---

### Statistics

Cache hit/miss statistics.

```typescript
interface Statistics {
  nodeCacheHit: number;      // Node cache hits
  nodeCacheMiss: number;     // Node cache misses
  fastNodeCacheHit: number;  // Fast node cache hits
  fastNodeCacheMiss: number; // Fast node cache misses
}
```

**Example:**
```typescript
const stats = ndb.getStatistics();
if (stats) {
  console.log(`Node cache hit rate: ${stats.nodeCacheHit / (stats.nodeCacheHit + stats.nodeCacheMiss)}`);
}
```

---

### ExportNode

Represents a node during export/import operations.

```typescript
interface ExportNode {
  key: Uint8Array;      // Node key
  value: Uint8Array;    // Node value
  version: bigint;      // Version when created
  height: number;       // Height in tree
}
```

---

## Error Handling

All async methods may throw errors. Common error cases:

- **Version not found**: Loading or deleting non-existent versions
- **Invalid proof**: Generating proofs for wrong existence state
- **Database errors**: Underlying storage failures
- **Tree invariants**: AVL balance violations (should not occur)

**Example:**
```typescript
try {
  await tree.loadVersion(999n);
} catch (error) {
  console.error("Version not found:", error);
}
```

---

## Performance Considerations

### Caching

- **Node cache**: Larger cache (10,000+) improves performance for large trees
- **Fast storage**: Use fast storage for O(1) sequential access
- **Batch operations**: Import/export uses efficient batch processing

### Memory

- **Working set**: Keep recently accessed nodes in cache
- **Immutable trees**: Share node references across versions (copy-on-write)
- **Large values**: Consider storing large values externally and only storing hashes

### Iteration

- **FastIterator**: Use for sequential access (much faster than TreeIterator)
- **Range queries**: Specify bounds to avoid iterating entire tree
- **Close iterators**: Always close iterators to release resources

---

## Thread Safety

**Node.js Environment:**

IAVL-TS is designed for Node.js, which is single-threaded with async I/O. However:

- **Multiple reads**: Safe from different async contexts
- **Concurrent writes**: NOT safe - mutations must be serialized by caller
- **Immutable trees**: Safe to read from multiple contexts simultaneously

**Recommendation:**

Serialize mutations to MutableTree. Multiple ImmutableTree instances can be read concurrently.

---

## TypeScript Types

All classes and methods have full TypeScript type definitions. Enable `strict` mode for maximum type safety:

```typescript
import type { NodeGetter, ExportNode } from "iavl-ts";
import { MutableTree, NodeDB } from "iavl-ts";
```

---

## Migration from Go IAVL

If you're familiar with Go IAVL v1.3.5, here are the key differences:

1. **Async methods**: All I/O methods are async (use `await`)
2. **BigInt**: Version numbers are `bigint` instead of `int64`
3. **Uint8Array**: Keys/values are `Uint8Array` instead of `[]byte`
4. **No concurrency primitives**: Node.js is single-threaded
5. **Promises**: Replace channels/goroutines with async/await

**Go:**
```go
tree.Set([]byte("key"), []byte("value"))
hash, version, err := tree.SaveVersion()
```

**TypeScript:**
```typescript
await tree.set(Buffer.from("key"), Buffer.from("value"));
const { hash, version } = await tree.saveVersion();
```

---

## Additional Resources

- [README.md](./README.md) - Quick start guide
- [IMPLEMENTATION_PLAN.md](./IMPLEMENTATION_PLAN.md) - Implementation details
- [Go IAVL Reference](https://github.com/cosmos/iavl) - Original implementation
- [ICS23 Specification](https://github.com/cosmos/ics23) - Proof format

---

## License

Apache 2.0 - See LICENSE file for details
