Skip to main content
Version: next

Class: Synchronizer

The synchronizer is used to construct the Unirep state. After events are emitted from the Unirep contract, the synchronizer will verify the events and then save the states.

Example

import { Synchronizer } from '@unirep/core'

const state = new Synchronizer({
unirepAddress: '0xaabbccaabbccaabbccaabbccaabbccaabbccaaaa',
provider, // an ethers.js provider
})

// start the synchronizer deamon
await state.start()
await state.waitForSync()

// stop the synchronizer deamon
state.stop()

Hierarchy​

  • EventEmitter

    ↳ Synchronizer

Constructors​

constructor​

• new Synchronizer(config)

Parameters​

NameType
configObject
config.attesterId?bigint | bigint[]
config.db?DB
config.genesisBlock?number
config.providerProvider
config.unirepAddressstring

Overrides​

EventEmitter.constructor

Defined in​

packages/core/src/Synchronizer.ts:168

Properties​

_attesterId​

• Private _attesterId: bigint[] = []

The array of attester IDs which are synchronized in the synchronizer.

Defined in​

packages/core/src/Synchronizer.ts:79


_attesterSettings​

• Private _attesterSettings: Object = {}

The settings of attesters. There are startTimestamp and epochLength of each attester.

Index signature​

▪ [key: string]: AttesterSetting

Defined in​

packages/core/src/Synchronizer.ts:89


_blockEnd​

• Private _blockEnd: Number = 0

The latest completed block number.

Defined in​

packages/core/src/Synchronizer.ts:166


_blocks​

• Private _blocks: any[] = []

Unprocessed events.

Defined in​

packages/core/src/Synchronizer.ts:161


_db​

• Private _db: DB

The database object.

Defined in​

packages/core/src/Synchronizer.ts:64


_eventFilters​

• Private _eventFilters: any

The mapping of a contract address and its event filters.

Defined in​

packages/core/src/Synchronizer.ts:115


_eventHandlers​

• Private _eventHandlers: any

The mapping of the event name and its handler

Defined in​

packages/core/src/Synchronizer.ts:110


_genesisBlock​

• Private _genesisBlock: number = 0

Allow passing the genesis block as the starting block for querying events

Defined in​

packages/core/src/Synchronizer.ts:133


_provider​

• Private _provider: Provider

The provider which is connected in the synchronizer.

Defined in​

packages/core/src/Synchronizer.ts:69


_settings​

• Private _settings: any

The circuits settings.

Defined in​

packages/core/src/Synchronizer.ts:84


_syncAll​

• Private _syncAll: boolean = false

Indicates if the synchronizer is to sync with all Unirep attesters.

Defined in​

packages/core/src/Synchronizer.ts:104


_unirepContract​

• Private _unirepContract: Contract

The UniRep smart contract object which is connected in the synchronizer.

Defined in​

packages/core/src/Synchronizer.ts:74


blockRate​

• blockRate: number = 10000

How many blocks the synchronizer will query on each poll. Default: 100000

Defined in​

packages/core/src/Synchronizer.ts:129


defaultEpochTreeLeaf​

• Protected defaultEpochTreeLeaf: bigint

The default zero epoch tree leaf.

Defined in​

packages/core/src/Synchronizer.ts:99


defaultStateTreeLeaf​

• Protected defaultStateTreeLeaf: bigint

The default zero state tree leaf.

Defined in​

packages/core/src/Synchronizer.ts:94


lock​

• Private lock: any

Lock on poll event.

Defined in​

packages/core/src/Synchronizer.ts:150


pollId​

• Private pollId: null | string = null

The id of the poll event.

Defined in​

packages/core/src/Synchronizer.ts:121


pollRate​

• pollRate: number = 5000

How frequently the synchronizer will poll the blockchain for new events (specified in milliseconds). Default: 5000

Defined in​

packages/core/src/Synchronizer.ts:125


promises​

• Private promises: any[] = []

Load events promises.

Defined in​

packages/core/src/Synchronizer.ts:156


setupComplete​

• Private setupComplete: boolean = false

Check if a setup is completed or not.

Defined in​

packages/core/src/Synchronizer.ts:139


setupPromise​

• Private setupPromise: any

If a setup is not completed, there will be a setup promise.

Defined in​

packages/core/src/Synchronizer.ts:144


captureRejectionSymbol​

▪ Static Readonly captureRejectionSymbol: typeof captureRejectionSymbol

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.

Since

v13.4.0, v12.16.0

Inherited from​

EventEmitter.captureRejectionSymbol

Defined in​

node_modules/@types/node/events.d.ts:402


captureRejections​

▪ Static captureRejections: boolean

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.

Since

v13.4.0, v12.16.0

Inherited from​

EventEmitter.captureRejections

Defined in​

node_modules/@types/node/events.d.ts:409


defaultMaxListeners​

▪ Static defaultMaxListeners: number

By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual EventEmitter instances using the emitter.setMaxListeners(n) method. To change the default for allEventEmitter instances, the events.defaultMaxListenersproperty can be used. If this value is not a positive number, a RangeErroris thrown.

Take caution when setting the events.defaultMaxListeners because the change affects allEventEmitter instances, including those created before the change is made. However, calling emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners.

This is not a hard limit. The EventEmitter instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any singleEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()methods can be used to temporarily avoid this warning:

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});

The --trace-warnings command-line flag can be used to display the stack trace for such warnings.

The emitted warning can be inspected with process.on('warning') and will have the additional emitter, type, and count properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Its name property is set to 'MaxListenersExceededWarning'.

Since

v0.11.2

Inherited from​

EventEmitter.defaultMaxListeners

Defined in​

node_modules/@types/node/events.d.ts:446


errorMonitor​

▪ Static Readonly errorMonitor: typeof errorMonitor

This symbol shall be used to install a listener for only monitoring 'error'events. Listeners installed using this symbol are called before the regular'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an'error' event is emitted. Therefore, the process will still crash if no regular 'error' listener is installed.

Since

v13.6.0, v12.17.0

Inherited from​

EventEmitter.errorMonitor

Defined in​

node_modules/@types/node/events.d.ts:395

Accessors​

attesterId​

• get attesterId(): bigint

The default attester ID that is set when constructed. If there is a list of attester IDs, then the first one will be the default attester ID. If no attester ID is given during construction, all attesters will be synchronized and the default attesterId will be BigInt(0).

caution

The default attester ID should be checked carefully while synchronizing more than one attester. The default attester ID can be changed with setAttesterId.

Returns​

bigint

Defined in​

packages/core/src/Synchronizer.ts:331


attestersOrClauses​

• get attestersOrClauses(): any[]

Returns​

any[]

Defined in​

packages/core/src/Synchronizer.ts:336


contracts​

• get contracts(): Object

Overwrite this to query events in different attester addresses.

Returns​

Object

Example

export class AppSynchronizer extends Synchronizer {
...
get contracts(){
return {
...super.contracts,
[this.appContract.address]: {
contract: this.appContract,
eventNames: [
'Event1',
'Event2',
'Event3',
...
]
}
}
}

Defined in​

packages/core/src/Synchronizer.ts:707


db​

• get db(): DB

Read the database object.

Returns​

DB

Defined in​

packages/core/src/Synchronizer.ts:289


genesisBlock​

• get genesisBlock(): number

Read the genesis block of the provider environment.

Returns​

number

Defined in​

packages/core/src/Synchronizer.ts:317


provider​

• get provider(): Provider

Read the provider which is connected in the synchronizer.

Returns​

Provider

Defined in​

packages/core/src/Synchronizer.ts:296


settings​

• get settings(): any

Read the settings of the UniRep smart contract.

Returns​

any

Defined in​

packages/core/src/Synchronizer.ts:310


unirepContract​

• get unirepContract(): Contract

Read the UniRep smart contract object which is connected in the synchronizer.

Returns​

Contract

Defined in​

packages/core/src/Synchronizer.ts:303

Methods​

[captureRejectionSymbol]​

▸ Optional [captureRejectionSymbol](error, event, ...args): void

Parameters​

NameType
errorError
eventstring
...argsany[]

Returns​

void

Inherited from​

EventEmitter.[captureRejectionSymbol]

Defined in​

node_modules/@types/node/events.d.ts:112


_findStartBlock​

▸ Private _findStartBlock(): Promise<void>

Find the attester's genesis block in the Unirep smart contract. Then store the startTimestamp and epochLength in database and in the memory.

Returns​

Promise<void>

Defined in​

packages/core/src/Synchronizer.ts:429


_poll​

▸ Private _poll(): Promise<{ complete: boolean }>

Execute polling events and processing events.

Returns​

Promise<{ complete: boolean }>

Defined in​

packages/core/src/Synchronizer.ts:552


_setup​

▸ _setup(): Promise<void>

Query settings from smart contract and setup event handlers.

Returns​

Promise<void>

Defined in​

packages/core/src/Synchronizer.ts:408


addListener​

▸ addListener(eventName, listener): Synchronizer

Alias for emitter.on(eventName, listener).

Parameters​

NameType
eventNamestring | symbol
listener(...args: any[]) => void

Returns​

Synchronizer

Since

v0.1.26

Inherited from​

EventEmitter.addListener

Defined in​

node_modules/@types/node/events.d.ts:510


attesterExist​

▸ attesterExist(attesterId): boolean

Check if attester events are synchronized in this synchronizer.

Parameters​

NameTypeDescription
attesterIdstring | bigintThe queried attester ID.

Returns​

boolean

True if the attester events are synced, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:369


buildEventHandlers​

▸ Private buildEventHandlers(): void

Returns​

void

Defined in​

packages/core/src/Synchronizer.ts:211


calcCurrentEpoch​

▸ calcCurrentEpoch(attesterId?): number

Calculate the current epoch determining the amount of time since the attester registration timestamp. This operation is synchronous and does not involve any database operations.

Parameters​

NameTypeDescription
attesterIdstring | bigintThe queried attester Id.

Returns​

number

The number of current calculated epoch.

Defined in​

packages/core/src/Synchronizer.ts:834


calcEpochRemainingTime​

▸ calcEpochRemainingTime(attesterId?): number

Calculate the amount of time remaining in the current epoch. This operation is synchronous and does not involve any database operations.

Parameters​

NameTypeDescription
attesterIdstring | bigintThe queried attester Id.

Returns​

number

Current calculated time to the next epoch.

Defined in​

packages/core/src/Synchronizer.ts:851


checkAttesterId​

▸ checkAttesterId(attesterId): void

Check if attester events are synchronized in this synchronizer. It will throw an error if the attester is not synchronized.

Parameters​

NameTypeDescription
attesterIdstring | bigintThe queried attester ID.

Returns​

void

Defined in​

packages/core/src/Synchronizer.ts:377


emit​

▸ emit(eventName, ...args): boolean

Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments to each.

Returns true if the event had listeners, false otherwise.

import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();

// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});

console.log(myEmitter.listeners('event'));

myEmitter.emit('event', 1, 2, 3, 4, 5);

// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener

Parameters​

NameType
eventNamestring | symbol
...argsany[]

Returns​

boolean

Since

v0.1.26

Inherited from​

EventEmitter.emit

Defined in​

node_modules/@types/node/events.d.ts:772


epochTreeProof​

▸ epochTreeProof(epoch, leafIndex, attesterId?): Promise<MerkleProof>

Build a merkle inclusion proof for the tree from a certain epoch.

Parameters​

NameTypeDescription
epochnumberThe epoch to be queried.
leafIndexanyThe leaf index to be queried.
attesterIdstring | bigintThe attester to be queried.

Returns​

Promise<MerkleProof>

The merkle proof of the epoch tree index.

Defined in​

packages/core/src/Synchronizer.ts:895


epochTreeRoot​

▸ epochTreeRoot(epoch, attesterId?): Promise<any>

Get the epoch tree root for a certain epoch.

Parameters​

NameTypeDescription
epochnumberThe epoch to be queried.
attesterIdstring | bigintThe attester to be queried.

Returns​

Promise<any>

The epoch tree root.

Defined in​

packages/core/src/Synchronizer.ts:881


epochTreeRootExists​

▸ epochTreeRootExists(root, epoch, attesterId?): Promise<boolean>

Check if the epoch tree root is stored in the database.

Parameters​

NameTypeDescription
rootstring | bigintThe queried epoch tree root
epochnumberThe queried epoch of the epoch tree
attesterIdstring | bigintThe attester to be queried.

Returns​

Promise<boolean>

True if the epoch tree root is in the database, false otherwise.

Note

caution

Epoch tree root of current epoch might change frequently and the tree root is not stored everytime. Try use this function when querying the epoch tree in the previous epoch.

Defined in​

packages/core/src/Synchronizer.ts:1033


eventNames​

▸ eventNames(): (string | symbol)[]

Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

import { EventEmitter } from 'node:events';

const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

const sym = Symbol('symbol');
myEE.on(sym, () => {});

console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]

Returns​

(string | symbol)[]

Since

v6.0.0

Inherited from​

EventEmitter.eventNames

Defined in​

node_modules/@types/node/events.d.ts:835


genEpochTree​

▸ genEpochTree(epoch, attesterId?): Promise<IncrementalMerkleTree>

Build the latest epoch tree for a certain epoch.

Parameters​

NameTypeDescription
epochnumber | bigintThe epoch to be queried.
attesterIdstring | bigintThe attester to be queried.

Returns​

Promise<IncrementalMerkleTree>

The epoch tree.

Defined in​

packages/core/src/Synchronizer.ts:977


genHistoryTree​

▸ genHistoryTree(attesterId?): Promise<IncrementalMerkleTree>

Build the latest history tree for the current attester.

Parameters​

NameTypeDescription
attesterIdstring | bigintThe attester to be queried.

Returns​

Promise<IncrementalMerkleTree>

The history tree.

Defined in​

packages/core/src/Synchronizer.ts:951


genStateTree​

▸ genStateTree(epoch, attesterId?): Promise<IncrementalMerkleTree>

Build the latest state tree for a certain epoch.

Parameters​

NameTypeDescription
epochnumber | bigintThe epoch to be queried.
attesterIdstring | bigintThe attester to be queried.

Returns​

Promise<IncrementalMerkleTree>

The state tree.

Defined in​

packages/core/src/Synchronizer.ts:921


getMaxListeners​

▸ getMaxListeners(): number

Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.

Returns​

number

Since

v1.0.0

Inherited from​

EventEmitter.getMaxListeners

Defined in​

node_modules/@types/node/events.d.ts:687


handleAttestation​

▸ handleAttestation(args): Promise<undefined | true>

Handle attestation event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1161


handleAttesterSignedUp​

▸ handleAttesterSignedUp(args): Promise<undefined | true>

Handle attester signup event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1301


handleEpochEnded​

▸ handleEpochEnded(args): Promise<undefined | true>

Handle epoch ended event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1251


handleEpochTreeLeaf​

▸ handleEpochTreeLeaf(args): Promise<undefined | true>

Handle epoch tree leaf event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1100


handleHistoryTreeLeaf​

▸ handleHistoryTreeLeaf(args): Promise<undefined | true>

Handle history tree leaf event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1344


handleStateTreeLeaf​

▸ handleStateTreeLeaf(args): Promise<undefined | true>

Handle state tree leaf event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1067


handleUserSignedUp​

▸ handleUserSignedUp(args): Promise<undefined | true>

Handle user signup event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1133


handleUserStateTransitioned​

▸ handleUserStateTransitioned(args): Promise<undefined | true>

Handle user state transition event

Parameters​

NameTypeDescription
argsEventHandlerArgsEventHandlerArgs type arguments.

Returns​

Promise<undefined | true>

True if succeeds, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1219


listenerCount​

▸ listenerCount(eventName, listener?): number

Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

Parameters​

NameTypeDescription
eventNamestring | symbolThe name of the event being listened for
listener?FunctionThe event handler function

Returns​

number

Since

v3.2.0

Inherited from​

EventEmitter.listenerCount

Defined in​

node_modules/@types/node/events.d.ts:781


listeners​

▸ listeners(eventName): Function[]

Returns a copy of the array of listeners for the event named eventName.

server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]

Parameters​

NameType
eventNamestring | symbol

Returns​

Function[]

Since

v0.1.26

Inherited from​

EventEmitter.listeners

Defined in​

node_modules/@types/node/events.d.ts:700


loadBlocks​

▸ loadBlocks(n): Promise<void>

Load more events from the smart contract.

Parameters​

NameTypeDescription
nnumberHow many blocks will be loaded.

Returns​

Promise<void>

Defined in​

packages/core/src/Synchronizer.ts:607


loadCurrentEpoch​

▸ loadCurrentEpoch(attesterId?): Promise<number>

Load the current epoch number from the blockchain.

tip

Use this function in test environments where the blockchain timestamp may not match the real timestamp (e.g. due to snapshot/revert patterns).

Parameters​

NameTypeDescription
attesterIdstring | bigintThe queried attester Id.

Returns​

Promise<number>

The number of current epoch on-chain.

Defined in​

packages/core/src/Synchronizer.ts:870


loadNewEvents​

▸ loadNewEvents(fromBlock, toBlock): Promise<any[]>

Load new event from smart contract.

Parameters​

NameTypeDescription
fromBlocknumberFrom which block number.
toBlocknumberTo which block number.

Returns​

Promise<any[]>

All events in the block range.

Defined in​

packages/core/src/Synchronizer.ts:653


nullifierExist​

▸ nullifierExist(nullifier): Promise<any>

Determine if a nullifier exists. All nullifiers are stored in a single mapping and expected to be globally unique.

Parameters​

NameTypeDescription
nullifieranyA nullifier to be queried.

Returns​

Promise<any>

True if the nullifier exists on-chain before, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:910


numStateTreeLeaves​

▸ numStateTreeLeaves(epoch, attesterId?): Promise<number>

Get the number of state tree leaves in a certain epoch.

Parameters​

NameTypeDescription
epochnumberThe queried epoch.
attesterIdstring | bigint-

Returns​

Promise<number>

The number of the state tree leaves.

Defined in​

packages/core/src/Synchronizer.ts:1050


off​

▸ off(eventName, listener): Synchronizer

Alias for emitter.removeListener().

Parameters​

NameType
eventNamestring | symbol
listener(...args: any[]) => void

Returns​

Synchronizer

Since

v10.0.0

Inherited from​

EventEmitter.off

Defined in​

node_modules/@types/node/events.d.ts:660


on​

▸ on(eventName, listener): Synchronizer

Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple times.

server.on('connection', (stream) => {
console.log('someone connected!');
});

Returns a reference to the EventEmitter, so that calls can be chained.

By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a

Parameters​

NameTypeDescription
eventNamestring | symbolThe name of the event.
listener(...args: any[]) => voidThe callback function

Returns​

Synchronizer

Since

v0.1.101

Inherited from​

EventEmitter.on

Defined in​

node_modules/@types/node/events.d.ts:542


once​

▸ once(eventName, listener): Synchronizer

Adds a one-timelistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});

Returns a reference to the EventEmitter, so that calls can be chained.

By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a

Parameters​

NameTypeDescription
eventNamestring | symbolThe name of the event.
listener(...args: any[]) => voidThe callback function

Returns​

Synchronizer

Since

v0.3.0

Inherited from​

EventEmitter.once

Defined in​

node_modules/@types/node/events.d.ts:572


poll​

▸ poll(): Promise<{ complete: boolean }>

Manually poll for new events. Returns a boolean indicating whether the synchronizer has synced to the head of the blockchain.

Returns​

Promise<{ complete: boolean }>

Defined in​

packages/core/src/Synchronizer.ts:544


prependListener​

▸ prependListener(eventName, listener): Synchronizer

Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple times.

server.prependListener('connection', (stream) => {
console.log('someone connected!');
});

Returns a reference to the EventEmitter, so that calls can be chained.

Parameters​

NameTypeDescription
eventNamestring | symbolThe name of the event.
listener(...args: any[]) => voidThe callback function

Returns​

Synchronizer

Since

v6.0.0

Inherited from​

EventEmitter.prependListener

Defined in​

node_modules/@types/node/events.d.ts:799


prependOnceListener​

▸ prependOnceListener(eventName, listener): Synchronizer

Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});

Returns a reference to the EventEmitter, so that calls can be chained.

Parameters​

NameTypeDescription
eventNamestring | symbolThe name of the event.
listener(...args: any[]) => voidThe callback function

Returns​

Synchronizer

Since

v6.0.0

Inherited from​

EventEmitter.prependOnceListener

Defined in​

node_modules/@types/node/events.d.ts:815


processEvents​

▸ Private processEvents(events): Promise<void>

Process events with each event handler.

Parameters​

NameTypeDescription
eventsEvent[]The array of events will be proccessed.

Returns​

Promise<void>

Defined in​

packages/core/src/Synchronizer.ts:729


rawListeners​

▸ rawListeners(eventName): Function[]

Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));

// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];

// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();

// Logs "log once" to the console and removes the listener
logFnWrapper();

emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');

// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');

Parameters​

NameType
eventNamestring | symbol

Returns​

Function[]

Since

v9.4.0

Inherited from​

EventEmitter.rawListeners

Defined in​

node_modules/@types/node/events.d.ts:731


readCurrentEpoch​

▸ readCurrentEpoch(attesterId?): Promise<any>

Get the latest processed epoch from the database.

caution

This value may mismatch the onchain value depending on synchronization status.

Parameters​

NameTypeDescription
attesterIdstring | bigintThe queried attester Id.

Returns​

Promise<any>

{number: number, sealed: boolean}

Defined in​

packages/core/src/Synchronizer.ts:811


removeAllListeners​

▸ removeAllListeners(event?): Synchronizer

Removes all listeners, or those of the specified eventName.

It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

Returns a reference to the EventEmitter, so that calls can be chained.

Parameters​

NameType
event?string | symbol

Returns​

Synchronizer

Since

v0.1.26

Inherited from​

EventEmitter.removeAllListeners

Defined in​

node_modules/@types/node/events.d.ts:671


removeListener​

▸ removeListener(eventName, listener): Synchronizer

Removes the specified listener from the listener array for the event namedeventName.

const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);

removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};

const callbackB = () => {
console.log('B');
};

myEmitter.on('event', callbackA);

myEmitter.on('event', callbackB);

// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B

// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A

Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping')listener is removed:

import { EventEmitter } from 'node:events';
const ee = new EventEmitter();

function pong() {
console.log('pong');
}

ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);

ee.emit('ping');
ee.emit('ping');

Returns a reference to the EventEmitter, so that calls can be chained.

Parameters​

NameType
eventNamestring | symbol
listener(...args: any[]) => void

Returns​

Synchronizer

Since

v0.1.26

Inherited from​

EventEmitter.removeListener

Defined in​

node_modules/@types/node/events.d.ts:655


setAttesterId​

▸ setAttesterId(attesterId): void

Change default attesterId to another attester ID. It will fail if an attesterId is not synchronized during construction.

Parameters​

NameTypeDescription
attesterIdstring | bigintThe default attester Id to be set.

Returns​

void

Defined in​

packages/core/src/Synchronizer.ts:351


setMaxListeners​

▸ setMaxListeners(n): Synchronizer

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.

Returns a reference to the EventEmitter, so that calls can be chained.

Parameters​

NameType
nnumber

Returns​

Synchronizer

Since

v0.3.5

Inherited from​

EventEmitter.setMaxListeners

Defined in​

node_modules/@types/node/events.d.ts:681


setup​

▸ setup(): Promise<any>

Run setup promises.

Returns​

Promise<any>

Setup promises.

Defined in​

packages/core/src/Synchronizer.ts:394


start​

▸ start(): Promise<void>

Start the synchronizer daemon. Start polling the blockchain for new events. If we're behind the HEAD block we'll poll many times quickly

Returns​

Promise<void>

Defined in​

packages/core/src/Synchronizer.ts:491


stateTreeRootExists​

▸ stateTreeRootExists(root, epoch, attesterId?): Promise<any>

Determine if a state root exists in a certain epoch.

Parameters​

NameTypeDescription
rootstring | bigintThe queried global state tree root
epochnumberThe queried epoch of the global state tree
attesterIdstring | bigintThe attester to be queried.

Returns​

Promise<any>

True if the global state tree root exists, false otherwise.

Defined in​

packages/core/src/Synchronizer.ts:1009


stop​

▸ stop(): void

Stop synchronizing with Unirep contract.

Returns​

void

Defined in​

packages/core/src/Synchronizer.ts:536


waitForSync​

▸ waitForSync(blockNumber?): Promise<void>

Wait for the synchronizer to sync up to a certain block. By default this will wait until the current latest known block (according to the provider).

Parameters​

NameTypeDescription
blockNumber?numberThe block number to be synced to.

Returns​

Promise<void>

Defined in​

packages/core/src/Synchronizer.ts:785


addAbortListener​

▸ Static addAbortListener(signal, resource): Disposable

Listens once to the abort event on the provided signal.

Listening to the abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.

This API allows safely using AbortSignals in Node.js APIs by solving these two issues by listening to the event such that stopImmediatePropagation does not prevent the listener from running.

Returns a disposable so that it may be unsubscribed from more easily.

import { addAbortListener } from 'node:events';

function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}

Parameters​

NameType
signalAbortSignal
resource(event: Event) => void

Returns​

Disposable

Disposable that removes the abort listener.

Since

v20.5.0

Inherited from​

EventEmitter.addAbortListener

Defined in​

node_modules/@types/node/events.d.ts:387


getEventListeners​

▸ Static getEventListeners(emitter, name): Function[]

Returns a copy of the array of listeners for the event named eventName.

For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

import { getEventListeners, EventEmitter } from 'node:events';

{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}

Parameters​

NameType
emitterEventEmitter | _DOMEventTarget
namestring | symbol

Returns​

Function[]

Since

v15.2.0, v14.17.0

Inherited from​

EventEmitter.getEventListeners

Defined in​

node_modules/@types/node/events.d.ts:308


getMaxListeners​

▸ Static getMaxListeners(emitter): number

Returns the currently set max amount of listeners.

For EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.

For EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.

import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';

{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}

Parameters​

NameType
emitterEventEmitter | _DOMEventTarget

Returns​

number

Since

v19.9.0

Inherited from​

EventEmitter.getMaxListeners

Defined in​

node_modules/@types/node/events.d.ts:337


listenerCount​

▸ Static listenerCount(emitter, eventName): number

A class method that returns the number of listeners for the given eventNameregistered on the given emitter.

import { EventEmitter, listenerCount } from 'node:events';

const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2

Parameters​

NameTypeDescription
emitterEventEmitterThe emitter to query
eventNamestring | symbolThe event name

Returns​

number

Since

v0.9.12

Deprecated

Since v3.2.0 - Use listenerCount instead.

Inherited from​

EventEmitter.listenerCount

Defined in​

node_modules/@types/node/events.d.ts:280


on​

▸ Static on(emitter, eventName, options?): AsyncIterableIterator<any>

import { on, EventEmitter } from 'node:events';
import process from 'node:process';

const ee = new EventEmitter();

// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});

for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here

Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

An AbortSignal can be used to cancel waiting on events:

import { on, EventEmitter } from 'node:events';
import process from 'node:process';

const ac = new AbortController();

(async () => {
const ee = new EventEmitter();

// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});

for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();

process.nextTick(() => ac.abort());

Parameters​

NameTypeDescription
emitterEventEmitter-
eventNamestringThe name of the event being listened for
options?StaticEventEmitterOptions-

Returns​

AsyncIterableIterator<any>

that iterates eventName events emitted by the emitter

Since

v13.6.0, v12.16.0

Inherited from​

EventEmitter.on

Defined in​

node_modules/@types/node/events.d.ts:258


once​

▸ Static once(emitter, eventName, options?): Promise<any[]>

Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

import { once, EventEmitter } from 'node:events';
import process from 'node:process';

const ee = new EventEmitter();

process.nextTick(() => {
ee.emit('myevent', 42);
});

const [value] = await once(ee, 'myevent');
console.log(value);

const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});

try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}

The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:

import { EventEmitter, once } from 'node:events';

const ee = new EventEmitter();

once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));

ee.emit('error', new Error('boom'));

// Prints: ok boom

An AbortSignal can be used to cancel waiting for the event:

import { EventEmitter, once } from 'node:events';

const ee = new EventEmitter();
const ac = new AbortController();

async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}

foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!

Parameters​

NameType
emitter_NodeEventTarget
eventNamestring | symbol
options?StaticEventEmitterOptions

Returns​

Promise<any[]>

Since

v11.13.0, v10.16.0

Inherited from​

EventEmitter.once

Defined in​

node_modules/@types/node/events.d.ts:193

▸ Static once(emitter, eventName, options?): Promise<any[]>

Parameters​

NameType
emitter_DOMEventTarget
eventNamestring
options?StaticEventEmitterOptions

Returns​

Promise<any[]>

Inherited from​

EventEmitter.once

Defined in​

node_modules/@types/node/events.d.ts:198


setMaxListeners​

▸ Static setMaxListeners(n?, ...eventTargets): void

import { setMaxListeners, EventEmitter } from 'node:events';

const target = new EventTarget();
const emitter = new EventEmitter();

setMaxListeners(5, target, emitter);

Parameters​

NameTypeDescription
n?numberA non-negative number. The maximum number of listeners per EventTarget event.
...eventTargets(EventEmitter | _DOMEventTarget)[]-

Returns​

void

Since

v15.4.0

Inherited from​

EventEmitter.setMaxListeners

Defined in​

node_modules/@types/node/events.d.ts:352