Added more DB services

This commit is contained in:
Tornado Contrib 2024-10-21 05:05:39 +00:00
parent ddf306a835
commit dfb20aa617
Signed by: tornadocontrib
GPG Key ID: 60B4DF1A076C64B1
9 changed files with 761 additions and 55 deletions

12
dist/events/base.d.ts vendored

@ -6,6 +6,7 @@ import { type NetIdType, type SubdomainMap } from '../networkConfig';
import { RelayerParams } from '../relayerClient'; import { RelayerParams } from '../relayerClient';
import type { TovarishClient } from '../tovarishClient'; import type { TovarishClient } from '../tovarishClient';
import type { ReverseRecords } from '../typechain'; import type { ReverseRecords } from '../typechain';
import type { MerkleTreeService } from '../merkleTree';
import type { BaseEvents, CachedEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, EncryptedNotesEvents, AllGovernanceEvents, GovernanceProposalCreatedEvents, GovernanceVotedEvents, RegistersEvents, EchoEvents } from './types'; import type { BaseEvents, CachedEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, EncryptedNotesEvents, AllGovernanceEvents, GovernanceProposalCreatedEvents, GovernanceVotedEvents, RegistersEvents, EchoEvents } from './types';
export declare const DEPOSIT = "deposit"; export declare const DEPOSIT = "deposit";
export declare const WITHDRAWAL = "withdrawal"; export declare const WITHDRAWAL = "withdrawal";
@ -77,7 +78,7 @@ export declare class BaseEventsService<EventType extends MinimalEvents> {
getLatestEvents({ fromBlock }: { getLatestEvents({ fromBlock }: {
fromBlock: number; fromBlock: number;
}): Promise<BaseEvents<EventType>>; }): Promise<BaseEvents<EventType>>;
validateEvents({ events, lastBlock }: BaseEvents<EventType>): void; validateEvents<S>({ events, lastBlock }: BaseEvents<EventType>): Promise<S>;
/** /**
* Handle saving events * Handle saving events
*/ */
@ -85,15 +86,17 @@ export declare class BaseEventsService<EventType extends MinimalEvents> {
/** /**
* Trigger saving and receiving latest events * Trigger saving and receiving latest events
*/ */
updateEvents(): Promise<{ updateEvents<S>(): Promise<{
events: EventType[]; events: EventType[];
lastBlock: number; lastBlock: number;
validateResult: Awaited<S>;
}>; }>;
} }
export interface BaseTornadoServiceConstructor extends Omit<BaseEventsServiceConstructor, 'contract'> { export interface BaseTornadoServiceConstructor extends Omit<BaseEventsServiceConstructor, 'contract'> {
Tornado: Tornado; Tornado: Tornado;
amount: string; amount: string;
currency: string; currency: string;
merkleTreeService?: MerkleTreeService;
} }
export interface DepositsGraphParams extends BaseGraphParams { export interface DepositsGraphParams extends BaseGraphParams {
amount: string; amount: string;
@ -102,6 +105,7 @@ export interface DepositsGraphParams extends BaseGraphParams {
export declare class BaseTornadoService extends BaseEventsService<DepositsEvents | WithdrawalsEvents> { export declare class BaseTornadoService extends BaseEventsService<DepositsEvents | WithdrawalsEvents> {
amount: string; amount: string;
currency: string; currency: string;
merkleTreeService?: MerkleTreeService;
batchTransactionService: BatchTransactionService; batchTransactionService: BatchTransactionService;
batchBlockService: BatchBlockService; batchBlockService: BatchBlockService;
constructor(serviceConstructor: BaseTornadoServiceConstructor); constructor(serviceConstructor: BaseTornadoServiceConstructor);
@ -109,9 +113,9 @@ export declare class BaseTornadoService extends BaseEventsService<DepositsEvents
getGraphMethod(): string; getGraphMethod(): string;
getGraphParams(): DepositsGraphParams; getGraphParams(): DepositsGraphParams;
formatEvents(events: EventLog[]): Promise<(DepositsEvents | WithdrawalsEvents)[]>; formatEvents(events: EventLog[]): Promise<(DepositsEvents | WithdrawalsEvents)[]>;
validateEvents({ events }: { validateEvents<S>({ events }: {
events: (DepositsEvents | WithdrawalsEvents)[]; events: (DepositsEvents | WithdrawalsEvents)[];
}): void; }): Promise<S>;
getLatestEvents({ fromBlock }: { getLatestEvents({ fromBlock }: {
fromBlock: number; fromBlock: number;
}): Promise<BaseEvents<DepositsEvents | WithdrawalsEvents>>; }): Promise<BaseEvents<DepositsEvents | WithdrawalsEvents>>;

56
dist/events/db.d.ts vendored

@ -1,6 +1,6 @@
import { IndexedDB } from '../idb'; import { IndexedDB } from '../idb';
import { BaseTornadoService, BaseTornadoServiceConstructor } from './base'; import { BaseTornadoService, BaseTornadoServiceConstructor, BaseEchoService, BaseEchoServiceConstructor, BaseEncryptedNotesService, BaseEncryptedNotesServiceConstructor, BaseGovernanceService, BaseGovernanceServiceConstructor, BaseRegistryService, BaseRegistryServiceConstructor } from './base';
import { BaseEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, CachedEvents } from './types'; import { BaseEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, CachedEvents, EchoEvents, EncryptedNotesEvents, AllGovernanceEvents, RegistersEvents } from './types';
export declare function saveDBEvents<T extends MinimalEvents>({ idb, instanceName, events, lastBlock, }: { export declare function saveDBEvents<T extends MinimalEvents>({ idb, instanceName, events, lastBlock, }: {
idb: IndexedDB; idb: IndexedDB;
instanceName: string; instanceName: string;
@ -30,3 +30,55 @@ export declare class DBTornadoService extends BaseTornadoService {
getEventsFromCache(): Promise<CachedEvents<DepositsEvents | WithdrawalsEvents>>; getEventsFromCache(): Promise<CachedEvents<DepositsEvents | WithdrawalsEvents>>;
saveEvents({ events, lastBlock }: BaseEvents<DepositsEvents | WithdrawalsEvents>): Promise<void>; saveEvents({ events, lastBlock }: BaseEvents<DepositsEvents | WithdrawalsEvents>): Promise<void>;
} }
export interface DBEchoServiceConstructor extends BaseEchoServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export declare class DBEchoService extends BaseEchoService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBEchoServiceConstructor);
getEventsFromDB(): Promise<BaseEvents<EchoEvents>>;
getEventsFromCache(): Promise<CachedEvents<EchoEvents>>;
saveEvents({ events, lastBlock }: BaseEvents<EchoEvents>): Promise<void>;
}
export interface DBEncryptedNotesServiceConstructor extends BaseEncryptedNotesServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export declare class DBEncryptedNotesService extends BaseEncryptedNotesService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBEncryptedNotesServiceConstructor);
getEventsFromDB(): Promise<BaseEvents<EncryptedNotesEvents>>;
getEventsFromCache(): Promise<CachedEvents<EncryptedNotesEvents>>;
saveEvents({ events, lastBlock }: BaseEvents<EncryptedNotesEvents>): Promise<void>;
}
export interface DBGovernanceServiceConstructor extends BaseGovernanceServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export declare class DBGovernanceService extends BaseGovernanceService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBGovernanceServiceConstructor);
getEventsFromDB(): Promise<BaseEvents<AllGovernanceEvents>>;
getEventsFromCache(): Promise<CachedEvents<AllGovernanceEvents>>;
saveEvents({ events, lastBlock }: BaseEvents<AllGovernanceEvents>): Promise<void>;
}
export interface DBRegistryServiceConstructor extends BaseRegistryServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export declare class DBRegistryService extends BaseRegistryService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBRegistryServiceConstructor);
getEventsFromDB(): Promise<BaseEvents<RegistersEvents>>;
getEventsFromCache(): Promise<CachedEvents<RegistersEvents>>;
saveEvents({ events, lastBlock }: BaseEvents<RegistersEvents>): Promise<void>;
}

166
dist/index.js vendored

@ -2948,7 +2948,8 @@ class BaseEventsService {
}; };
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
validateEvents({ events, lastBlock }) { async validateEvents({ events, lastBlock }) {
return void 0;
} }
/** /**
* Handle saving events * Handle saving events
@ -2979,29 +2980,32 @@ class BaseEventsService {
return !hasEvent; return !hasEvent;
}); });
const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber; const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber;
this.validateEvents({ events: allEvents, lastBlock }); const validateResult = await this.validateEvents({ events: allEvents, lastBlock });
if (savedEvents.fromCache || newEvents.events.length) { if (savedEvents.fromCache || newEvents.events.length) {
await this.saveEvents({ events: allEvents, lastBlock }); await this.saveEvents({ events: allEvents, lastBlock });
} }
return { return {
events: allEvents, events: allEvents,
lastBlock lastBlock,
validateResult
}; };
} }
} }
class BaseTornadoService extends BaseEventsService { class BaseTornadoService extends BaseEventsService {
amount; amount;
currency; currency;
merkleTreeService;
batchTransactionService; batchTransactionService;
batchBlockService; batchBlockService;
constructor(serviceConstructor) { constructor(serviceConstructor) {
const { Tornado: contract, amount, currency, provider } = serviceConstructor; const { Tornado: contract, amount, currency, provider, merkleTreeService } = serviceConstructor;
super({ super({
...serviceConstructor, ...serviceConstructor,
contract contract
}); });
this.amount = amount; this.amount = amount;
this.currency = currency; this.currency = currency;
this.merkleTreeService = merkleTreeService;
this.batchTransactionService = new BatchTransactionService({ this.batchTransactionService = new BatchTransactionService({
provider, provider,
onProgress: this.updateTransactionProgress onProgress: this.updateTransactionProgress
@ -3075,14 +3079,19 @@ class BaseTornadoService extends BaseEventsService {
}); });
} }
} }
validateEvents({ events }) { async validateEvents({ events }) {
if (events.length && this.getType().toLowerCase() === DEPOSIT) { if (events.length && this.getType().toLowerCase() === DEPOSIT) {
const lastEvent = events[events.length - 1]; const depositEvents = events;
if (lastEvent.leafIndex !== events.length - 1) { const lastEvent = depositEvents[depositEvents.length - 1];
const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; if (lastEvent.leafIndex !== depositEvents.length - 1) {
const errMsg = `Deposit events invalid wants ${depositEvents.length - 1} leafIndex have ${lastEvent.leafIndex}`;
throw new Error(errMsg); throw new Error(errMsg);
} }
if (this.merkleTreeService) {
return await this.merkleTreeService.verifyTree(depositEvents);
}
} }
return void 0;
} }
async getLatestEvents({ fromBlock }) { async getLatestEvents({ fromBlock }) {
if (this.tovarishClient?.selectedRelayer) { if (this.tovarishClient?.selectedRelayer) {
@ -3790,6 +3799,134 @@ class DBTornadoService extends BaseTornadoService {
}); });
} }
} }
class DBEchoService extends BaseEchoService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBEncryptedNotesService extends BaseEncryptedNotesService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBGovernanceService extends BaseGovernanceService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBRegistryService extends BaseRegistryService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
const _abi$8 = [ const _abi$8 = [
{ {
@ -10060,15 +10197,18 @@ class MerkleTreeService {
Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while
` `
); );
console.time("Created tree in"); const timeStart = Date.now();
const tree = await this.createTree(events.map(({ commitment }) => commitment)); const tree = await this.createTree(events.map(({ commitment }) => commitment));
console.timeEnd("Created tree in");
console.log("");
const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root))); const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root)));
if (!isKnownRoot) { if (!isKnownRoot) {
const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`; const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`;
throw new Error(errMsg); throw new Error(errMsg);
} }
console.log(
`
Created ${this.netId} ${this.amount} ${this.currency.toUpperCase()} tree in ${Date.now() - timeStart}ms
`
);
return tree; return tree;
} }
} }
@ -10499,6 +10639,10 @@ exports.BaseTornadoService = BaseTornadoService;
exports.BatchBlockService = BatchBlockService; exports.BatchBlockService = BatchBlockService;
exports.BatchEventsService = BatchEventsService; exports.BatchEventsService = BatchEventsService;
exports.BatchTransactionService = BatchTransactionService; exports.BatchTransactionService = BatchTransactionService;
exports.DBEchoService = DBEchoService;
exports.DBEncryptedNotesService = DBEncryptedNotesService;
exports.DBGovernanceService = DBGovernanceService;
exports.DBRegistryService = DBRegistryService;
exports.DBTornadoService = DBTornadoService; exports.DBTornadoService = DBTornadoService;
exports.DEPOSIT = DEPOSIT; exports.DEPOSIT = DEPOSIT;
exports.Deposit = Deposit; exports.Deposit = Deposit;

164
dist/index.mjs vendored

@ -2927,7 +2927,8 @@ class BaseEventsService {
}; };
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
validateEvents({ events, lastBlock }) { async validateEvents({ events, lastBlock }) {
return void 0;
} }
/** /**
* Handle saving events * Handle saving events
@ -2958,29 +2959,32 @@ class BaseEventsService {
return !hasEvent; return !hasEvent;
}); });
const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber; const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber;
this.validateEvents({ events: allEvents, lastBlock }); const validateResult = await this.validateEvents({ events: allEvents, lastBlock });
if (savedEvents.fromCache || newEvents.events.length) { if (savedEvents.fromCache || newEvents.events.length) {
await this.saveEvents({ events: allEvents, lastBlock }); await this.saveEvents({ events: allEvents, lastBlock });
} }
return { return {
events: allEvents, events: allEvents,
lastBlock lastBlock,
validateResult
}; };
} }
} }
class BaseTornadoService extends BaseEventsService { class BaseTornadoService extends BaseEventsService {
amount; amount;
currency; currency;
merkleTreeService;
batchTransactionService; batchTransactionService;
batchBlockService; batchBlockService;
constructor(serviceConstructor) { constructor(serviceConstructor) {
const { Tornado: contract, amount, currency, provider } = serviceConstructor; const { Tornado: contract, amount, currency, provider, merkleTreeService } = serviceConstructor;
super({ super({
...serviceConstructor, ...serviceConstructor,
contract contract
}); });
this.amount = amount; this.amount = amount;
this.currency = currency; this.currency = currency;
this.merkleTreeService = merkleTreeService;
this.batchTransactionService = new BatchTransactionService({ this.batchTransactionService = new BatchTransactionService({
provider, provider,
onProgress: this.updateTransactionProgress onProgress: this.updateTransactionProgress
@ -3054,14 +3058,19 @@ class BaseTornadoService extends BaseEventsService {
}); });
} }
} }
validateEvents({ events }) { async validateEvents({ events }) {
if (events.length && this.getType().toLowerCase() === DEPOSIT) { if (events.length && this.getType().toLowerCase() === DEPOSIT) {
const lastEvent = events[events.length - 1]; const depositEvents = events;
if (lastEvent.leafIndex !== events.length - 1) { const lastEvent = depositEvents[depositEvents.length - 1];
const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; if (lastEvent.leafIndex !== depositEvents.length - 1) {
const errMsg = `Deposit events invalid wants ${depositEvents.length - 1} leafIndex have ${lastEvent.leafIndex}`;
throw new Error(errMsg); throw new Error(errMsg);
} }
if (this.merkleTreeService) {
return await this.merkleTreeService.verifyTree(depositEvents);
}
} }
return void 0;
} }
async getLatestEvents({ fromBlock }) { async getLatestEvents({ fromBlock }) {
if (this.tovarishClient?.selectedRelayer) { if (this.tovarishClient?.selectedRelayer) {
@ -3769,6 +3778,134 @@ class DBTornadoService extends BaseTornadoService {
}); });
} }
} }
class DBEchoService extends BaseEchoService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBEncryptedNotesService extends BaseEncryptedNotesService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBGovernanceService extends BaseGovernanceService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBRegistryService extends BaseRegistryService {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
const _abi$8 = [ const _abi$8 = [
{ {
@ -10039,15 +10176,18 @@ class MerkleTreeService {
Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while
` `
); );
console.time("Created tree in"); const timeStart = Date.now();
const tree = await this.createTree(events.map(({ commitment }) => commitment)); const tree = await this.createTree(events.map(({ commitment }) => commitment));
console.timeEnd("Created tree in");
console.log("");
const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root))); const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root)));
if (!isKnownRoot) { if (!isKnownRoot) {
const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`; const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`;
throw new Error(errMsg); throw new Error(errMsg);
} }
console.log(
`
Created ${this.netId} ${this.amount} ${this.currency.toUpperCase()} tree in ${Date.now() - timeStart}ms
`
);
return tree; return tree;
} }
} }
@ -10469,4 +10609,4 @@ async function calculateSnarkProof(input, circuit, provingKey) {
return { proof, args }; return { proof, args };
} }
export { BaseEchoService, BaseEncryptedNotesService, BaseEventsService, BaseGovernanceService, BaseRegistryService, BaseTornadoService, BatchBlockService, BatchEventsService, BatchTransactionService, DBTornadoService, DEPOSIT, Deposit, ENSNameWrapper__factory, ENSRegistry__factory, ENSResolver__factory, ENSUtils, ENS__factory, ERC20__factory, EnsContracts, GET_DEPOSITS, GET_ECHO_EVENTS, GET_ENCRYPTED_NOTES, GET_GOVERNANCE_APY, GET_GOVERNANCE_EVENTS, GET_NOTE_ACCOUNTS, GET_REGISTERED, GET_STATISTIC, GET_WITHDRAWALS, INDEX_DB_ERROR, IndexedDB, Invoice, MAX_FEE, MAX_TOVARISH_EVENTS, MIN_FEE, MIN_STAKE_BALANCE, MerkleTreeService, Mimc, Multicall__factory, NetId, NoteAccount, OffchainOracle__factory, OvmGasPriceOracle__factory, Pedersen, RelayerClient, ReverseRecords__factory, TokenPriceOracle, TornadoBrowserProvider, TornadoFeeOracle, TornadoRpcSigner, TornadoVoidSigner, TornadoWallet, TovarishClient, WITHDRAWAL, _META, addNetwork, addressSchemaType, ajv, base64ToBytes, bigIntReplacer, bnSchemaType, bnToBytes, buffPedersenHash, bufferToBytes, bytes32BNSchemaType, bytes32SchemaType, bytesToBN, bytesToBase64, bytesToHex, calculateScore, calculateSnarkProof, chunk, concatBytes, convertETHToTokenAmount, createDeposit, crypto, customConfig, defaultConfig, defaultUserAgent, depositsEventsSchema, digest, downloadZip, echoEventsSchema, enabledChains, encodedLabelToLabelhash, encryptedNotesSchema, index as factories, fetch, fetchData, fetchGetUrlFunc, gasZipID, gasZipInbounds, gasZipInput, gasZipMinMax, getActiveTokenInstances, getActiveTokens, getAllDeposits, getAllEncryptedNotes, getAllGovernanceEvents, getAllGraphEchoEvents, getAllRegisters, getAllWithdrawals, getConfig, getDeposits, getEncryptedNotes, getEventsSchemaValidator, getGovernanceEvents, getGraphEchoEvents, getHttpAgent, getIndexedDB, getInstanceByAddress, getMeta, getNetworkConfig, getNoteAccounts, getProvider, getProviderWithNetId, getRegisters, getRelayerEnsSubdomains, getStatistic, getStatusSchema, getSupportedInstances, getTokenBalances, getTovarishNetworks, getWeightRandom, getWithdrawals, governanceEventsSchema, hexToBytes, initGroth16, isHex, isNode, jobRequestSchema, jobsSchema, labelhash, leBuff2Int, leInt2Buff, loadDBEvents, loadRemoteEvents, makeLabelNodeAndParent, mimc, multicall, numberFormatter, packEncryptedMessage, pedersen, pickWeightedRandomRelayer, populateTransaction, proofSchemaType, proposalState, queryGraph, rBigInt, registeredEventsSchema, saveDBEvents, sleep, substring, toFixedHex, toFixedLength, unpackEncryptedMessage, unzipAsync, validateUrl, withdrawalsEventsSchema, zipAsync }; export { BaseEchoService, BaseEncryptedNotesService, BaseEventsService, BaseGovernanceService, BaseRegistryService, BaseTornadoService, BatchBlockService, BatchEventsService, BatchTransactionService, DBEchoService, DBEncryptedNotesService, DBGovernanceService, DBRegistryService, DBTornadoService, DEPOSIT, Deposit, ENSNameWrapper__factory, ENSRegistry__factory, ENSResolver__factory, ENSUtils, ENS__factory, ERC20__factory, EnsContracts, GET_DEPOSITS, GET_ECHO_EVENTS, GET_ENCRYPTED_NOTES, GET_GOVERNANCE_APY, GET_GOVERNANCE_EVENTS, GET_NOTE_ACCOUNTS, GET_REGISTERED, GET_STATISTIC, GET_WITHDRAWALS, INDEX_DB_ERROR, IndexedDB, Invoice, MAX_FEE, MAX_TOVARISH_EVENTS, MIN_FEE, MIN_STAKE_BALANCE, MerkleTreeService, Mimc, Multicall__factory, NetId, NoteAccount, OffchainOracle__factory, OvmGasPriceOracle__factory, Pedersen, RelayerClient, ReverseRecords__factory, TokenPriceOracle, TornadoBrowserProvider, TornadoFeeOracle, TornadoRpcSigner, TornadoVoidSigner, TornadoWallet, TovarishClient, WITHDRAWAL, _META, addNetwork, addressSchemaType, ajv, base64ToBytes, bigIntReplacer, bnSchemaType, bnToBytes, buffPedersenHash, bufferToBytes, bytes32BNSchemaType, bytes32SchemaType, bytesToBN, bytesToBase64, bytesToHex, calculateScore, calculateSnarkProof, chunk, concatBytes, convertETHToTokenAmount, createDeposit, crypto, customConfig, defaultConfig, defaultUserAgent, depositsEventsSchema, digest, downloadZip, echoEventsSchema, enabledChains, encodedLabelToLabelhash, encryptedNotesSchema, index as factories, fetch, fetchData, fetchGetUrlFunc, gasZipID, gasZipInbounds, gasZipInput, gasZipMinMax, getActiveTokenInstances, getActiveTokens, getAllDeposits, getAllEncryptedNotes, getAllGovernanceEvents, getAllGraphEchoEvents, getAllRegisters, getAllWithdrawals, getConfig, getDeposits, getEncryptedNotes, getEventsSchemaValidator, getGovernanceEvents, getGraphEchoEvents, getHttpAgent, getIndexedDB, getInstanceByAddress, getMeta, getNetworkConfig, getNoteAccounts, getProvider, getProviderWithNetId, getRegisters, getRelayerEnsSubdomains, getStatistic, getStatusSchema, getSupportedInstances, getTokenBalances, getTovarishNetworks, getWeightRandom, getWithdrawals, governanceEventsSchema, hexToBytes, initGroth16, isHex, isNode, jobRequestSchema, jobsSchema, labelhash, leBuff2Int, leInt2Buff, loadDBEvents, loadRemoteEvents, makeLabelNodeAndParent, mimc, multicall, numberFormatter, packEncryptedMessage, pedersen, pickWeightedRandomRelayer, populateTransaction, proofSchemaType, proposalState, queryGraph, rBigInt, registeredEventsSchema, saveDBEvents, sleep, substring, toFixedHex, toFixedLength, unpackEncryptedMessage, unzipAsync, validateUrl, withdrawalsEventsSchema, zipAsync };

172
dist/tornado.umd.js vendored

@ -59367,7 +59367,8 @@ class BaseEventsService {
}; };
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
validateEvents({ events, lastBlock }) { async validateEvents({ events, lastBlock }) {
return void 0;
} }
/** /**
* Handle saving events * Handle saving events
@ -59398,29 +59399,32 @@ class BaseEventsService {
return !hasEvent; return !hasEvent;
}); });
const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber; const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber;
this.validateEvents({ events: allEvents, lastBlock }); const validateResult = await this.validateEvents({ events: allEvents, lastBlock });
if (savedEvents.fromCache || newEvents.events.length) { if (savedEvents.fromCache || newEvents.events.length) {
await this.saveEvents({ events: allEvents, lastBlock }); await this.saveEvents({ events: allEvents, lastBlock });
} }
return { return {
events: allEvents, events: allEvents,
lastBlock lastBlock,
validateResult
}; };
} }
} }
class BaseTornadoService extends BaseEventsService { class BaseTornadoService extends BaseEventsService {
amount; amount;
currency; currency;
merkleTreeService;
batchTransactionService; batchTransactionService;
batchBlockService; batchBlockService;
constructor(serviceConstructor) { constructor(serviceConstructor) {
const { Tornado: contract, amount, currency, provider } = serviceConstructor; const { Tornado: contract, amount, currency, provider, merkleTreeService } = serviceConstructor;
super({ super({
...serviceConstructor, ...serviceConstructor,
contract contract
}); });
this.amount = amount; this.amount = amount;
this.currency = currency; this.currency = currency;
this.merkleTreeService = merkleTreeService;
this.batchTransactionService = new _batch__WEBPACK_IMPORTED_MODULE_1__/* .BatchTransactionService */ .AF({ this.batchTransactionService = new _batch__WEBPACK_IMPORTED_MODULE_1__/* .BatchTransactionService */ .AF({
provider, provider,
onProgress: this.updateTransactionProgress onProgress: this.updateTransactionProgress
@ -59494,14 +59498,19 @@ class BaseTornadoService extends BaseEventsService {
}); });
} }
} }
validateEvents({ events }) { async validateEvents({ events }) {
if (events.length && this.getType().toLowerCase() === DEPOSIT) { if (events.length && this.getType().toLowerCase() === DEPOSIT) {
const lastEvent = events[events.length - 1]; const depositEvents = events;
if (lastEvent.leafIndex !== events.length - 1) { const lastEvent = depositEvents[depositEvents.length - 1];
const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; if (lastEvent.leafIndex !== depositEvents.length - 1) {
const errMsg = `Deposit events invalid wants ${depositEvents.length - 1} leafIndex have ${lastEvent.leafIndex}`;
throw new Error(errMsg); throw new Error(errMsg);
} }
if (this.merkleTreeService) {
return await this.merkleTreeService.verifyTree(depositEvents);
}
} }
return void 0;
} }
async getLatestEvents({ fromBlock }) { async getLatestEvents({ fromBlock }) {
if (this.tovarishClient?.selectedRelayer) { if (this.tovarishClient?.selectedRelayer) {
@ -60053,10 +60062,14 @@ class BaseRegistryService extends BaseEventsService {
"use strict"; "use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ $B: () => (/* binding */ DBEncryptedNotesService),
/* harmony export */ Aq: () => (/* binding */ DBGovernanceService),
/* harmony export */ Fb: () => (/* binding */ saveDBEvents), /* harmony export */ Fb: () => (/* binding */ saveDBEvents),
/* harmony export */ Oz: () => (/* binding */ loadRemoteEvents), /* harmony export */ Oz: () => (/* binding */ loadRemoteEvents),
/* harmony export */ f8: () => (/* binding */ DBTornadoService), /* harmony export */ f8: () => (/* binding */ DBTornadoService),
/* harmony export */ w8: () => (/* binding */ loadDBEvents) /* harmony export */ hD: () => (/* binding */ DBRegistryService),
/* harmony export */ w8: () => (/* binding */ loadDBEvents),
/* harmony export */ xc: () => (/* binding */ DBEchoService)
/* harmony export */ }); /* harmony export */ });
/* harmony import */ var _zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18995); /* harmony import */ var _zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18995);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(71304); /* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(71304);
@ -60178,6 +60191,134 @@ class DBTornadoService extends _base__WEBPACK_IMPORTED_MODULE_1__/* .BaseTornado
}); });
} }
} }
class DBEchoService extends _base__WEBPACK_IMPORTED_MODULE_1__/* .BaseEchoService */ .GS {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBEncryptedNotesService extends _base__WEBPACK_IMPORTED_MODULE_1__/* .BaseEncryptedNotesService */ .O_ {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBGovernanceService extends _base__WEBPACK_IMPORTED_MODULE_1__/* .BaseGovernanceService */ .JJ {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
class DBRegistryService extends _base__WEBPACK_IMPORTED_MODULE_1__/* .BaseRegistryService */ .cE {
staticUrl;
idb;
zipDigest;
constructor(params) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents({
idb: this.idb,
instanceName: this.getInstanceName()
});
}
async getEventsFromCache() {
return await loadRemoteEvents({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest
});
}
async saveEvents({ events, lastBlock }) {
await saveDBEvents({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock
});
}
}
/***/ }), /***/ }),
@ -60194,6 +60335,10 @@ __webpack_require__.r(__webpack_exports__);
/* harmony export */ BaseGovernanceService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.JJ), /* harmony export */ BaseGovernanceService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.JJ),
/* harmony export */ BaseRegistryService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.cE), /* harmony export */ BaseRegistryService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.cE),
/* harmony export */ BaseTornadoService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.e0), /* harmony export */ BaseTornadoService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.e0),
/* harmony export */ DBEchoService: () => (/* reexport safe */ _db__WEBPACK_IMPORTED_MODULE_2__.xc),
/* harmony export */ DBEncryptedNotesService: () => (/* reexport safe */ _db__WEBPACK_IMPORTED_MODULE_2__.$B),
/* harmony export */ DBGovernanceService: () => (/* reexport safe */ _db__WEBPACK_IMPORTED_MODULE_2__.Aq),
/* harmony export */ DBRegistryService: () => (/* reexport safe */ _db__WEBPACK_IMPORTED_MODULE_2__.hD),
/* harmony export */ DBTornadoService: () => (/* reexport safe */ _db__WEBPACK_IMPORTED_MODULE_2__.f8), /* harmony export */ DBTornadoService: () => (/* reexport safe */ _db__WEBPACK_IMPORTED_MODULE_2__.f8),
/* harmony export */ DEPOSIT: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.Lx), /* harmony export */ DEPOSIT: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.Lx),
/* harmony export */ WITHDRAWAL: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.oW), /* harmony export */ WITHDRAWAL: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.oW),
@ -62145,15 +62290,18 @@ class MerkleTreeService {
Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while
` `
); );
console.time("Created tree in"); const timeStart = Date.now();
const tree = await this.createTree(events.map(({ commitment }) => commitment)); const tree = await this.createTree(events.map(({ commitment }) => commitment));
console.timeEnd("Created tree in");
console.log("");
const isKnownRoot = await this.Tornado.isKnownRoot((0,_utils__WEBPACK_IMPORTED_MODULE_2__/* .toFixedHex */ .$W)(BigInt(tree.root))); const isKnownRoot = await this.Tornado.isKnownRoot((0,_utils__WEBPACK_IMPORTED_MODULE_2__/* .toFixedHex */ .$W)(BigInt(tree.root)));
if (!isKnownRoot) { if (!isKnownRoot) {
const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`; const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`;
throw new Error(errMsg); throw new Error(errMsg);
} }
console.log(
`
Created ${this.netId} ${this.amount} ${this.currency.toUpperCase()} tree in ${Date.now() - timeStart}ms
`
);
return tree; return tree;
} }
} }

File diff suppressed because one or more lines are too long

@ -39,6 +39,7 @@ import { RelayerParams, MIN_STAKE_BALANCE } from '../relayerClient';
import type { TovarishClient } from '../tovarishClient'; import type { TovarishClient } from '../tovarishClient';
import type { ReverseRecords } from '../typechain'; import type { ReverseRecords } from '../typechain';
import type { MerkleTreeService } from '../merkleTree';
import type { import type {
BaseEvents, BaseEvents,
CachedEvents, CachedEvents,
@ -295,7 +296,9 @@ export class BaseEventsService<EventType extends MinimalEvents> {
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
validateEvents({ events, lastBlock }: BaseEvents<EventType>) {} async validateEvents<S>({ events, lastBlock }: BaseEvents<EventType>): Promise<S> {
return undefined as S;
}
/** /**
* Handle saving events * Handle saving events
@ -308,7 +311,7 @@ export class BaseEventsService<EventType extends MinimalEvents> {
* Trigger saving and receiving latest events * Trigger saving and receiving latest events
*/ */
async updateEvents() { async updateEvents<S>() {
const savedEvents = await this.getSavedEvents(); const savedEvents = await this.getSavedEvents();
let fromBlock = this.deployedBlock; let fromBlock = this.deployedBlock;
@ -337,7 +340,7 @@ export class BaseEventsService<EventType extends MinimalEvents> {
const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber; const lastBlock = newEvents.lastBlock || allEvents[allEvents.length - 1]?.blockNumber;
this.validateEvents({ events: allEvents, lastBlock }); const validateResult = await this.validateEvents<S>({ events: allEvents, lastBlock });
// If the events are loaded from cache or we have found new events, save them // If the events are loaded from cache or we have found new events, save them
if ((savedEvents as CachedEvents<EventType>).fromCache || newEvents.events.length) { if ((savedEvents as CachedEvents<EventType>).fromCache || newEvents.events.length) {
@ -347,6 +350,7 @@ export class BaseEventsService<EventType extends MinimalEvents> {
return { return {
events: allEvents, events: allEvents,
lastBlock, lastBlock,
validateResult,
}; };
} }
} }
@ -355,6 +359,7 @@ export interface BaseTornadoServiceConstructor extends Omit<BaseEventsServiceCon
Tornado: Tornado; Tornado: Tornado;
amount: string; amount: string;
currency: string; currency: string;
merkleTreeService?: MerkleTreeService;
} }
export interface DepositsGraphParams extends BaseGraphParams { export interface DepositsGraphParams extends BaseGraphParams {
@ -365,11 +370,13 @@ export interface DepositsGraphParams extends BaseGraphParams {
export class BaseTornadoService extends BaseEventsService<DepositsEvents | WithdrawalsEvents> { export class BaseTornadoService extends BaseEventsService<DepositsEvents | WithdrawalsEvents> {
amount: string; amount: string;
currency: string; currency: string;
merkleTreeService?: MerkleTreeService;
batchTransactionService: BatchTransactionService; batchTransactionService: BatchTransactionService;
batchBlockService: BatchBlockService; batchBlockService: BatchBlockService;
constructor(serviceConstructor: BaseTornadoServiceConstructor) { constructor(serviceConstructor: BaseTornadoServiceConstructor) {
const { Tornado: contract, amount, currency, provider } = serviceConstructor; const { Tornado: contract, amount, currency, provider, merkleTreeService } = serviceConstructor;
super({ super({
...serviceConstructor, ...serviceConstructor,
@ -379,6 +386,8 @@ export class BaseTornadoService extends BaseEventsService<DepositsEvents | Withd
this.amount = amount; this.amount = amount;
this.currency = currency; this.currency = currency;
this.merkleTreeService = merkleTreeService;
this.batchTransactionService = new BatchTransactionService({ this.batchTransactionService = new BatchTransactionService({
provider, provider,
onProgress: this.updateTransactionProgress, onProgress: this.updateTransactionProgress,
@ -466,15 +475,23 @@ export class BaseTornadoService extends BaseEventsService<DepositsEvents | Withd
} }
} }
validateEvents({ events }: { events: (DepositsEvents | WithdrawalsEvents)[] }) { async validateEvents<S>({ events }: { events: (DepositsEvents | WithdrawalsEvents)[] }) {
if (events.length && this.getType().toLowerCase() === DEPOSIT) { if (events.length && this.getType().toLowerCase() === DEPOSIT) {
const lastEvent = events[events.length - 1] as DepositsEvents; const depositEvents = events as DepositsEvents[];
if (lastEvent.leafIndex !== events.length - 1) { const lastEvent = depositEvents[depositEvents.length - 1];
const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`;
if (lastEvent.leafIndex !== depositEvents.length - 1) {
const errMsg = `Deposit events invalid wants ${depositEvents.length - 1} leafIndex have ${lastEvent.leafIndex}`;
throw new Error(errMsg); throw new Error(errMsg);
} }
if (this.merkleTreeService) {
return (await this.merkleTreeService.verifyTree(depositEvents)) as S;
}
} }
return undefined as S;
} }
async getLatestEvents({ fromBlock }: { fromBlock: number }): Promise<BaseEvents<DepositsEvents | WithdrawalsEvents>> { async getLatestEvents({ fromBlock }: { fromBlock: number }): Promise<BaseEvents<DepositsEvents | WithdrawalsEvents>> {

@ -1,8 +1,30 @@
import { downloadZip } from '../zip'; import { downloadZip } from '../zip';
import { IndexedDB } from '../idb'; import { IndexedDB } from '../idb';
import { BaseTornadoService, BaseTornadoServiceConstructor } from './base'; import {
import { BaseEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, CachedEvents } from './types'; BaseTornadoService,
BaseTornadoServiceConstructor,
BaseEchoService,
BaseEchoServiceConstructor,
BaseEncryptedNotesService,
BaseEncryptedNotesServiceConstructor,
BaseGovernanceService,
BaseGovernanceServiceConstructor,
BaseRegistryService,
BaseRegistryServiceConstructor,
} from './base';
import {
BaseEvents,
MinimalEvents,
DepositsEvents,
WithdrawalsEvents,
CachedEvents,
EchoEvents,
EncryptedNotesEvents,
AllGovernanceEvents,
RegistersEvents,
} from './types';
export async function saveDBEvents<T extends MinimalEvents>({ export async function saveDBEvents<T extends MinimalEvents>({
idb, idb,
@ -154,3 +176,179 @@ export class DBTornadoService extends BaseTornadoService {
}); });
} }
} }
export interface DBEchoServiceConstructor extends BaseEchoServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export class DBEchoService extends BaseEchoService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBEchoServiceConstructor) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents<EchoEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
});
}
async getEventsFromCache() {
return await loadRemoteEvents<EchoEvents>({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest,
});
}
async saveEvents({ events, lastBlock }: BaseEvents<EchoEvents>) {
await saveDBEvents<EchoEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock,
});
}
}
export interface DBEncryptedNotesServiceConstructor extends BaseEncryptedNotesServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export class DBEncryptedNotesService extends BaseEncryptedNotesService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBEncryptedNotesServiceConstructor) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents<EncryptedNotesEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
});
}
async getEventsFromCache() {
return await loadRemoteEvents<EncryptedNotesEvents>({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest,
});
}
async saveEvents({ events, lastBlock }: BaseEvents<EncryptedNotesEvents>) {
await saveDBEvents<EncryptedNotesEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock,
});
}
}
export interface DBGovernanceServiceConstructor extends BaseGovernanceServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export class DBGovernanceService extends BaseGovernanceService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBGovernanceServiceConstructor) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents<AllGovernanceEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
});
}
async getEventsFromCache() {
return await loadRemoteEvents<AllGovernanceEvents>({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest,
});
}
async saveEvents({ events, lastBlock }: BaseEvents<AllGovernanceEvents>) {
await saveDBEvents<AllGovernanceEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock,
});
}
}
export interface DBRegistryServiceConstructor extends BaseRegistryServiceConstructor {
staticUrl: string;
idb: IndexedDB;
}
export class DBRegistryService extends BaseRegistryService {
staticUrl: string;
idb: IndexedDB;
zipDigest?: string;
constructor(params: DBRegistryServiceConstructor) {
super(params);
this.staticUrl = params.staticUrl;
this.idb = params.idb;
}
async getEventsFromDB() {
return await loadDBEvents<RegistersEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
});
}
async getEventsFromCache() {
return await loadRemoteEvents<RegistersEvents>({
staticUrl: this.staticUrl,
instanceName: this.getInstanceName(),
deployedBlock: this.deployedBlock,
zipDigest: this.zipDigest,
});
}
async saveEvents({ events, lastBlock }: BaseEvents<RegistersEvents>) {
await saveDBEvents<RegistersEvents>({
idb: this.idb,
instanceName: this.getInstanceName(),
events,
lastBlock,
});
}
}

@ -182,10 +182,9 @@ export class MerkleTreeService {
`\nCreating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while\n`, `\nCreating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while\n`,
); );
console.time('Created tree in'); const timeStart = Date.now();
const tree = await this.createTree(events.map(({ commitment }) => commitment)); const tree = await this.createTree(events.map(({ commitment }) => commitment));
console.timeEnd('Created tree in');
console.log('');
const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root))); const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root)));
@ -194,6 +193,10 @@ export class MerkleTreeService {
throw new Error(errMsg); throw new Error(errMsg);
} }
console.log(
`\nCreated ${this.netId} ${this.amount} ${this.currency.toUpperCase()} tree in ${Date.now() - timeStart}ms\n`,
);
return tree; return tree;
} }
} }