### Node.js Setup
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/README.md
Import and initialize Poseidon and Eddsa builders in a Node.js environment.
```javascript
import { buildPoseidon, buildEddsa } from "circomlibjs";
const poseidon = await buildPoseidon();
const eddsa = await buildEddsa();
```
--------------------------------
### Install circomlibjs
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/00-START-HERE.md
Install the circomlibjs library using npm. This is the first step before importing any modules.
```bash
npm install circomlibjs
```
--------------------------------
### Browser Setup
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/README.md
Import and initialize the Poseidon builder in a browser environment using a module script.
```html
```
--------------------------------
### Install circomlibjs Globally
Source: https://github.com/iden3/circomlibjs/blob/main/README.md
Use this command to install the circomlibjs library globally on your system.
```text
npm install -g circomlibjs
```
--------------------------------
### Install circomlibjs
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/index.md
Install the circomlibjs package using npm. It can be installed locally for a project or globally.
```bash
npm install circomlibjs
```
```bash
npm install -g circomlibjs
```
--------------------------------
### Create Uint8Array
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Example of initializing a Uint8Array with byte values.
```javascript
const buf2 = new Uint8Array([1, 2, 3]);
```
--------------------------------
### Field Instance Setup
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/index.md
Shows how to import and initialize a field instance from the ffjavascript library for BN-128 curve operations.
```javascript
import { getCurveFromName } from "ffjavascript";
const bn128 = await getCurveFromName("bn128", true);
const F = bn128.Fr; // Field instance
const Scalar = bn128.r; // Curve order field
```
--------------------------------
### Build EdDSA Instance
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/eddsa.md
Asynchronously initializes and returns an EdDSA instance with all required cryptographic components. Import this function to get started.
```javascript
import buildEddsa from "circomlibjs";
const eddsa = await buildEddsa();
const msg = Buffer.from("hello");
const signature = eddsa.signPedersen(privateKey, msg);
```
--------------------------------
### Async Initialization Example
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/index.md
Demonstrates the asynchronous initialization pattern used for cryptographic objects, allowing for deferred WASM loading and pre-computation.
```javascript
const obj = await buildSomething();
```
--------------------------------
### Example SMT Nodes
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Illustrates the creation of a leaf node and an internal node for a Sparse Merkle Tree using field elements.
```javascript
const leafNode = [F.e(1), F.e(42), F.e(100)];
const internalNode = [F.e(hash1), F.e(hash2)];
```
--------------------------------
### Example: Control Flow with Labels and Jumps
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
Demonstrates defining a label, performing an operation, and then jumping back to the label to create a loop.
```javascript
C.label("loop");
C.push("0x01");
C.add();
C.jmpi("loop");
```
--------------------------------
### Hash Function Examples
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Demonstrates the usage of different hash functions like Poseidon, MiMC-7, and Pedersen, showing their respective return types (Field, Field[], or Uint8Array).
```javascript
const hash1 = poseidon([1, 2, 3]); // Field
const hash2 = poseidon([1, 2, 3], 0, 2); // Field[]
const hash3 = mimc7.hash(x, k); // Field
const hash4 = await pedersenHash.hash(msg); // Uint8Array
```
--------------------------------
### buildBabyJub
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/babyjub.md
Initializes and returns a BabyJub instance configured for the BN-128 elliptic curve. This is the factory function to get started with the BabyJub API.
```APIDOC
## Factory Function: buildBabyJub
### Description
Initializes and returns a BabyJub instance configured for the BN-128 elliptic curve.
### Returns
`Promise` - A promise that resolves to a BabyJub instance.
### Example
```javascript
import buildBabyJub from "circomlibjs";
const babyJub = await buildBabyJub();
const point = babyJub.Generator;
```
```
--------------------------------
### Import Poseidon Contract Functions
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/contract_generation.md
Import the necessary functions for creating Poseidon verification contracts. Use `createCode(nInputs)` to generate contract bytecode and `generateABI(nInputs)` to get the contract's ABI.
```javascript
import * as poseidonContract from "circomlibjs";
// Available:
// - createCode(nInputs)
// - generateABI(nInputs)
```
--------------------------------
### Example: Conditional Jump with mload
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
Illustrates a conditional jump that executes only if the value loaded from memory is non-zero.
```javascript
C.push("0x00");
C.mload();
C.jmpi("non_zero");
```
--------------------------------
### Initialize MiMC-7 Instance
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/mimc7.md
Use the buildMimc7 factory function to get an initialized Mimc7 instance. This is the entry point for using the MiMC-7 hash function.
```javascript
import buildMimc7 from "circomlibjs";
const mimc7 = await buildMimc7();
const hash = mimc7.hash(123, 456);
```
--------------------------------
### Get Account Balance
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
Use `balance()` to get the balance of a given account. Its bytecode is `0x31`.
```javascript
balance()
```
--------------------------------
### Use Pedersen Hash with Custom Options
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Example of using the pedersenHash function with a specified baseHash option.
```javascript
const hash = pedersenHash.hash(msg, { baseHash: "blake2b" });
```
--------------------------------
### Initialize EVM Assembly Builder
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
Creates a new instance of the EVM assembly builder. This is the starting point for constructing EVM bytecode.
```javascript
import Contract from "circomlibjs";
const C = new Contract();
C.push("0x42");
C.mstore();
const bytecode = C.createTxData();
```
--------------------------------
### Type Coercion Examples
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Illustrates functions accepting various input types that are internally coerced.
```javascript
poseidon([1, "0x123", BigInt(456)]);
mimc7.hash(123, "456");
babyJub.addPoint([0, 1], babyJub.Generator);
```
--------------------------------
### Storing a Leaf Node in SMTMemDb
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Example of how to store a leaf node in the SMTMemDb. Keys are converted to strings for storage.
```javascript
const db = new SMTMemDb(F);
const key = F.e(12345);
const keyStr = F.toString(key);
db.nodes[keyStr] = [1, key, value];
```
--------------------------------
### get
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Retrieves a single node by its key hash.
```APIDOC
## get
### Description
Retrieves a single node by its key hash.
### Parameters
#### Path Parameters
- **key** (Field) - Required - Node hash key
### Returns
- **Promise** - Node value or undefined if not found
### Example
```javascript
const node = await db.get(hashKey);
if (node) {
console.log(node); // [type, data, ...]
}
```
```
--------------------------------
### newMemEmptyTrie
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt.md
Convenience function that creates an empty Sparse Merkle Tree with an in-memory database. Useful for quick setup and testing.
```APIDOC
## Factory Function: newMemEmptyTrie
### Description
Convenience function that creates an empty Sparse Merkle Tree with in-memory database.
### Method
async
### Request Example
```javascript
import { newMemEmptyTrie } from "circomlibjs";
const smt = await newMemEmptyTrie();
await smt.insert(key, value);
```
```
--------------------------------
### Deploying Generated Contract Bytecode
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/contract_generation.md
Use this JavaScript snippet to deploy generated contract bytecode to an Ethereum-compatible blockchain. Ensure you have circomlibjs and ethers.js installed and configured.
```javascript
import { createCode, generateABI } from "circomlibjs";
import { ethers } from "ethers";
const bytecode = createCode(2);
const abi = generateABI(2);
const signer = ...;
const factory = new ethers.ContractFactory(abi, bytecode, signer);
const contract = await factory.deploy();
await contract.deployed();
```
--------------------------------
### Initialize BabyJub Instance
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/babyjub.md
Use this function to get an instance of the BabyJub curve. It returns a Promise that resolves to the BabyJub object.
```javascript
import buildBabyJub from "circomlibjs";
const babyJub = await buildBabyJub();
const point = babyJub.Generator;
```
--------------------------------
### Get SMT Root
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Retrieves the current root hash of the Sparse Merkle Tree. Assumes the database has been initialized.
```javascript
const db = new SMTMemDb(F);
const root = await db.getRoot();
```
--------------------------------
### Hash Function Common Methods
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/api_overview.md
Illustrates the common methods available across different hash functions for hashing inputs, performing multi-hashes, retrieving constants, and getting initialization vectors. The `hash` method supports stateful hashing, while `multiHash` allows hashing arrays.
```javascript
// Hash with state
hash(input, initState?, nOut?)
```
```javascript
// Multi-hash from array
multiHash(array, key?, numOutputs?)
```
```javascript
// Constants
getConstants(seed?, nRounds?)
```
```javascript
// Initialization vector
getIV(seed?)
```
--------------------------------
### Sparse Merkle Tree Database Interface
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt.md
Defines the asynchronous interface required for the database used by the Sparse Merkle Tree. This includes methods for getting and setting nodes and the root, as well as for bulk insertion and deletion.
```javascript
{
// Get node by hash
async get(key) -> Array or undefined
// Get multiple nodes
async multiGet(keys) -> Array
// Set root
async setRoot(root) -> void
// Get current root
async getRoot() -> Field
// Insert multiple [key, value] pairs
async multiIns(inserts) -> void
// Delete multiple keys
async multiDel(dels) -> void
}
```
--------------------------------
### Integrating SMTMemDb with SMT Operations
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Demonstrates how to initialize SMTMemDb and use it as a backend for building and interacting with an SMT, including inserting key-value pairs.
```javascript
import { buildSMT } from "circomlibjs";
import SMTMemDb from "circomlibjs";
const db = new SMTMemDb(F);
const smt = await buildSMT(db, F.zero);
await smt.insert(key, value);
```
--------------------------------
### buildPoseidonOpt
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/poseidon.md
Optimized JavaScript implementation using pre-computed matrices. Faster than reference but slower than WASM.
```APIDOC
## Factory Function: buildPoseidonOpt
### Description
Optimized JavaScript implementation using pre-computed matrices. Faster than reference but slower than WASM.
### Returns
`Promise`
### Example
```javascript
import buildPoseidonOpt from "circomlibjs";
const poseidon = await buildPoseidonOpt();
const hash = poseidon([1, 2, 3]);
```
```
--------------------------------
### Get Message Caller
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
Use `caller()` to retrieve the address of the message sender. Its bytecode is `0x33`.
```javascript
caller()
```
--------------------------------
### SMTMemDb Constructor
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Initializes an in-memory database backend for SMT operations.
```APIDOC
## Constructor SMTMemDb
### Description
Initializes an in-memory database backend for SMT operations.
### Parameters
#### Path Parameters
- **F** (Field) - Required - Field instance for operations
### Request Example
```javascript
import SMTMemDb from "circomlibjs";
import { getCurveFromName } from "ffjavascript";
const bn128 = await getCurveFromName("bn128", true);
const db = new SMTMemDb(bn128.Fr);
```
```
--------------------------------
### Database Get Single Node
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/api_overview.md
Retrieves a single node from the database using its hash. This operation is asynchronous.
```javascript
// Database
node = await db.get(hash)
```
--------------------------------
### Build SMT Instance with Database and Root
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt.md
Use `buildSMT` to create a Sparse Merkle Tree instance, providing a database and the current root hash. Initialize with `F.zero` for an empty tree.
```javascript
import { buildSMT, SMTMemDb } from "circomlibjs";
const db = new SMTMemDb(F);
const smt = await buildSMT(db, F.zero);
```
--------------------------------
### Get Transaction Origin
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
The `origin()` opcode returns the address of the transaction's originator. Its bytecode is `0x32`.
```javascript
origin()
```
--------------------------------
### Build and Use Poseidon Hash Function
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/poseidon.md
Demonstrates basic usage of the Poseidon hash function, including hashing single and multiple values, using an initial state, and obtaining multiple outputs. Also shows how to use Uint8Array inputs with the WASM implementation.
```javascript
import { buildPoseidon } from "circomlibjs";
const poseidon = await buildPoseidon();
// Basic usage
const hash1 = poseidon([42]);
const hash2 = poseidon([1, 2, 3]);
// With initial state
const hash3 = poseidon([1, 2], F.e(99));
// Multiple outputs
const [out1, out2] = poseidon([1, 2, 3], 0, 2);
// With Uint8Array input (WASM only)
const buffer = new Uint8Array(64); // 2 field elements
const hash4 = poseidon(buffer);
```
--------------------------------
### Generate Poseidon Contract Bytecode and ABI
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/00-START-HERE.md
Demonstrates how to generate the bytecode and ABI for a Poseidon hash verification contract.
```javascript
import { poseidonContract } from "circomlibjs";
const bytecode = poseidonContract.createCode(2);
const abi = poseidonContract.generateABI(2);
// Deploy to Ethereum...
```
--------------------------------
### Get Merkle Tree Root
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/api_overview.md
Retrieves the current root hash of the Merkle Tree database. This operation is asynchronous.
```javascript
// Root management
root = await db.getRoot()
```
--------------------------------
### Get Call Value
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
The `callvalue()` opcode returns the amount of Ether sent with the call in Wei. Its bytecode is `0x34`.
```javascript
callvalue()
```
--------------------------------
### Get Current Contract Address
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
The `address()` opcode retrieves the current contract's address. Its bytecode is `0x30`.
```javascript
address()
```
--------------------------------
### Create Node.js Buffer
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Demonstrates creating a Buffer object from a string in Node.js.
```javascript
const buf1 = Buffer.from("hello");
```
--------------------------------
### Build Pedersen Hash Instance
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/pedersen_hash.md
Initializes and returns a PedersenHash instance. This is the entry point for using the Pedersen hash functionality.
```javascript
import buildPedersenHash from "circomlibjs";
const pedersenHash = await buildPedersenHash();
const msg = Buffer.from("hello");
const hash = pedersenHash.hash(msg);
```
--------------------------------
### Compute Poseidon Hashes
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/00-START-HERE.md
Shows how to build a Poseidon hash instance and compute hashes of arrays of numbers. Supports single or multiple outputs.
```javascript
import { buildPoseidon } from "circomlibjs";
const poseidon = await buildPoseidon();
const hash = poseidon([1, 2, 3]);
const [h1, h2] = poseidon([1, 2], 0, 2); // Multiple outputs
```
--------------------------------
### Sparse Merkle Tree Operations
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/00-START-HERE.md
Illustrates building a Sparse Merkle Tree with an in-memory database, inserting a key-value pair, and generating a proof for a key.
```javascript
import { buildSMT, SMTMemDb } from "circomlibjs";
const db = new SMTMemDb(F);
const smt = await buildSMT(db, F.zero);
await smt.insert(key, value);
const proof = await smt.find(key);
```
--------------------------------
### getIV
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/mimcsponge.md
Generates an initialization vector from a seed string using Keccak-256.
```APIDOC
## Method: getIV
### Description
Generates an initialization vector from a seed string using Keccak-256.
### Parameters
* **seed** (string) - Optional - "mimcsponge" - Seed for IV generation
### Returns
`Field` - Initialization vector as field element
### Algorithm
Keccak-256(seed + "_iv") mod p
### Example
```javascript
const mimcSponge = await buildMimcSponge();
const iv = mimcSponge.getIV("custom_seed");
```
```
--------------------------------
### Initialize SMTMemDb
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Instantiates an SMTMemDb with a Field instance. Required for all SMT operations.
```javascript
import SMTMemDb from "circomlibjs";
import { getCurveFromName } from "ffjavascript";
const bn128 = await getCurveFromName("bn128", true);
const db = new SMTMemDb(bn128.Fr);
```
--------------------------------
### Mimc7 Hash Function
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/api_overview.md
Implements the MiMC-7 hash function, providing methods to get initialization vectors, constants, and to compute hashes.
```APIDOC
## Mimc7
### Description
Implements the MiMC-7 hash function.
### Methods
- **getIV**(seed?)
- **getConstants**(seed?, nRounds?)
- **hash**(input, initState?)
- **multiHash**(array, key?)
```
--------------------------------
### Data Structures
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/_COMPLETION_SUMMARY.txt
Documentation for Sparse Merkle Tree (SMT) and its in-memory database backend.
```APIDOC
## Data Structures
This section details the Sparse Merkle Tree (SMT) implementation and its associated database backends.
### Sparse Merkle Tree (`smt.md`)
Provides functionalities for building and querying Sparse Merkle Trees.
#### Functions
- **buildSMT(db)**: Factory function to create an SMT instance with a specified database backend.
#### Class: `SMT`
Represents a Sparse Merkle Tree.
- **insert(key, value)**: Inserts or updates a key-value pair in the SMT.
- **remove(key)**: Removes a key from the SMT.
- **get(key)**: Retrieves the value associated with a key.
- **root()**: Returns the current root hash of the SMT.
### In-Memory Database (`smt_memdb.md`)
An in-memory database backend for the SMT.
#### Functions
- **newMemEmptyTrie()**: Creates a new, empty in-memory database for SMT.
#### Class: `SMTMemDb`
Implements the database interface for SMT using memory.
- **put(key, value)**: Stores a key-value pair.
- **get(key)**: Retrieves a value by key.
- **del(key)**: Deletes a key-value pair.
- **copy()**: Creates a copy of the database.
- **close()**: Closes the database connection (no-op for in-memory).
```
--------------------------------
### Get Single Node
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Retrieves a specific node from the database using its hash key. Returns the node data or undefined if not found.
```javascript
const node = await db.get(hashKey);
if (node) {
console.log(node); // [type, data, ...]
}
```
--------------------------------
### Hash Functions
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/_COMPLETION_SUMMARY.txt
Documentation for various hash functions including Poseidon, MiMC-7, MiMC-Sponge, and Pedersen.
```APIDOC
## Hash Functions
This section covers the different hash functions implemented in circomlibjs.
### Poseidon Hash (`poseidon.md`)
Implements the Poseidon hash function with WASM and JavaScript variants.
#### Functions
- **buildPoseidon(options)**: Factory function to create a Poseidon hash instance.
#### Class: `Poseidon`
Provides methods for hashing.
- **hash(inputs)**: Computes the Poseidon hash of the given inputs.
- **hash2(inputs)**: Computes a two-output Poseidon hash.
- **hashN(inputs)**: Computes a Poseidon hash for a variable number of inputs.
### MiMC-7 Hash (`mimc7.md`)
Implements the 91-round MiMC-7 hash function.
#### Functions
- **buildMimc7(options)**: Factory function to create a MiMC-7 hash instance.
#### Class: `Mimc7`
Provides methods for hashing.
- **hash(inputs)**: Computes the MiMC-7 hash.
### MiMC-Sponge Hash (`mimcsponge.md`)
Implements the 220-round MiMC-Sponge hash function.
#### Functions
- **buildMimcSponge(options)**: Factory function to create a MiMC-Sponge hash instance.
#### Class: `MimcSponge`
Provides methods for hashing.
- **hash(inputs)**: Computes the MiMC-Sponge hash.
### Pedersen Hash (`pedersen_hash.md`)
Implements the Pedersen hash function based on the Baby Jubjub curve.
#### Functions
- **buildPedersenHash(options)**: Factory function to create a Pedersen hash instance.
#### Class: `PedersenHash`
Provides methods for hashing.
- **hash(inputs)**: Computes the Pedersen hash.
- **hash2(inputs)**: Computes a two-output Pedersen hash.
- **commit(inputs)**: Computes a commitment using the Pedersen hash.
- **commit2(inputs)**: Computes a two-output commitment.
```
--------------------------------
### Find Key and Generate Proof in SMT
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt.md
The `find` method searches for a key in the SMT and returns whether it was found, its value if present, and the proof path (siblings). It can also prove non-existence.
```javascript
const smt = await newMemEmptyTrie();
await smt.insert(42, 100);
const result = await smt.find(42);
console.log(result.found); // true
console.log(result.foundValue); // 100
console.log(result.siblings); // Proof path
const result2 = await smt.find(99);
console.log(result2.found); // false
```
--------------------------------
### MiMC-7 Contract ABI
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/contract_generation.md
Provides the standard Solidity ABI for the MiMC-7 hash function. Access the ABI array to get function details.
```javascript
const { abi } = mimc7Contract;
console.log(abi[0].name); // "MiMCpe7"
```
--------------------------------
### Initialize Cryptographic Components
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/index.md
Initialize various cryptographic components like babyJub, eddsa, and poseidon. These are essential for cryptographic operations within ZK applications.
```javascript
import {
buildBabyjub,
buildEddsa,
buildPoseidon,
buildMimc7,
buildMimcSponge,
buildPedersenHash,
buildSMT,
SMTMemDb
} from "circomlibjs";
// Initialize cryptographic components
const babyJub = await buildBabyjub();
const eddsa = await buildEddsa();
const poseidon = await buildPoseidon();
```
--------------------------------
### Import MiMC-7 Contract Functions
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/contract_generation.md
Import the necessary functions for creating MiMC-7 verification contracts. Use `createCode(seed, n)` to generate contract bytecode and `abi` for the contract's ABI.
```javascript
import * as mimc7Contract from "circomlibjs";
// Available:
// - createCode(seed, n)
// - abi
```
--------------------------------
### Get Multiple Nodes
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt_memdb.md
Retrieves multiple nodes in parallel by providing an array of their keys. Returns an array of node values, with undefined for any missing nodes.
```javascript
const nodes = await db.multiGet([key1, key2, key3]);
```
--------------------------------
### Get Pedersen Base Point
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/pedersen_hash.md
Derives a base point for a given segment index using specified hash types. Points are cached for reuse.
```javascript
const pedersenHash = await buildPedersenHash();
const base0 = pedersenHash.getBasePoint("blake", 0);
const base1 = pedersenHash.getBasePoint("blake", 1);
```
--------------------------------
### Field Element Creation
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Demonstrates how to create field elements using a field instance (F) from various input types like numbers, hex strings, and BigInts.
```javascript
const F = /* field instance */;
const e1 = F.e(123); // number
const e2 = F.e("0x456"); // hex string
const e3 = F.e(BigInt(789)); // bigint
```
--------------------------------
### Generate EdDSA Signature
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/00-START-HERE.md
Demonstrates how to build an EdDSA instance, generate a public key from a private key, sign a message using Poseidon hash, and verify the signature.
```javascript
import { buildEddsa } from "circomlibjs";
const eddsa = await buildEddsa();
const prv = Buffer.from("0123..."); // 32 bytes
const msg = Buffer.from("hello");
const pub = eddsa.prv2pub(prv);
const sig = eddsa.signPoseidon(prv, msg);
const valid = eddsa.verifyPoseidon(msg, sig, pub);
```
--------------------------------
### Import MiMC-Sponge Contract Functions
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/contract_generation.md
Import the necessary functions for creating MiMC-Sponge verification contracts. Use `createCode(seed, n)` to generate contract bytecode and `abi` for the contract's ABI. Note the export name typo: `mimcSpongecontract`.
```javascript
import * as mimcSpongecontract from "circomlibjs";
// Available:
// - createCode(seed, n)
// - abi
```
--------------------------------
### Code Size and Copy Operations
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
These opcodes relate to the contract's code: `codesize()` gets the code size (0x38), and `codecopy()` copies code (0x39).
```javascript
codesize() // Get code size (0x38)
codecopy() // Copy code (0x39)
```
--------------------------------
### buildMimcSponge
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/mimcsponge.md
Initializes and returns a MimcSponge instance with pre-computed 220 round constants.
```APIDOC
## Function: buildMimcSponge
### Description
Initializes and returns a MimcSponge instance with pre-computed 220 round constants.
### Returns
`Promise` - A promise that resolves to a MimcSponge instance.
### Example
```javascript
import buildMimcSponge from "circomlibjs";
const mimcSponge = await buildMimcSponge();
const hash = mimcSponge.multiHash([1, 2, 3]);
```
```
--------------------------------
### Calldata Operations
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
These opcodes handle calldata: `calldataload()` loads from calldata (0x35), `calldatasize()` gets calldata size (0x36), and `calldatacopy()` copies calldata (0x37).
```javascript
calldataload() // Load calldata (0x35)
calldatasize() // Get calldata size (0x36)
calldatacopy() // Copy calldata (0x37)
```
--------------------------------
### Manage Sparse Merkle Trees
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/index.md
Implement and manage Sparse Merkle Trees (SMT). This includes creating an empty tree, inserting values, retrieving values with proofs, and deleting entries.
```javascript
// Create empty tree
const F = /* field instance */;
const db = new SMTMemDb(F);
const smt = await buildSMT(db, F.zero);
// Insert values
const result = await smt.insert(key, value);
console.log(result.newRoot);
// Find values
const found = await smt.find(key);
if (found.found) {
console.log("Value:", found.foundValue);
console.log("Proof siblings:", found.siblings);
}
// Delete values
await smt.delete(key);
```
--------------------------------
### buildPoseidon (WASM)
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/poseidon.md
Initializes and returns the WASM-optimized Poseidon hash function. This is the recommended implementation for production use.
```APIDOC
## Factory Function: buildPoseidon (WASM)
### Description
Initializes and returns the WASM-optimized Poseidon hash function. This is the recommended implementation for production use.
### Returns
`Promise`
### Example
```javascript
import { buildPoseidon } from "circomlibjs";
const poseidon = await buildPoseidon();
const hash = poseidon([1, 2, 3]);
```
```
--------------------------------
### buildSMT
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt.md
Creates and returns a Sparse Merkle Tree instance with a provided database and root. This is a factory function for initializing an SMT.
```APIDOC
## Factory Function: buildSMT
### Description
Creates and returns a Sparse Merkle Tree instance with provided database and root.
### Method
async
### Parameters
#### Path Parameters
- **db** (Object) - Required - Database implementing SMT interface
- **root** (Field/number/bigint) - Required - Current tree root (or F.zero for empty)
### Request Example
```javascript
import { buildSMT, SMTMemDb } from "circomlibjs";
const db = new SMTMemDb(F);
const smt = await buildSMT(db, F.zero);
```
```
--------------------------------
### buildPoseidonReference
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/poseidon.md
Pure JavaScript implementation of Poseidon. Slower than WASM but useful for environments where WASM is unavailable.
```APIDOC
## Factory Function: buildPoseidonReference
### Description
Pure JavaScript implementation of Poseidon. Slower than WASM but useful for environments where WASM is unavailable.
### Returns
`Promise`
### Example
```javascript
import buildPoseidonReference from "circomlibjs";
const poseidon = await buildPoseidonReference();
const hash = poseidon([1, 2, 3]);
```
```
--------------------------------
### Build MiMC-Sponge Instance
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/mimcsponge.md
Initializes and returns a MimcSponge instance with pre-computed round constants. This is the entry point for using the MiMC-Sponge hash functionality.
```javascript
import buildMimcSponge from "circomlibjs";
const mimcSponge = await buildMimcSponge();
const hash = mimcSponge.multiHash([1, 2, 3]);
```
--------------------------------
### Contract Constructor
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
Creates a new EVM assembly builder instance. It initializes properties for tracking bytecode, labels, and pending label references.
```APIDOC
## Class: Contract
Main class for building EVM bytecode.
### Constructor
```javascript
constructor()
```
Creates a new EVM assembly builder.
**Properties**:
- `code` — Array of bytecode bytes
- `labels` — Object mapping label names to bytecode offsets
- `pendingLabels` — Object tracking unresolved label references
**Example**:
```javascript
import Contract from "circomlibjs";
const C = new Contract();
C.push("0x42");
C.mstore();
const bytecode = C.createTxData();
```
```
--------------------------------
### Handle Library Errors
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/README.md
Demonstrates how to catch and log errors thrown by the library. Ensure to handle potential exceptions when using functions like createCode.
```javascript
try {
const code = createCode(20); // Invalid: must be 1-8
} catch (e) {
console.error(e.message);
// "Invalid number of inputs. Must be 1<=nInputs<=8"
}
```
--------------------------------
### Convert Between Buffer Types
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Shows how to convert a Uint8Array to a Node.js Buffer.
```javascript
const buf3 = Buffer.from(buf2);
```
--------------------------------
### Generate Initialization Vector (IV)
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/mimc7.md
Generates an initialization vector from a seed string using Keccak-256. Useful for setting up the hash state with a custom seed.
```javascript
const mimc7 = await buildMimc7();
const iv = mimc7.getIV("custom_seed");
```
--------------------------------
### Memory Write and Read
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/evmasm.md
Demonstrates storing a value to memory at a specific offset and then reading it back.
```javascript
C.push(value);
C.push(offset);
C.mstore(); // Store value at offset
C.push(offset);
C.mload(); // Load value from offset
```
--------------------------------
### buildMimc7
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/mimc7.md
Factory function to initialize and return a Mimc7 instance. This instance is pre-configured with round constants and ready for hashing operations.
```APIDOC
## Function: buildMimc7
### Description
Initializes and returns a Mimc7 instance with pre-computed round constants.
### Signature
```javascript
export default async function buildMimc7()
```
### Returns
- `Promise`: A promise that resolves to a Mimc7 instance.
### Example
```javascript
import buildMimc7 from "circomlibjs";
const mimc7 = await buildMimc7();
const hash = mimc7.hash(123, 456);
```
```
--------------------------------
### Create New In-Memory Empty Trie
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt.md
The `newMemEmptyTrie` function is a convenience wrapper to quickly create an SMT instance with an in-memory database, ready for operations.
```javascript
import { newMemEmptyTrie } from "circomlibjs";
const smt = await newMemEmptyTrie();
await smt.insert(key, value);
```
--------------------------------
### Perform Hashing Operations
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/index.md
Perform various hashing operations using different algorithms like Poseidon (recommended for ZK), MiMC-7, and Pedersen hash. Supports single and multiple outputs for Poseidon.
```javascript
// Poseidon hash (recommended for ZK)
const hash1 = poseidon([1, 2, 3]);
const [h1, h2] = poseidon([1, 2, 3], 0, 2); // Multiple outputs
// MiMC-7 hash
const hash2 = mimc7.hash(42, 0);
const hash3 = mimc7.multiHash([1, 2, 3]);
// Pedersen hash
const msg = Buffer.from("data");
const hash4 = pedersenHash.hash(msg);
```
--------------------------------
### SMTMemDb Methods
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/api_overview.md
Provides memory database functionalities for Sparse Merkle Trees (SMT), including root management, data retrieval, and batch operations.
```APIDOC
## SMTMemDb
### Description
Provides memory database functionalities for Sparse Merkle Trees (SMT).
### Methods
- **getRoot**()
- **setRoot**(root)
- **get**(key)
- **multiGet**(keys)
- **multiIns**(entries)
- **multiDel**(keys)
```
--------------------------------
### Initialize WASM Poseidon Hash Function
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/poseidon.md
Use this function to initialize the WASM-optimized Poseidon hash function. It returns a Promise that resolves to the hash function. Recommended for production.
```javascript
import { buildPoseidon } from "circomlibjs";
const poseidon = await buildPoseidon();
const hash = poseidon([1, 2, 3]);
```
--------------------------------
### Smart Contract Generation
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/_COMPLETION_SUMMARY.txt
Tools for generating EVM bytecode and low-level EVM assembly.
```APIDOC
## Smart Contract Generation (`contract_generation.md`, `evmasm.md`)
This module provides utilities for generating EVM bytecode and low-level assembly, useful for creating smart contracts programmatically.
### EVM Bytecode Generation (`contract_generation.md`)
- **Contract**: A class representing an EVM contract, with over 100 operations for building bytecode.
### Low-level EVM Assembly (`evmasm.md`)
Provides low-level access to EVM assembly instructions for fine-grained control over contract logic.
```
--------------------------------
### Async Factory Pattern for Cryptographic Objects
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/types.md
Illustrates the use of async factories to create cryptographic objects like BabyJub, Mimc7, Eddsa, and SMT. This pattern enables deferred initialization of cryptographic parameters.
```javascript
type Factory = () => Promise;
const babyJub = await buildBabyJub(); // Async
const mimc7 = await buildMimc7();
const eddsa = await buildEddsa();
const smt = await buildSMT(db, root);
```
--------------------------------
### Mimc7.getIV
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/mimc7.md
Generates an initialization vector (IV) from a seed string using Keccak-256. This IV can be used to initialize hashing states.
```APIDOC
## Method: getIV
### Description
Generates an initialization vector from a seed string using Keccak-256.
### Signature
```javascript
getIV(seed)
```
### Parameters
#### Query Parameters
- **seed** (string) - Optional - Default: "mimc" - Seed for IV generation
### Returns
- `Field`: Initialization vector as a field element.
### Algorithm
Keccak-256(seed + "_iv") mod p
### Example
```javascript
const mimc7 = await buildMimc7();
const iv = mimc7.getIV("custom_seed");
```
```
--------------------------------
### buildEddsa
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/eddsa.md
Factory function to asynchronously initialize and return an EdDSA instance with all required cryptographic components.
```APIDOC
## Function: buildEddsa
### Description
Asynchronously initializes and returns an EdDSA instance with all required cryptographic components.
### Returns
`Promise` - An instance of the Eddsa class.
### Example
```javascript
import buildEddsa from "circomlibjs";
const eddsa = await buildEddsa();
const msg = Buffer.from("hello");
const signature = eddsa.signPedersen(privateKey, msg);
```
```
--------------------------------
### Sparse Merkle Tree Proof Generation
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/api_overview.md
Generates a proof for a given key in the Sparse Merkle Tree. This operation is asynchronous.
```javascript
// Proof generation
proof = await smt.find(key)
```
--------------------------------
### Deploy Poseidon Contract
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/contract_generation.md
Generates and deploys a Poseidon hash contract. Requires a signer object from ethers.js. The number of inputs for the Poseidon hash can be specified.
```javascript
import { createCode, generateABI } from "circomlibjs";
import { Contract, ContractFactory, ethers } from "ethers";
async function deployPoseidon(signer, nInputs = 2) {
const bytecode = createCode(nInputs);
const abi = generateABI(nInputs);
const factory = new ContractFactory(abi, bytecode, signer);
const poseidon = await factory.deploy();
return {
address: poseidon.address,
contract: poseidon,
nInputs
};
}
// Usage
const { provider } = ethers.getDefaultProvider();
const signer = new ethers.Wallet(privateKey, provider);
const { address } = await deployPoseidon(signer, 2);
console.log("Deployed at:", address);
```
--------------------------------
### Run Mocha Test Suite
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/api_overview.md
Execute the unit and integration tests for the circomlibjs library using npm and the mocha test runner.
```bash
npm test # Run mocha test suite
```
--------------------------------
### SMT.find
Source: https://github.com/iden3/circomlibjs/blob/main/_autodocs/smt.md
Searches for a key within the Sparse Merkle Tree and returns a proof of its existence or non-existence, along with the found value if applicable.
```APIDOC
## Method: find
### Description
Searches for a key in the tree and returns proof of existence or non-existence.
### Method
async
### Parameters
#### Path Parameters
- **_key** (Field/number/bigint) - Required - 256-bit key to search
### Returns
Promise