@waku/rln 0.0.2-09108d9.0 → 0.0.2-219b8cb.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,20 @@ 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
+ let index = evt.args.index;
268
+
269
+ if (!index) {
270
+ return;
271
+ }
272
+
273
+ if (typeof index === "number" || typeof index === "string") {
274
+ index = ethers.BigNumber.from(index);
275
+ }
276
+
152
277
  const toRemoveVal = toRemoveTable.get(evt.blockNumber);
153
278
  if (toRemoveVal != undefined) {
154
279
  toRemoveVal.push(index.toNumber());
@@ -156,7 +281,7 @@ export class RLNContract {
156
281
  } else {
157
282
  toRemoveTable.set(evt.blockNumber, [index.toNumber()]);
158
283
  }
159
- } else {
284
+ } else if (evt.event === "MembershipRegistered") {
160
285
  let eventsPerBlock = toInsertTable.get(evt.blockNumber);
161
286
  if (eventsPerBlock == undefined) {
162
287
  eventsPerBlock = [];
@@ -177,18 +302,26 @@ export class RLNContract {
177
302
  ): void {
178
303
  toInsert.forEach((events: ethers.Event[], blockNumber: number) => {
179
304
  events.forEach((evt) => {
180
- const _idCommitment = evt?.args?.idCommitment;
181
- const index: ethers.BigNumber = evt?.args?.index;
305
+ if (!evt.args) return;
306
+
307
+ const _idCommitment = evt.args.idCommitment as string;
308
+ let index = evt.args.index;
182
309
 
183
310
  if (!_idCommitment || !index) {
184
311
  return;
185
312
  }
186
313
 
187
- const idCommitment = zeroPadLE(hexToBytes(_idCommitment?._hex), 32);
314
+ if (typeof index === "number" || typeof index === "string") {
315
+ index = ethers.BigNumber.from(index);
316
+ }
317
+
318
+ const idCommitment = zeroPadLE(hexToBytes(_idCommitment), 32);
188
319
  rlnInstance.zerokit.insertMember(idCommitment);
189
- this._members.set(index.toNumber(), {
320
+
321
+ const numericIndex = index.toNumber();
322
+ this._members.set(numericIndex, {
190
323
  index,
191
- idCommitment: _idCommitment?._hex
324
+ idCommitment: _idCommitment
192
325
  });
193
326
  });
194
327
 
@@ -201,7 +334,7 @@ export class RLNContract {
201
334
  rlnInstance: RLNInstance,
202
335
  toRemove: Map<number, number[]>
203
336
  ): void {
204
- const removeDescending = new Map([...toRemove].sort().reverse());
337
+ const removeDescending = new Map([...toRemove].reverse());
205
338
  removeDescending.forEach((indexes: number[], blockNumber: number) => {
206
339
  indexes.forEach((index) => {
207
340
  if (this._members.has(index)) {
@@ -215,63 +348,357 @@ export class RLNContract {
215
348
  }
216
349
 
217
350
  public subscribeToMembers(rlnInstance: RLNInstance): void {
218
- this.contract.on(this.membersFilter, (_pubkey, _index, event) =>
219
- this.processEvents(rlnInstance, [event])
351
+ this.contract.on(
352
+ this.membersFilter,
353
+ (
354
+ _idCommitment: string,
355
+ _membershipRateLimit: ethers.BigNumber,
356
+ _index: ethers.BigNumber,
357
+ event: ethers.Event
358
+ ) => {
359
+ this.processEvents(rlnInstance, [event]);
360
+ }
361
+ );
362
+
363
+ this.contract.on(
364
+ this.membershipErasedFilter,
365
+ (
366
+ _idCommitment: string,
367
+ _membershipRateLimit: ethers.BigNumber,
368
+ _index: ethers.BigNumber,
369
+ event: ethers.Event
370
+ ) => {
371
+ this.processEvents(rlnInstance, [event]);
372
+ }
373
+ );
374
+
375
+ this.contract.on(
376
+ this.membersExpiredFilter,
377
+ (
378
+ _idCommitment: string,
379
+ _membershipRateLimit: ethers.BigNumber,
380
+ _index: ethers.BigNumber,
381
+ event: ethers.Event
382
+ ) => {
383
+ this.processEvents(rlnInstance, [event]);
384
+ }
220
385
  );
221
386
  }
222
387
 
223
388
  public async registerWithIdentity(
224
389
  identity: IdentityCredential
225
390
  ): Promise<DecryptedCredentials | undefined> {
226
- if (this.storageIndex === undefined) {
227
- throw Error(
228
- "Cannot register credential, no storage contract index found."
391
+ try {
392
+ log.info(
393
+ `Registering identity with rate limit: ${this.rateLimit} messages/epoch`
229
394
  );
230
- }
231
- const txRegisterResponse: ethers.ContractTransaction =
232
- await this.registryContract["register(uint16,uint256)"](
233
- this.storageIndex,
395
+
396
+ // Check if the ID commitment is already registered
397
+ const existingIndex = await this.getMemberIndex(
398
+ identity.IDCommitmentBigInt.toString()
399
+ );
400
+ if (existingIndex) {
401
+ throw new Error(
402
+ `ID commitment is already registered with index ${existingIndex}`
403
+ );
404
+ }
405
+
406
+ // Check if there's enough remaining rate limit
407
+ const remainingRateLimit = await this.getRemainingTotalRateLimit();
408
+ if (remainingRateLimit < this.rateLimit) {
409
+ throw new Error(
410
+ `Not enough remaining rate limit. Requested: ${this.rateLimit}, Available: ${remainingRateLimit}`
411
+ );
412
+ }
413
+
414
+ const estimatedGas = await this.contract.estimateGas.register(
234
415
  identity.IDCommitmentBigInt,
235
- { gasLimit: 100000 }
416
+ this.rateLimit,
417
+ []
236
418
  );
237
- const txRegisterReceipt = await txRegisterResponse.wait();
419
+ const gasLimit = estimatedGas.add(10000);
238
420
 
239
- // assumption: register(uint16,uint256) emits one event
240
- const memberRegistered = txRegisterReceipt?.events?.[0];
421
+ const txRegisterResponse: ethers.ContractTransaction =
422
+ await this.contract.register(
423
+ identity.IDCommitmentBigInt,
424
+ this.rateLimit,
425
+ [],
426
+ { gasLimit }
427
+ );
241
428
 
242
- if (!memberRegistered) {
243
- return undefined;
429
+ const txRegisterReceipt = await txRegisterResponse.wait();
430
+
431
+ if (txRegisterReceipt.status === 0) {
432
+ throw new Error("Transaction failed on-chain");
433
+ }
434
+
435
+ const memberRegistered = txRegisterReceipt.events?.find(
436
+ (event) => event.event === "MembershipRegistered"
437
+ );
438
+
439
+ if (!memberRegistered || !memberRegistered.args) {
440
+ log.error(
441
+ "Failed to register membership: No MembershipRegistered event found"
442
+ );
443
+ return undefined;
444
+ }
445
+
446
+ const decodedData: MembershipRegisteredEvent = {
447
+ idCommitment: memberRegistered.args.idCommitment,
448
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
449
+ index: memberRegistered.args.index
450
+ };
451
+
452
+ log.info(
453
+ `Successfully registered membership with index ${decodedData.index} ` +
454
+ `and rate limit ${decodedData.membershipRateLimit}`
455
+ );
456
+
457
+ const network = await this.contract.provider.getNetwork();
458
+ const address = this.contract.address;
459
+ const membershipId = Number(decodedData.index);
460
+
461
+ return {
462
+ identity,
463
+ membership: {
464
+ address,
465
+ treeIndex: membershipId,
466
+ chainId: network.chainId
467
+ }
468
+ };
469
+ } catch (error) {
470
+ if (error instanceof Error) {
471
+ const errorMessage = error.message;
472
+ log.error("registerWithIdentity - error message:", errorMessage);
473
+ log.error("registerWithIdentity - error stack:", error.stack);
474
+
475
+ // Try to extract more specific error information
476
+ if (errorMessage.includes("CannotExceedMaxTotalRateLimit")) {
477
+ throw new Error(
478
+ "Registration failed: Cannot exceed maximum total rate limit"
479
+ );
480
+ } else if (errorMessage.includes("InvalidIdCommitment")) {
481
+ throw new Error("Registration failed: Invalid ID commitment");
482
+ } else if (errorMessage.includes("InvalidMembershipRateLimit")) {
483
+ throw new Error("Registration failed: Invalid membership rate limit");
484
+ } else if (errorMessage.includes("execution reverted")) {
485
+ throw new Error(
486
+ "Contract execution reverted. Check contract requirements."
487
+ );
488
+ } else {
489
+ throw new Error(`Error in registerWithIdentity: ${errorMessage}`);
490
+ }
491
+ } else {
492
+ throw new Error("Unknown error in registerWithIdentity", {
493
+ cause: error
494
+ });
495
+ }
244
496
  }
497
+ }
245
498
 
246
- const decodedData = this.contract.interface.decodeEventLog(
247
- "MemberRegistered",
248
- memberRegistered.data
249
- );
499
+ /**
500
+ * Helper method to get remaining messages in current epoch
501
+ * @param membershipId The ID of the membership to check
502
+ * @returns number of remaining messages allowed in current epoch
503
+ */
504
+ public async getRemainingMessages(membershipId: number): Promise<number> {
505
+ try {
506
+ const [startTime, , rateLimit] =
507
+ await this.contract.getMembershipInfo(membershipId);
508
+
509
+ // Calculate current epoch
510
+ const currentTime = Math.floor(Date.now() / 1000);
511
+ const epochsPassed = Math.floor(
512
+ (currentTime - startTime) / RATE_LIMIT_PARAMS.EPOCH_LENGTH
513
+ );
514
+ const currentEpochStart =
515
+ startTime + epochsPassed * RATE_LIMIT_PARAMS.EPOCH_LENGTH;
516
+
517
+ // Get message count in current epoch using contract's function
518
+ const messageCount = await this.contract.getMessageCount(
519
+ membershipId,
520
+ currentEpochStart
521
+ );
522
+ return Math.max(0, rateLimit.sub(messageCount).toNumber());
523
+ } catch (error) {
524
+ log.error(
525
+ `Error getting remaining messages: ${(error as Error).message}`
526
+ );
527
+ return 0; // Fail safe: assume no messages remaining on error
528
+ }
529
+ }
250
530
 
251
- const network = await this.registryContract.provider.getNetwork();
252
- const address = this.registryContract.address;
253
- const membershipId = decodedData.index.toNumber();
531
+ public async registerWithPermitAndErase(
532
+ identity: IdentityCredential,
533
+ permit: {
534
+ owner: string;
535
+ deadline: number;
536
+ v: number;
537
+ r: string;
538
+ s: string;
539
+ },
540
+ idCommitmentsToErase: string[]
541
+ ): Promise<DecryptedCredentials | undefined> {
542
+ try {
543
+ log.info(
544
+ `Registering identity with permit and rate limit: ${this.rateLimit} messages/epoch`
545
+ );
546
+
547
+ const txRegisterResponse: ethers.ContractTransaction =
548
+ await this.contract.registerWithPermit(
549
+ permit.owner,
550
+ permit.deadline,
551
+ permit.v,
552
+ permit.r,
553
+ permit.s,
554
+ identity.IDCommitmentBigInt,
555
+ this.rateLimit,
556
+ idCommitmentsToErase.map((id) => ethers.BigNumber.from(id))
557
+ );
558
+ const txRegisterReceipt = await txRegisterResponse.wait();
559
+
560
+ const memberRegistered = txRegisterReceipt.events?.find(
561
+ (event) => event.event === "MembershipRegistered"
562
+ );
254
563
 
255
- return {
256
- identity,
257
- membership: {
258
- address,
259
- treeIndex: membershipId,
260
- chainId: network.chainId
564
+ if (!memberRegistered || !memberRegistered.args) {
565
+ log.error(
566
+ "Failed to register membership with permit: No MembershipRegistered event found"
567
+ );
568
+ return undefined;
261
569
  }
262
- };
570
+
571
+ const decodedData: MembershipRegisteredEvent = {
572
+ idCommitment: memberRegistered.args.idCommitment,
573
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
574
+ index: memberRegistered.args.index
575
+ };
576
+
577
+ log.info(
578
+ `Successfully registered membership with permit. Index: ${decodedData.index}, ` +
579
+ `Rate limit: ${decodedData.membershipRateLimit}, Erased ${idCommitmentsToErase.length} commitments`
580
+ );
581
+
582
+ const network = await this.contract.provider.getNetwork();
583
+ const address = this.contract.address;
584
+ const membershipId = Number(decodedData.index);
585
+
586
+ return {
587
+ identity,
588
+ membership: {
589
+ address,
590
+ treeIndex: membershipId,
591
+ chainId: network.chainId
592
+ }
593
+ };
594
+ } catch (error) {
595
+ log.error(
596
+ `Error in registerWithPermitAndErase: ${(error as Error).message}`
597
+ );
598
+ return undefined;
599
+ }
263
600
  }
264
601
 
265
602
  public roots(): Uint8Array[] {
266
603
  return this.merkleRootTracker.roots();
267
604
  }
605
+
606
+ public async withdraw(token: string, holder: string): Promise<void> {
607
+ try {
608
+ const tx = await this.contract.withdraw(token, { from: holder });
609
+ await tx.wait();
610
+ } catch (error) {
611
+ log.error(`Error in withdraw: ${(error as Error).message}`);
612
+ }
613
+ }
614
+
615
+ public async getMembershipInfo(
616
+ idCommitment: string
617
+ ): Promise<MembershipInfo | undefined> {
618
+ try {
619
+ const [startBlock, endBlock, rateLimit] =
620
+ await this.contract.getMembershipInfo(idCommitment);
621
+ const currentBlock = await this.contract.provider.getBlockNumber();
622
+
623
+ let state: MembershipState;
624
+ if (currentBlock < startBlock) {
625
+ state = MembershipState.Active;
626
+ } else if (currentBlock < endBlock) {
627
+ state = MembershipState.GracePeriod;
628
+ } else {
629
+ state = MembershipState.Expired;
630
+ }
631
+
632
+ const index = await this.getMemberIndex(idCommitment);
633
+ if (!index) return undefined;
634
+
635
+ return {
636
+ index,
637
+ idCommitment,
638
+ rateLimit: rateLimit.toNumber(),
639
+ startBlock: startBlock.toNumber(),
640
+ endBlock: endBlock.toNumber(),
641
+ state
642
+ };
643
+ } catch (error) {
644
+ return undefined;
645
+ }
646
+ }
647
+
648
+ public async extendMembership(
649
+ idCommitment: string
650
+ ): Promise<ethers.ContractTransaction> {
651
+ return this.contract.extendMemberships([idCommitment]);
652
+ }
653
+
654
+ public async eraseMembership(
655
+ idCommitment: string,
656
+ eraseFromMembershipSet: boolean = true
657
+ ): Promise<ethers.ContractTransaction> {
658
+ return this.contract.eraseMemberships(
659
+ [idCommitment],
660
+ eraseFromMembershipSet
661
+ );
662
+ }
663
+
664
+ public async registerMembership(
665
+ idCommitment: string,
666
+ rateLimit: number = DEFAULT_RATE_LIMIT
667
+ ): Promise<ethers.ContractTransaction> {
668
+ if (
669
+ rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
670
+ rateLimit > RATE_LIMIT_PARAMS.MAX_RATE
671
+ ) {
672
+ throw new Error(
673
+ `Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE}`
674
+ );
675
+ }
676
+ return this.contract.register(idCommitment, rateLimit, []);
677
+ }
678
+
679
+ private async getMemberIndex(
680
+ idCommitment: string
681
+ ): Promise<ethers.BigNumber | undefined> {
682
+ try {
683
+ const events = await this.contract.queryFilter(
684
+ this.contract.filters.MembershipRegistered(idCommitment)
685
+ );
686
+ if (events.length === 0) return undefined;
687
+
688
+ // Get the most recent registration event
689
+ const event = events[events.length - 1];
690
+ return event.args?.index;
691
+ } catch (error) {
692
+ return undefined;
693
+ }
694
+ }
268
695
  }
269
696
 
270
- type CustomQueryOptions = FetchMembersOptions & {
697
+ interface CustomQueryOptions extends FetchMembersOptions {
271
698
  membersFilter: ethers.EventFilter;
272
- };
699
+ }
273
700
 
274
- // these value should be tested on other networks
701
+ // These values should be tested on other networks
275
702
  const FETCH_CHUNK = 5;
276
703
  const BLOCK_RANGE = 3000;
277
704
 
@@ -286,18 +713,18 @@ async function queryFilter(
286
713
  fetchChunks = FETCH_CHUNK
287
714
  } = options;
288
715
 
289
- if (!fromBlock) {
716
+ if (fromBlock === undefined) {
290
717
  return contract.queryFilter(membersFilter);
291
718
  }
292
719
 
293
- if (!contract.signer.provider) {
294
- throw Error("No provider found on the contract's signer.");
720
+ if (!contract.provider) {
721
+ throw Error("No provider found on the contract.");
295
722
  }
296
723
 
297
- const toBlock = await contract.signer.provider.getBlockNumber();
724
+ const toBlock = await contract.provider.getBlockNumber();
298
725
 
299
726
  if (toBlock - fromBlock < fetchRange) {
300
- return contract.queryFilter(membersFilter);
727
+ return contract.queryFilter(membersFilter, fromBlock, toBlock);
301
728
  }
302
729
 
303
730
  const events: ethers.Event[][] = [];
@@ -319,7 +746,7 @@ function splitToChunks(
319
746
  to: number,
320
747
  step: number
321
748
  ): Array<[number, number]> {
322
- const chunks = [];
749
+ const chunks: Array<[number, number]> = [];
323
750
 
324
751
  let left = from;
325
752
  while (left < to) {
@@ -345,9 +772,18 @@ function* takeN<T>(array: T[], size: number): Iterable<T[]> {
345
772
  }
346
773
  }
347
774
 
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}`);
775
+ async function ignoreErrors<T>(
776
+ promise: Promise<T>,
777
+ defaultValue: T
778
+ ): Promise<T> {
779
+ try {
780
+ return await promise;
781
+ } catch (err: unknown) {
782
+ if (err instanceof Error) {
783
+ log.info(`Ignoring an error during query: ${err.message}`);
784
+ } else {
785
+ log.info(`Ignoring an unknown error during query`);
786
+ }
351
787
  return defaultValue;
352
- });
788
+ }
353
789
  }