@waku/rln 0.0.2-09108d9.0 → 0.0.2-2380dac.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,9 +6,10 @@ import type { IdentityCredential } from "../identity.js";
6
6
  import type { DecryptedCredentials } from "../keystore/index.js";
7
7
  import type { RLNInstance } from "../rln.js";
8
8
  import { MerkleRootTracker } from "../root_tracker.js";
9
- import { zeroPadLE } from "../utils/index.js";
9
+ import { zeroPadLE } from "../utils/bytes.js";
10
10
 
11
- import { RLN_REGISTRY_ABI, RLN_STORAGE_ABI } from "./constants.js";
11
+ import { RLN_ABI } from "./abi.js";
12
+ import { DEFAULT_RATE_LIMIT, RATE_LIMIT_PARAMS } from "./constants.js";
12
13
 
13
14
  const log = new Logger("waku:rln:contract");
14
15
 
@@ -17,18 +18,21 @@ type Member = {
17
18
  index: ethers.BigNumber;
18
19
  };
19
20
 
20
- type Signer = ethers.Signer;
21
-
22
- type RLNContractOptions = {
23
- signer: Signer;
24
- registryAddress: string;
25
- };
21
+ interface RLNContractOptions {
22
+ signer: ethers.Signer;
23
+ address: string;
24
+ rateLimit?: number;
25
+ }
26
26
 
27
- type RLNStorageOptions = {
28
- storageIndex?: number;
29
- };
27
+ interface RLNContractInitOptions extends RLNContractOptions {
28
+ contract?: ethers.Contract;
29
+ }
30
30
 
31
- type RLNContractInitOptions = RLNContractOptions & RLNStorageOptions;
31
+ export interface MembershipRegisteredEvent {
32
+ idCommitment: string;
33
+ membershipRateLimit: ethers.BigNumber;
34
+ index: ethers.BigNumber;
35
+ }
32
36
 
33
37
  type FetchMembersOptions = {
34
38
  fromBlock?: number;
@@ -36,80 +40,159 @@ type FetchMembersOptions = {
36
40
  fetchChunks?: number;
37
41
  };
38
42
 
43
+ export interface MembershipInfo {
44
+ index: ethers.BigNumber;
45
+ idCommitment: string;
46
+ rateLimit: number;
47
+ startBlock: number;
48
+ endBlock: number;
49
+ state: MembershipState;
50
+ }
51
+
52
+ export enum MembershipState {
53
+ Active = "Active",
54
+ GracePeriod = "GracePeriod",
55
+ Expired = "Expired",
56
+ ErasedAwaitsWithdrawal = "ErasedAwaitsWithdrawal"
57
+ }
58
+
39
59
  export class RLNContract {
40
- private registryContract: ethers.Contract;
60
+ public contract: ethers.Contract;
41
61
  private merkleRootTracker: MerkleRootTracker;
42
62
 
43
63
  private deployBlock: undefined | number;
44
- private storageIndex: undefined | number;
45
- private storageContract: undefined | ethers.Contract;
46
- private _membersFilter: undefined | ethers.EventFilter;
64
+ private rateLimit: number;
47
65
 
48
66
  private _members: Map<number, Member> = new Map();
49
-
67
+ private _membersFilter: ethers.EventFilter;
68
+ private _membershipErasedFilter: ethers.EventFilter;
69
+ private _membersExpiredFilter: ethers.EventFilter;
70
+
71
+ /**
72
+ * Asynchronous initializer for RLNContract.
73
+ * Allows injecting a mocked contract for testing purposes.
74
+ */
50
75
  public static async init(
51
76
  rlnInstance: RLNInstance,
52
77
  options: RLNContractInitOptions
53
78
  ): Promise<RLNContract> {
54
79
  const rlnContract = new RLNContract(rlnInstance, options);
55
80
 
56
- await rlnContract.initStorageContract(options.signer);
57
81
  await rlnContract.fetchMembers(rlnInstance);
58
82
  rlnContract.subscribeToMembers(rlnInstance);
59
83
 
60
84
  return rlnContract;
61
85
  }
62
86
 
63
- public constructor(
87
+ private constructor(
64
88
  rlnInstance: RLNInstance,
65
- { registryAddress, signer }: RLNContractOptions
89
+ options: RLNContractInitOptions
66
90
  ) {
91
+ const {
92
+ address,
93
+ signer,
94
+ rateLimit = DEFAULT_RATE_LIMIT,
95
+ contract
96
+ } = options;
97
+
98
+ if (
99
+ rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
100
+ rateLimit > RATE_LIMIT_PARAMS.MAX_RATE
101
+ ) {
102
+ throw new Error(
103
+ `Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE} messages per epoch`
104
+ );
105
+ }
106
+
107
+ this.rateLimit = rateLimit;
108
+
67
109
  const initialRoot = rlnInstance.zerokit.getMerkleRoot();
68
110
 
69
- this.registryContract = new ethers.Contract(
70
- registryAddress,
71
- RLN_REGISTRY_ABI,
72
- signer
73
- );
111
+ // Use the injected contract if provided; otherwise, instantiate a new one.
112
+ this.contract = contract || new ethers.Contract(address, RLN_ABI, signer);
74
113
  this.merkleRootTracker = new MerkleRootTracker(5, initialRoot);
114
+
115
+ // Initialize event filters
116
+ this._membersFilter = this.contract.filters.MembershipRegistered();
117
+ this._membershipErasedFilter = this.contract.filters.MembershipErased();
118
+ this._membersExpiredFilter = this.contract.filters.MembershipExpired();
75
119
  }
76
120
 
77
- private async initStorageContract(
78
- signer: Signer,
79
- options: RLNStorageOptions = {}
80
- ): Promise<void> {
81
- const storageIndex = options?.storageIndex
82
- ? options.storageIndex
83
- : await this.registryContract.usingStorageIndex();
84
- const storageAddress = await this.registryContract.storages(storageIndex);
121
+ /**
122
+ * Gets the current rate limit for this contract instance
123
+ */
124
+ public getRateLimit(): number {
125
+ return this.rateLimit;
126
+ }
85
127
 
86
- if (!storageAddress || storageAddress === ethers.constants.AddressZero) {
87
- throw Error("No RLN Storage initialized on registry contract.");
88
- }
128
+ /**
129
+ * Gets the contract address
130
+ */
131
+ public get address(): string {
132
+ return this.contract.address;
133
+ }
89
134
 
90
- this.storageIndex = storageIndex;
91
- this.storageContract = new ethers.Contract(
92
- storageAddress,
93
- RLN_STORAGE_ABI,
94
- signer
95
- );
96
- this._membersFilter = this.storageContract.filters.MemberRegistered();
135
+ /**
136
+ * Gets the contract provider
137
+ */
138
+ public get provider(): ethers.providers.Provider {
139
+ return this.contract.provider;
140
+ }
97
141
 
98
- this.deployBlock = await this.storageContract.deployedBlockNumber();
142
+ /**
143
+ * Gets the minimum allowed rate limit from the contract
144
+ * @returns Promise<number> The minimum rate limit in messages per epoch
145
+ */
146
+ public async getMinRateLimit(): Promise<number> {
147
+ const minRate = await this.contract.minMembershipRateLimit();
148
+ return minRate.toNumber();
99
149
  }
100
150
 
101
- public get registry(): ethers.Contract {
102
- if (!this.registryContract) {
103
- throw Error("Registry contract was not initialized");
104
- }
105
- return this.registryContract as ethers.Contract;
151
+ /**
152
+ * Gets the maximum allowed rate limit from the contract
153
+ * @returns Promise<number> The maximum rate limit in messages per epoch
154
+ */
155
+ public async getMaxRateLimit(): Promise<number> {
156
+ const maxRate = await this.contract.maxMembershipRateLimit();
157
+ return maxRate.toNumber();
106
158
  }
107
159
 
108
- public get contract(): ethers.Contract {
109
- if (!this.storageContract) {
110
- throw Error("Storage contract was not initialized");
111
- }
112
- return this.storageContract as ethers.Contract;
160
+ /**
161
+ * Gets the maximum total rate limit across all memberships
162
+ * @returns Promise<number> The maximum total rate limit in messages per epoch
163
+ */
164
+ public async getMaxTotalRateLimit(): Promise<number> {
165
+ const maxTotalRate = await this.contract.maxTotalRateLimit();
166
+ return maxTotalRate.toNumber();
167
+ }
168
+
169
+ /**
170
+ * Gets the current total rate limit usage across all memberships
171
+ * @returns Promise<number> The current total rate limit usage in messages per epoch
172
+ */
173
+ public async getCurrentTotalRateLimit(): Promise<number> {
174
+ const currentTotal = await this.contract.currentTotalRateLimit();
175
+ return currentTotal.toNumber();
176
+ }
177
+
178
+ /**
179
+ * Gets the remaining available total rate limit that can be allocated
180
+ * @returns Promise<number> The remaining rate limit that can be allocated
181
+ */
182
+ public async getRemainingTotalRateLimit(): Promise<number> {
183
+ const [maxTotal, currentTotal] = await Promise.all([
184
+ this.contract.maxTotalRateLimit(),
185
+ this.contract.currentTotalRateLimit()
186
+ ]);
187
+ return Number(maxTotal) - Number(currentTotal);
188
+ }
189
+
190
+ /**
191
+ * Updates the rate limit for future registrations
192
+ * @param newRateLimit The new rate limit to use
193
+ */
194
+ public async setRateLimit(newRateLimit: number): Promise<void> {
195
+ this.rateLimit = newRateLimit;
113
196
  }
114
197
 
115
198
  public get members(): Member[] {
@@ -123,7 +206,21 @@ export class RLNContract {
123
206
  if (!this._membersFilter) {
124
207
  throw Error("Members filter was not initialized.");
125
208
  }
126
- return this._membersFilter as ethers.EventFilter;
209
+ return this._membersFilter;
210
+ }
211
+
212
+ private get membershipErasedFilter(): ethers.EventFilter {
213
+ if (!this._membershipErasedFilter) {
214
+ throw Error("MembershipErased filter was not initialized.");
215
+ }
216
+ return this._membershipErasedFilter;
217
+ }
218
+
219
+ private get membersExpiredFilter(): ethers.EventFilter {
220
+ if (!this._membersExpiredFilter) {
221
+ throw Error("MembersExpired filter was not initialized.");
222
+ }
223
+ return this._membersExpiredFilter;
127
224
  }
128
225
 
129
226
  public async fetchMembers(
@@ -135,7 +232,23 @@ export class RLNContract {
135
232
  ...options,
136
233
  membersFilter: this.membersFilter
137
234
  });
138
- this.processEvents(rlnInstance, registeredMemberEvents);
235
+ const removedMemberEvents = await queryFilter(this.contract, {
236
+ fromBlock: this.deployBlock,
237
+ ...options,
238
+ membersFilter: this.membershipErasedFilter
239
+ });
240
+ const expiredMemberEvents = await queryFilter(this.contract, {
241
+ fromBlock: this.deployBlock,
242
+ ...options,
243
+ membersFilter: this.membersExpiredFilter
244
+ });
245
+
246
+ const events = [
247
+ ...registeredMemberEvents,
248
+ ...removedMemberEvents,
249
+ ...expiredMemberEvents
250
+ ];
251
+ this.processEvents(rlnInstance, events);
139
252
  }
140
253
 
141
254
  public processEvents(rlnInstance: RLNInstance, events: ethers.Event[]): void {
@@ -147,8 +260,22 @@ export class RLNContract {
147
260
  return;
148
261
  }
149
262
 
150
- if (evt.removed) {
151
- const index: ethers.BigNumber = evt.args.index;
263
+ if (
264
+ evt.event === "MembershipErased" ||
265
+ evt.event === "MembershipExpired"
266
+ ) {
267
+ // Both MembershipErased and MembershipExpired events should remove members
268
+ let index = evt.args.index;
269
+
270
+ if (!index) {
271
+ return;
272
+ }
273
+
274
+ // Convert index to ethers.BigNumber if it's not already
275
+ if (typeof index === "number" || typeof index === "string") {
276
+ index = ethers.BigNumber.from(index);
277
+ }
278
+
152
279
  const toRemoveVal = toRemoveTable.get(evt.blockNumber);
153
280
  if (toRemoveVal != undefined) {
154
281
  toRemoveVal.push(index.toNumber());
@@ -156,7 +283,7 @@ export class RLNContract {
156
283
  } else {
157
284
  toRemoveTable.set(evt.blockNumber, [index.toNumber()]);
158
285
  }
159
- } else {
286
+ } else if (evt.event === "MembershipRegistered") {
160
287
  let eventsPerBlock = toInsertTable.get(evt.blockNumber);
161
288
  if (eventsPerBlock == undefined) {
162
289
  eventsPerBlock = [];
@@ -177,18 +304,29 @@ export class RLNContract {
177
304
  ): void {
178
305
  toInsert.forEach((events: ethers.Event[], blockNumber: number) => {
179
306
  events.forEach((evt) => {
180
- const _idCommitment = evt?.args?.idCommitment;
181
- const index: ethers.BigNumber = evt?.args?.index;
307
+ if (!evt.args) return;
308
+
309
+ const _idCommitment = evt.args.idCommitment as string;
310
+ let index = evt.args.index;
182
311
 
312
+ // Ensure index is an ethers.BigNumber
183
313
  if (!_idCommitment || !index) {
184
314
  return;
185
315
  }
186
316
 
187
- const idCommitment = zeroPadLE(hexToBytes(_idCommitment?._hex), 32);
317
+ // Convert index to ethers.BigNumber if it's not already
318
+ if (typeof index === "number" || typeof index === "string") {
319
+ index = ethers.BigNumber.from(index);
320
+ }
321
+
322
+ const idCommitment = zeroPadLE(hexToBytes(_idCommitment), 32);
188
323
  rlnInstance.zerokit.insertMember(idCommitment);
189
- this._members.set(index.toNumber(), {
190
- index,
191
- idCommitment: _idCommitment?._hex
324
+
325
+ // Always store the numeric index as the key, but the BigNumber as the value
326
+ const numericIndex = index.toNumber();
327
+ this._members.set(numericIndex, {
328
+ index, // This is always a BigNumber
329
+ idCommitment: _idCommitment
192
330
  });
193
331
  });
194
332
 
@@ -201,7 +339,7 @@ export class RLNContract {
201
339
  rlnInstance: RLNInstance,
202
340
  toRemove: Map<number, number[]>
203
341
  ): void {
204
- const removeDescending = new Map([...toRemove].sort().reverse());
342
+ const removeDescending = new Map([...toRemove].reverse());
205
343
  removeDescending.forEach((indexes: number[], blockNumber: number) => {
206
344
  indexes.forEach((index) => {
207
345
  if (this._members.has(index)) {
@@ -215,63 +353,357 @@ export class RLNContract {
215
353
  }
216
354
 
217
355
  public subscribeToMembers(rlnInstance: RLNInstance): void {
218
- this.contract.on(this.membersFilter, (_pubkey, _index, event) =>
219
- this.processEvents(rlnInstance, [event])
356
+ this.contract.on(
357
+ this.membersFilter,
358
+ (
359
+ _idCommitment: string,
360
+ _membershipRateLimit: ethers.BigNumber,
361
+ _index: ethers.BigNumber,
362
+ event: ethers.Event
363
+ ) => {
364
+ this.processEvents(rlnInstance, [event]);
365
+ }
366
+ );
367
+
368
+ this.contract.on(
369
+ this.membershipErasedFilter,
370
+ (
371
+ _idCommitment: string,
372
+ _membershipRateLimit: ethers.BigNumber,
373
+ _index: ethers.BigNumber,
374
+ event: ethers.Event
375
+ ) => {
376
+ this.processEvents(rlnInstance, [event]);
377
+ }
378
+ );
379
+
380
+ this.contract.on(
381
+ this.membersExpiredFilter,
382
+ (
383
+ _idCommitment: string,
384
+ _membershipRateLimit: ethers.BigNumber,
385
+ _index: ethers.BigNumber,
386
+ event: ethers.Event
387
+ ) => {
388
+ this.processEvents(rlnInstance, [event]);
389
+ }
220
390
  );
221
391
  }
222
392
 
223
393
  public async registerWithIdentity(
224
394
  identity: IdentityCredential
225
395
  ): Promise<DecryptedCredentials | undefined> {
226
- if (this.storageIndex === undefined) {
227
- throw Error(
228
- "Cannot register credential, no storage contract index found."
396
+ try {
397
+ log.info(
398
+ `Registering identity with rate limit: ${this.rateLimit} messages/epoch`
229
399
  );
230
- }
231
- const txRegisterResponse: ethers.ContractTransaction =
232
- await this.registryContract["register(uint16,uint256)"](
233
- this.storageIndex,
400
+
401
+ // Check if the ID commitment is already registered
402
+ const existingIndex = await this.getMemberIndex(
403
+ identity.IDCommitmentBigInt.toString()
404
+ );
405
+ if (existingIndex) {
406
+ throw new Error(
407
+ `ID commitment is already registered with index ${existingIndex}`
408
+ );
409
+ }
410
+
411
+ // Check if there's enough remaining rate limit
412
+ const remainingRateLimit = await this.getRemainingTotalRateLimit();
413
+ if (remainingRateLimit < this.rateLimit) {
414
+ throw new Error(
415
+ `Not enough remaining rate limit. Requested: ${this.rateLimit}, Available: ${remainingRateLimit}`
416
+ );
417
+ }
418
+
419
+ const estimatedGas = await this.contract.estimateGas.register(
234
420
  identity.IDCommitmentBigInt,
235
- { gasLimit: 100000 }
421
+ this.rateLimit,
422
+ []
236
423
  );
237
- const txRegisterReceipt = await txRegisterResponse.wait();
424
+ const gasLimit = estimatedGas.add(10000);
238
425
 
239
- // assumption: register(uint16,uint256) emits one event
240
- const memberRegistered = txRegisterReceipt?.events?.[0];
426
+ const txRegisterResponse: ethers.ContractTransaction =
427
+ await this.contract.register(
428
+ identity.IDCommitmentBigInt,
429
+ this.rateLimit,
430
+ [],
431
+ { gasLimit }
432
+ );
241
433
 
242
- if (!memberRegistered) {
243
- return undefined;
434
+ const txRegisterReceipt = await txRegisterResponse.wait();
435
+
436
+ if (txRegisterReceipt.status === 0) {
437
+ throw new Error("Transaction failed on-chain");
438
+ }
439
+
440
+ const memberRegistered = txRegisterReceipt.events?.find(
441
+ (event) => event.event === "MembershipRegistered"
442
+ );
443
+
444
+ if (!memberRegistered || !memberRegistered.args) {
445
+ log.error(
446
+ "Failed to register membership: No MembershipRegistered event found"
447
+ );
448
+ return undefined;
449
+ }
450
+
451
+ const decodedData: MembershipRegisteredEvent = {
452
+ idCommitment: memberRegistered.args.idCommitment,
453
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
454
+ index: memberRegistered.args.index
455
+ };
456
+
457
+ log.info(
458
+ `Successfully registered membership with index ${decodedData.index} ` +
459
+ `and rate limit ${decodedData.membershipRateLimit}`
460
+ );
461
+
462
+ const network = await this.contract.provider.getNetwork();
463
+ const address = this.contract.address;
464
+ const membershipId = Number(decodedData.index);
465
+
466
+ return {
467
+ identity,
468
+ membership: {
469
+ address,
470
+ treeIndex: membershipId,
471
+ chainId: network.chainId
472
+ }
473
+ };
474
+ } catch (error) {
475
+ if (error instanceof Error) {
476
+ const errorMessage = error.message;
477
+ log.error("registerWithIdentity - error message:", errorMessage);
478
+ log.error("registerWithIdentity - error stack:", error.stack);
479
+
480
+ // Try to extract more specific error information
481
+ if (errorMessage.includes("CannotExceedMaxTotalRateLimit")) {
482
+ throw new Error(
483
+ "Registration failed: Cannot exceed maximum total rate limit"
484
+ );
485
+ } else if (errorMessage.includes("InvalidIdCommitment")) {
486
+ throw new Error("Registration failed: Invalid ID commitment");
487
+ } else if (errorMessage.includes("InvalidMembershipRateLimit")) {
488
+ throw new Error("Registration failed: Invalid membership rate limit");
489
+ } else if (errorMessage.includes("execution reverted")) {
490
+ throw new Error(
491
+ "Contract execution reverted. Check contract requirements."
492
+ );
493
+ } else {
494
+ throw new Error(`Error in registerWithIdentity: ${errorMessage}`);
495
+ }
496
+ } else {
497
+ throw new Error("Unknown error in registerWithIdentity", {
498
+ cause: error
499
+ });
500
+ }
244
501
  }
502
+ }
245
503
 
246
- const decodedData = this.contract.interface.decodeEventLog(
247
- "MemberRegistered",
248
- memberRegistered.data
249
- );
504
+ /**
505
+ * Helper method to get remaining messages in current epoch
506
+ * @param membershipId The ID of the membership to check
507
+ * @returns number of remaining messages allowed in current epoch
508
+ */
509
+ public async getRemainingMessages(membershipId: number): Promise<number> {
510
+ try {
511
+ const [startTime, , rateLimit] =
512
+ await this.contract.getMembershipInfo(membershipId);
513
+
514
+ // Calculate current epoch
515
+ const currentTime = Math.floor(Date.now() / 1000);
516
+ const epochsPassed = Math.floor(
517
+ (currentTime - startTime) / RATE_LIMIT_PARAMS.EPOCH_LENGTH
518
+ );
519
+ const currentEpochStart =
520
+ startTime + epochsPassed * RATE_LIMIT_PARAMS.EPOCH_LENGTH;
521
+
522
+ // Get message count in current epoch using contract's function
523
+ const messageCount = await this.contract.getMessageCount(
524
+ membershipId,
525
+ currentEpochStart
526
+ );
527
+ return Math.max(0, rateLimit.sub(messageCount).toNumber());
528
+ } catch (error) {
529
+ log.error(
530
+ `Error getting remaining messages: ${(error as Error).message}`
531
+ );
532
+ return 0; // Fail safe: assume no messages remaining on error
533
+ }
534
+ }
250
535
 
251
- const network = await this.registryContract.provider.getNetwork();
252
- const address = this.registryContract.address;
253
- const membershipId = decodedData.index.toNumber();
536
+ public async registerWithPermitAndErase(
537
+ identity: IdentityCredential,
538
+ permit: {
539
+ owner: string;
540
+ deadline: number;
541
+ v: number;
542
+ r: string;
543
+ s: string;
544
+ },
545
+ idCommitmentsToErase: string[]
546
+ ): Promise<DecryptedCredentials | undefined> {
547
+ try {
548
+ log.info(
549
+ `Registering identity with permit and rate limit: ${this.rateLimit} messages/epoch`
550
+ );
551
+
552
+ const txRegisterResponse: ethers.ContractTransaction =
553
+ await this.contract.registerWithPermit(
554
+ permit.owner,
555
+ permit.deadline,
556
+ permit.v,
557
+ permit.r,
558
+ permit.s,
559
+ identity.IDCommitmentBigInt,
560
+ this.rateLimit,
561
+ idCommitmentsToErase.map((id) => ethers.BigNumber.from(id))
562
+ );
563
+ const txRegisterReceipt = await txRegisterResponse.wait();
564
+
565
+ const memberRegistered = txRegisterReceipt.events?.find(
566
+ (event) => event.event === "MembershipRegistered"
567
+ );
254
568
 
255
- return {
256
- identity,
257
- membership: {
258
- address,
259
- treeIndex: membershipId,
260
- chainId: network.chainId
569
+ if (!memberRegistered || !memberRegistered.args) {
570
+ log.error(
571
+ "Failed to register membership with permit: No MembershipRegistered event found"
572
+ );
573
+ return undefined;
261
574
  }
262
- };
575
+
576
+ const decodedData: MembershipRegisteredEvent = {
577
+ idCommitment: memberRegistered.args.idCommitment,
578
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
579
+ index: memberRegistered.args.index
580
+ };
581
+
582
+ log.info(
583
+ `Successfully registered membership with permit. Index: ${decodedData.index}, ` +
584
+ `Rate limit: ${decodedData.membershipRateLimit}, Erased ${idCommitmentsToErase.length} commitments`
585
+ );
586
+
587
+ const network = await this.contract.provider.getNetwork();
588
+ const address = this.contract.address;
589
+ const membershipId = Number(decodedData.index);
590
+
591
+ return {
592
+ identity,
593
+ membership: {
594
+ address,
595
+ treeIndex: membershipId,
596
+ chainId: network.chainId
597
+ }
598
+ };
599
+ } catch (error) {
600
+ log.error(
601
+ `Error in registerWithPermitAndErase: ${(error as Error).message}`
602
+ );
603
+ return undefined;
604
+ }
263
605
  }
264
606
 
265
607
  public roots(): Uint8Array[] {
266
608
  return this.merkleRootTracker.roots();
267
609
  }
610
+
611
+ public async withdraw(token: string, holder: string): Promise<void> {
612
+ try {
613
+ const tx = await this.contract.withdraw(token, { from: holder });
614
+ await tx.wait();
615
+ } catch (error) {
616
+ log.error(`Error in withdraw: ${(error as Error).message}`);
617
+ }
618
+ }
619
+
620
+ public async getMembershipInfo(
621
+ idCommitment: string
622
+ ): Promise<MembershipInfo | undefined> {
623
+ try {
624
+ const [startBlock, endBlock, rateLimit] =
625
+ await this.contract.getMembershipInfo(idCommitment);
626
+ const currentBlock = await this.contract.provider.getBlockNumber();
627
+
628
+ let state: MembershipState;
629
+ if (currentBlock < startBlock) {
630
+ state = MembershipState.Active;
631
+ } else if (currentBlock < endBlock) {
632
+ state = MembershipState.GracePeriod;
633
+ } else {
634
+ state = MembershipState.Expired;
635
+ }
636
+
637
+ const index = await this.getMemberIndex(idCommitment);
638
+ if (!index) return undefined;
639
+
640
+ return {
641
+ index,
642
+ idCommitment,
643
+ rateLimit: rateLimit.toNumber(),
644
+ startBlock: startBlock.toNumber(),
645
+ endBlock: endBlock.toNumber(),
646
+ state
647
+ };
648
+ } catch (error) {
649
+ return undefined;
650
+ }
651
+ }
652
+
653
+ public async extendMembership(
654
+ idCommitment: string
655
+ ): Promise<ethers.ContractTransaction> {
656
+ return this.contract.extendMemberships([idCommitment]);
657
+ }
658
+
659
+ public async eraseMembership(
660
+ idCommitment: string,
661
+ eraseFromMembershipSet: boolean = true
662
+ ): Promise<ethers.ContractTransaction> {
663
+ return this.contract.eraseMemberships(
664
+ [idCommitment],
665
+ eraseFromMembershipSet
666
+ );
667
+ }
668
+
669
+ public async registerMembership(
670
+ idCommitment: string,
671
+ rateLimit: number = DEFAULT_RATE_LIMIT
672
+ ): Promise<ethers.ContractTransaction> {
673
+ if (
674
+ rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
675
+ rateLimit > RATE_LIMIT_PARAMS.MAX_RATE
676
+ ) {
677
+ throw new Error(
678
+ `Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE}`
679
+ );
680
+ }
681
+ return this.contract.register(idCommitment, rateLimit, []);
682
+ }
683
+
684
+ private async getMemberIndex(
685
+ idCommitment: string
686
+ ): Promise<ethers.BigNumber | undefined> {
687
+ try {
688
+ const events = await this.contract.queryFilter(
689
+ this.contract.filters.MembershipRegistered(idCommitment)
690
+ );
691
+ if (events.length === 0) return undefined;
692
+
693
+ // Get the most recent registration event
694
+ const event = events[events.length - 1];
695
+ return event.args?.index;
696
+ } catch (error) {
697
+ return undefined;
698
+ }
699
+ }
268
700
  }
269
701
 
270
- type CustomQueryOptions = FetchMembersOptions & {
702
+ interface CustomQueryOptions extends FetchMembersOptions {
271
703
  membersFilter: ethers.EventFilter;
272
- };
704
+ }
273
705
 
274
- // these value should be tested on other networks
706
+ // These values should be tested on other networks
275
707
  const FETCH_CHUNK = 5;
276
708
  const BLOCK_RANGE = 3000;
277
709
 
@@ -286,18 +718,18 @@ async function queryFilter(
286
718
  fetchChunks = FETCH_CHUNK
287
719
  } = options;
288
720
 
289
- if (!fromBlock) {
721
+ if (fromBlock === undefined) {
290
722
  return contract.queryFilter(membersFilter);
291
723
  }
292
724
 
293
- if (!contract.signer.provider) {
294
- throw Error("No provider found on the contract's signer.");
725
+ if (!contract.provider) {
726
+ throw Error("No provider found on the contract.");
295
727
  }
296
728
 
297
- const toBlock = await contract.signer.provider.getBlockNumber();
729
+ const toBlock = await contract.provider.getBlockNumber();
298
730
 
299
731
  if (toBlock - fromBlock < fetchRange) {
300
- return contract.queryFilter(membersFilter);
732
+ return contract.queryFilter(membersFilter, fromBlock, toBlock);
301
733
  }
302
734
 
303
735
  const events: ethers.Event[][] = [];
@@ -319,7 +751,7 @@ function splitToChunks(
319
751
  to: number,
320
752
  step: number
321
753
  ): Array<[number, number]> {
322
- const chunks = [];
754
+ const chunks: Array<[number, number]> = [];
323
755
 
324
756
  let left = from;
325
757
  while (left < to) {
@@ -345,9 +777,18 @@ function* takeN<T>(array: T[], size: number): Iterable<T[]> {
345
777
  }
346
778
  }
347
779
 
348
- function ignoreErrors<T>(promise: Promise<T>, defaultValue: T): Promise<T> {
349
- return promise.catch((err) => {
350
- log.info(`Ignoring an error during query: ${err?.message}`);
780
+ async function ignoreErrors<T>(
781
+ promise: Promise<T>,
782
+ defaultValue: T
783
+ ): Promise<T> {
784
+ try {
785
+ return await promise;
786
+ } catch (err: unknown) {
787
+ if (err instanceof Error) {
788
+ log.info(`Ignoring an error during query: ${err.message}`);
789
+ } else {
790
+ log.info(`Ignoring an unknown error during query`);
791
+ }
351
792
  return defaultValue;
352
- });
793
+ }
353
794
  }