@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.
@@ -1,68 +1,28 @@
1
- // ref https://github.com/waku-org/waku-rln-contract/blob/19fded82bca07e7b535b429dc507cfb83f10dfcf/deployments/sepolia/WakuRlnRegistry_Implementation.json#L3
2
- const RLN_REGISTRY_ABI = [
3
- "error IncompatibleStorage()",
4
- "error IncompatibleStorageIndex()",
5
- "error NoStorageContractAvailable()",
6
- "error StorageAlreadyExists(address storageAddress)",
7
- "event AdminChanged(address previousAdmin, address newAdmin)",
8
- "event BeaconUpgraded(address indexed beacon)",
9
- "event Initialized(uint8 version)",
10
- "event NewStorageContract(uint16 index, address storageAddress)",
11
- "event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)",
12
- "event Upgraded(address indexed implementation)",
13
- "function forceProgress()",
14
- "function initialize(address _poseidonHasher)",
15
- "function newStorage()",
16
- "function nextStorageIndex() view returns (uint16)",
17
- "function owner() view returns (address)",
18
- "function poseidonHasher() view returns (address)",
19
- "function proxiableUUID() view returns (bytes32)",
20
- "function register(uint16 storageIndex, uint256 commitment)",
21
- "function register(uint256[] commitments)",
22
- "function register(uint16 storageIndex, uint256[] commitments)",
23
- "function registerStorage(address storageAddress)",
24
- "function renounceOwnership()",
25
- "function storages(uint16) view returns (address)",
26
- "function transferOwnership(address newOwner)",
27
- "function upgradeTo(address newImplementation)",
28
- "function upgradeToAndCall(address newImplementation, bytes data) payable",
29
- "function usingStorageIndex() view returns (uint16)"
30
- ];
31
- // ref https://github.com/waku-org/waku-rln-contract/blob/19fded82bca07e7b535b429dc507cfb83f10dfcf/deployments/sepolia/WakuRlnStorage_0.json#L3
32
- const RLN_STORAGE_ABI = [
33
- "constructor(address _poseidonHasher, uint16 _contractIndex)",
34
- "error DuplicateIdCommitment()",
35
- "error FullTree()",
36
- "error InvalidIdCommitment(uint256 idCommitment)",
37
- "error NotImplemented()",
38
- "event MemberRegistered(uint256 idCommitment, uint256 index)",
39
- "event MemberWithdrawn(uint256 idCommitment, uint256 index)",
40
- "event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)",
41
- "function DEPTH() view returns (uint256)",
42
- "function MEMBERSHIP_DEPOSIT() view returns (uint256)",
43
- "function SET_SIZE() view returns (uint256)",
44
- "function contractIndex() view returns (uint16)",
45
- "function deployedBlockNumber() view returns (uint32)",
46
- "function idCommitmentIndex() view returns (uint256)",
47
- "function isValidCommitment(uint256 idCommitment) view returns (bool)",
48
- "function memberExists(uint256) view returns (bool)",
49
- "function members(uint256) view returns (uint256)",
50
- "function owner() view returns (address)",
51
- "function poseidonHasher() view returns (address)",
52
- "function register(uint256[] idCommitments)",
53
- "function register(uint256 idCommitment) payable",
54
- "function renounceOwnership()",
55
- "function slash(uint256 idCommitment, address receiver, uint256[8] proof) pure",
56
- "function stakedAmounts(uint256) view returns (uint256)",
57
- "function transferOwnership(address newOwner)",
58
- "function verifier() view returns (address)",
59
- "function withdraw() pure",
60
- "function withdrawalBalance(address) view returns (uint256)"
61
- ];
1
+ import { RLN_ABI } from './abi.js';
2
+
62
3
  const SEPOLIA_CONTRACT = {
63
- chainId: 11155111,
64
- address: "0xF471d71E9b1455bBF4b85d475afb9BB0954A29c4",
65
- abi: RLN_REGISTRY_ABI
4
+ chainId: 59141,
5
+ // Implementation contract: 0xde2260ca49300357d5af4153cda0d18f7b3ea9b3
6
+ address: "0xb9cd878c90e49f797b4431fbf4fb333108cb90e6",
7
+ abi: RLN_ABI
8
+ };
9
+ /**
10
+ * Rate limit tiers (messages per epoch)
11
+ * Each membership can specify a rate limit within these bounds.
12
+ * @see https://github.com/waku-org/specs/blob/master/standards/core/rln-contract.md#implementation-suggestions
13
+ */
14
+ const RATE_LIMIT_TIERS = {
15
+ LOW: 20, // Suggested minimum rate - 20 messages per epoch
16
+ MEDIUM: 200,
17
+ HIGH: 600 // Suggested maximum rate - 600 messages per epoch
18
+ };
19
+ // Global rate limit parameters
20
+ const RATE_LIMIT_PARAMS = {
21
+ MIN_RATE: RATE_LIMIT_TIERS.LOW,
22
+ MAX_RATE: RATE_LIMIT_TIERS.HIGH,
23
+ MAX_TOTAL_RATE: 160_000, // Maximum total rate limit across all memberships
24
+ EPOCH_LENGTH: 600 // Epoch length in seconds (10 minutes)
66
25
  };
26
+ const DEFAULT_RATE_LIMIT = RATE_LIMIT_PARAMS.MAX_RATE;
67
27
 
68
- export { RLN_REGISTRY_ABI, RLN_STORAGE_ABI, SEPOLIA_CONTRACT };
28
+ export { DEFAULT_RATE_LIMIT, RATE_LIMIT_PARAMS, RATE_LIMIT_TIERS, SEPOLIA_CONTRACT };
@@ -5,56 +5,121 @@ import { hexToBytes } from '../../../utils/dist/bytes/index.js';
5
5
  import { Logger } from '../../../utils/dist/logger/index.js';
6
6
  import { MerkleRootTracker } from '../root_tracker.js';
7
7
  import { zeroPadLE } from '../utils/bytes.js';
8
- import '../utils/epoch.js';
9
- import { RLN_REGISTRY_ABI, RLN_STORAGE_ABI } from './constants.js';
8
+ import { RLN_ABI } from './abi.js';
9
+ import { RATE_LIMIT_PARAMS, DEFAULT_RATE_LIMIT } from './constants.js';
10
10
  import { Contract } from '../../../../node_modules/@ethersproject/contracts/lib.esm/index.js';
11
- import { AddressZero } from '../../../../node_modules/@ethersproject/constants/lib.esm/addresses.js';
11
+ import { BigNumber } from '../../../../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js';
12
12
 
13
13
  const log = new Logger("waku:rln:contract");
14
+ var MembershipState;
15
+ (function (MembershipState) {
16
+ MembershipState["Active"] = "Active";
17
+ MembershipState["GracePeriod"] = "GracePeriod";
18
+ MembershipState["Expired"] = "Expired";
19
+ MembershipState["ErasedAwaitsWithdrawal"] = "ErasedAwaitsWithdrawal";
20
+ })(MembershipState || (MembershipState = {}));
14
21
  class RLNContract {
15
- registryContract;
22
+ contract;
16
23
  merkleRootTracker;
17
24
  deployBlock;
18
- storageIndex;
19
- storageContract;
20
- _membersFilter;
25
+ rateLimit;
21
26
  _members = new Map();
27
+ _membersFilter;
28
+ _membershipErasedFilter;
29
+ _membersExpiredFilter;
30
+ /**
31
+ * Asynchronous initializer for RLNContract.
32
+ * Allows injecting a mocked contract for testing purposes.
33
+ */
22
34
  static async init(rlnInstance, options) {
23
35
  const rlnContract = new RLNContract(rlnInstance, options);
24
- await rlnContract.initStorageContract(options.signer);
25
36
  await rlnContract.fetchMembers(rlnInstance);
26
37
  rlnContract.subscribeToMembers(rlnInstance);
27
38
  return rlnContract;
28
39
  }
29
- constructor(rlnInstance, { registryAddress, signer }) {
40
+ constructor(rlnInstance, options) {
41
+ const { address, signer, rateLimit = DEFAULT_RATE_LIMIT, contract } = options;
42
+ if (rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
43
+ rateLimit > RATE_LIMIT_PARAMS.MAX_RATE) {
44
+ throw new Error(`Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE} messages per epoch`);
45
+ }
46
+ this.rateLimit = rateLimit;
30
47
  const initialRoot = rlnInstance.zerokit.getMerkleRoot();
31
- this.registryContract = new Contract(registryAddress, RLN_REGISTRY_ABI, signer);
48
+ // Use the injected contract if provided; otherwise, instantiate a new one.
49
+ this.contract = contract || new Contract(address, RLN_ABI, signer);
32
50
  this.merkleRootTracker = new MerkleRootTracker(5, initialRoot);
51
+ // Initialize event filters
52
+ this._membersFilter = this.contract.filters.MembershipRegistered();
53
+ this._membershipErasedFilter = this.contract.filters.MembershipErased();
54
+ this._membersExpiredFilter = this.contract.filters.MembershipExpired();
33
55
  }
34
- async initStorageContract(signer, options = {}) {
35
- const storageIndex = options?.storageIndex
36
- ? options.storageIndex
37
- : await this.registryContract.usingStorageIndex();
38
- const storageAddress = await this.registryContract.storages(storageIndex);
39
- if (!storageAddress || storageAddress === AddressZero) {
40
- throw Error("No RLN Storage initialized on registry contract.");
41
- }
42
- this.storageIndex = storageIndex;
43
- this.storageContract = new Contract(storageAddress, RLN_STORAGE_ABI, signer);
44
- this._membersFilter = this.storageContract.filters.MemberRegistered();
45
- this.deployBlock = await this.storageContract.deployedBlockNumber();
56
+ /**
57
+ * Gets the current rate limit for this contract instance
58
+ */
59
+ getRateLimit() {
60
+ return this.rateLimit;
46
61
  }
47
- get registry() {
48
- if (!this.registryContract) {
49
- throw Error("Registry contract was not initialized");
50
- }
51
- return this.registryContract;
62
+ /**
63
+ * Gets the contract address
64
+ */
65
+ get address() {
66
+ return this.contract.address;
52
67
  }
53
- get contract() {
54
- if (!this.storageContract) {
55
- throw Error("Storage contract was not initialized");
56
- }
57
- return this.storageContract;
68
+ /**
69
+ * Gets the contract provider
70
+ */
71
+ get provider() {
72
+ return this.contract.provider;
73
+ }
74
+ /**
75
+ * Gets the minimum allowed rate limit from the contract
76
+ * @returns Promise<number> The minimum rate limit in messages per epoch
77
+ */
78
+ async getMinRateLimit() {
79
+ const minRate = await this.contract.minMembershipRateLimit();
80
+ return minRate.toNumber();
81
+ }
82
+ /**
83
+ * Gets the maximum allowed rate limit from the contract
84
+ * @returns Promise<number> The maximum rate limit in messages per epoch
85
+ */
86
+ async getMaxRateLimit() {
87
+ const maxRate = await this.contract.maxMembershipRateLimit();
88
+ return maxRate.toNumber();
89
+ }
90
+ /**
91
+ * Gets the maximum total rate limit across all memberships
92
+ * @returns Promise<number> The maximum total rate limit in messages per epoch
93
+ */
94
+ async getMaxTotalRateLimit() {
95
+ const maxTotalRate = await this.contract.maxTotalRateLimit();
96
+ return maxTotalRate.toNumber();
97
+ }
98
+ /**
99
+ * Gets the current total rate limit usage across all memberships
100
+ * @returns Promise<number> The current total rate limit usage in messages per epoch
101
+ */
102
+ async getCurrentTotalRateLimit() {
103
+ const currentTotal = await this.contract.currentTotalRateLimit();
104
+ return currentTotal.toNumber();
105
+ }
106
+ /**
107
+ * Gets the remaining available total rate limit that can be allocated
108
+ * @returns Promise<number> The remaining rate limit that can be allocated
109
+ */
110
+ async getRemainingTotalRateLimit() {
111
+ const [maxTotal, currentTotal] = await Promise.all([
112
+ this.contract.maxTotalRateLimit(),
113
+ this.contract.currentTotalRateLimit()
114
+ ]);
115
+ return Number(maxTotal) - Number(currentTotal);
116
+ }
117
+ /**
118
+ * Updates the rate limit for future registrations
119
+ * @param newRateLimit The new rate limit to use
120
+ */
121
+ async setRateLimit(newRateLimit) {
122
+ this.rateLimit = newRateLimit;
58
123
  }
59
124
  get members() {
60
125
  const sortedMembers = Array.from(this._members.values()).sort((left, right) => left.index.toNumber() - right.index.toNumber());
@@ -66,13 +131,40 @@ class RLNContract {
66
131
  }
67
132
  return this._membersFilter;
68
133
  }
134
+ get membershipErasedFilter() {
135
+ if (!this._membershipErasedFilter) {
136
+ throw Error("MembershipErased filter was not initialized.");
137
+ }
138
+ return this._membershipErasedFilter;
139
+ }
140
+ get membersExpiredFilter() {
141
+ if (!this._membersExpiredFilter) {
142
+ throw Error("MembersExpired filter was not initialized.");
143
+ }
144
+ return this._membersExpiredFilter;
145
+ }
69
146
  async fetchMembers(rlnInstance, options = {}) {
70
147
  const registeredMemberEvents = await queryFilter(this.contract, {
71
148
  fromBlock: this.deployBlock,
72
149
  ...options,
73
150
  membersFilter: this.membersFilter
74
151
  });
75
- this.processEvents(rlnInstance, registeredMemberEvents);
152
+ const removedMemberEvents = await queryFilter(this.contract, {
153
+ fromBlock: this.deployBlock,
154
+ ...options,
155
+ membersFilter: this.membershipErasedFilter
156
+ });
157
+ const expiredMemberEvents = await queryFilter(this.contract, {
158
+ fromBlock: this.deployBlock,
159
+ ...options,
160
+ membersFilter: this.membersExpiredFilter
161
+ });
162
+ const events = [
163
+ ...registeredMemberEvents,
164
+ ...removedMemberEvents,
165
+ ...expiredMemberEvents
166
+ ];
167
+ this.processEvents(rlnInstance, events);
76
168
  }
77
169
  processEvents(rlnInstance, events) {
78
170
  const toRemoveTable = new Map();
@@ -81,8 +173,17 @@ class RLNContract {
81
173
  if (!evt.args) {
82
174
  return;
83
175
  }
84
- if (evt.removed) {
85
- const index = evt.args.index;
176
+ if (evt.event === "MembershipErased" ||
177
+ evt.event === "MembershipExpired") {
178
+ // Both MembershipErased and MembershipExpired events should remove members
179
+ let index = evt.args.index;
180
+ if (!index) {
181
+ return;
182
+ }
183
+ // Convert index to ethers.BigNumber if it's not already
184
+ if (typeof index === "number" || typeof index === "string") {
185
+ index = BigNumber.from(index);
186
+ }
86
187
  const toRemoveVal = toRemoveTable.get(evt.blockNumber);
87
188
  if (toRemoveVal != undefined) {
88
189
  toRemoveVal.push(index.toNumber());
@@ -92,7 +193,7 @@ class RLNContract {
92
193
  toRemoveTable.set(evt.blockNumber, [index.toNumber()]);
93
194
  }
94
195
  }
95
- else {
196
+ else if (evt.event === "MembershipRegistered") {
96
197
  let eventsPerBlock = toInsertTable.get(evt.blockNumber);
97
198
  if (eventsPerBlock == undefined) {
98
199
  eventsPerBlock = [];
@@ -107,16 +208,25 @@ class RLNContract {
107
208
  insertMembers(rlnInstance, toInsert) {
108
209
  toInsert.forEach((events, blockNumber) => {
109
210
  events.forEach((evt) => {
110
- const _idCommitment = evt?.args?.idCommitment;
111
- const index = evt?.args?.index;
211
+ if (!evt.args)
212
+ return;
213
+ const _idCommitment = evt.args.idCommitment;
214
+ let index = evt.args.index;
215
+ // Ensure index is an ethers.BigNumber
112
216
  if (!_idCommitment || !index) {
113
217
  return;
114
218
  }
115
- const idCommitment = zeroPadLE(hexToBytes(_idCommitment?._hex), 32);
219
+ // Convert index to ethers.BigNumber if it's not already
220
+ if (typeof index === "number" || typeof index === "string") {
221
+ index = BigNumber.from(index);
222
+ }
223
+ const idCommitment = zeroPadLE(hexToBytes(_idCommitment), 32);
116
224
  rlnInstance.zerokit.insertMember(idCommitment);
117
- this._members.set(index.toNumber(), {
118
- index,
119
- idCommitment: _idCommitment?._hex
225
+ // Always store the numeric index as the key, but the BigNumber as the value
226
+ const numericIndex = index.toNumber();
227
+ this._members.set(numericIndex, {
228
+ index, // This is always a BigNumber
229
+ idCommitment: _idCommitment
120
230
  });
121
231
  });
122
232
  const currentRoot = rlnInstance.zerokit.getMerkleRoot();
@@ -124,7 +234,7 @@ class RLNContract {
124
234
  });
125
235
  }
126
236
  removeMembers(rlnInstance, toRemove) {
127
- const removeDescending = new Map([...toRemove].sort().reverse());
237
+ const removeDescending = new Map([...toRemove].reverse());
128
238
  removeDescending.forEach((indexes, blockNumber) => {
129
239
  indexes.forEach((index) => {
130
240
  if (this._members.has(index)) {
@@ -136,50 +246,227 @@ class RLNContract {
136
246
  });
137
247
  }
138
248
  subscribeToMembers(rlnInstance) {
139
- this.contract.on(this.membersFilter, (_pubkey, _index, event) => this.processEvents(rlnInstance, [event]));
249
+ this.contract.on(this.membersFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
250
+ this.processEvents(rlnInstance, [event]);
251
+ });
252
+ this.contract.on(this.membershipErasedFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
253
+ this.processEvents(rlnInstance, [event]);
254
+ });
255
+ this.contract.on(this.membersExpiredFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
256
+ this.processEvents(rlnInstance, [event]);
257
+ });
140
258
  }
141
259
  async registerWithIdentity(identity) {
142
- if (this.storageIndex === undefined) {
143
- throw Error("Cannot register credential, no storage contract index found.");
144
- }
145
- const txRegisterResponse = await this.registryContract["register(uint16,uint256)"](this.storageIndex, identity.IDCommitmentBigInt, { gasLimit: 100000 });
146
- const txRegisterReceipt = await txRegisterResponse.wait();
147
- // assumption: register(uint16,uint256) emits one event
148
- const memberRegistered = txRegisterReceipt?.events?.[0];
149
- if (!memberRegistered) {
150
- return undefined;
260
+ try {
261
+ log.info(`Registering identity with rate limit: ${this.rateLimit} messages/epoch`);
262
+ // Check if the ID commitment is already registered
263
+ const existingIndex = await this.getMemberIndex(identity.IDCommitmentBigInt.toString());
264
+ if (existingIndex) {
265
+ throw new Error(`ID commitment is already registered with index ${existingIndex}`);
266
+ }
267
+ // Check if there's enough remaining rate limit
268
+ const remainingRateLimit = await this.getRemainingTotalRateLimit();
269
+ if (remainingRateLimit < this.rateLimit) {
270
+ throw new Error(`Not enough remaining rate limit. Requested: ${this.rateLimit}, Available: ${remainingRateLimit}`);
271
+ }
272
+ const estimatedGas = await this.contract.estimateGas.register(identity.IDCommitmentBigInt, this.rateLimit, []);
273
+ const gasLimit = estimatedGas.add(10000);
274
+ const txRegisterResponse = await this.contract.register(identity.IDCommitmentBigInt, this.rateLimit, [], { gasLimit });
275
+ const txRegisterReceipt = await txRegisterResponse.wait();
276
+ if (txRegisterReceipt.status === 0) {
277
+ throw new Error("Transaction failed on-chain");
278
+ }
279
+ const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
280
+ if (!memberRegistered || !memberRegistered.args) {
281
+ log.error("Failed to register membership: No MembershipRegistered event found");
282
+ return undefined;
283
+ }
284
+ const decodedData = {
285
+ idCommitment: memberRegistered.args.idCommitment,
286
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
287
+ index: memberRegistered.args.index
288
+ };
289
+ log.info(`Successfully registered membership with index ${decodedData.index} ` +
290
+ `and rate limit ${decodedData.membershipRateLimit}`);
291
+ const network = await this.contract.provider.getNetwork();
292
+ const address = this.contract.address;
293
+ const membershipId = Number(decodedData.index);
294
+ return {
295
+ identity,
296
+ membership: {
297
+ address,
298
+ treeIndex: membershipId,
299
+ chainId: network.chainId
300
+ }
301
+ };
302
+ }
303
+ catch (error) {
304
+ if (error instanceof Error) {
305
+ const errorMessage = error.message;
306
+ log.error("registerWithIdentity - error message:", errorMessage);
307
+ log.error("registerWithIdentity - error stack:", error.stack);
308
+ // Try to extract more specific error information
309
+ if (errorMessage.includes("CannotExceedMaxTotalRateLimit")) {
310
+ throw new Error("Registration failed: Cannot exceed maximum total rate limit");
311
+ }
312
+ else if (errorMessage.includes("InvalidIdCommitment")) {
313
+ throw new Error("Registration failed: Invalid ID commitment");
314
+ }
315
+ else if (errorMessage.includes("InvalidMembershipRateLimit")) {
316
+ throw new Error("Registration failed: Invalid membership rate limit");
317
+ }
318
+ else if (errorMessage.includes("execution reverted")) {
319
+ throw new Error("Contract execution reverted. Check contract requirements.");
320
+ }
321
+ else {
322
+ throw new Error(`Error in registerWithIdentity: ${errorMessage}`);
323
+ }
324
+ }
325
+ else {
326
+ throw new Error("Unknown error in registerWithIdentity", {
327
+ cause: error
328
+ });
329
+ }
330
+ }
331
+ }
332
+ /**
333
+ * Helper method to get remaining messages in current epoch
334
+ * @param membershipId The ID of the membership to check
335
+ * @returns number of remaining messages allowed in current epoch
336
+ */
337
+ async getRemainingMessages(membershipId) {
338
+ try {
339
+ const [startTime, , rateLimit] = await this.contract.getMembershipInfo(membershipId);
340
+ // Calculate current epoch
341
+ const currentTime = Math.floor(Date.now() / 1000);
342
+ const epochsPassed = Math.floor((currentTime - startTime) / RATE_LIMIT_PARAMS.EPOCH_LENGTH);
343
+ const currentEpochStart = startTime + epochsPassed * RATE_LIMIT_PARAMS.EPOCH_LENGTH;
344
+ // Get message count in current epoch using contract's function
345
+ const messageCount = await this.contract.getMessageCount(membershipId, currentEpochStart);
346
+ return Math.max(0, rateLimit.sub(messageCount).toNumber());
151
347
  }
152
- const decodedData = this.contract.interface.decodeEventLog("MemberRegistered", memberRegistered.data);
153
- const network = await this.registryContract.provider.getNetwork();
154
- const address = this.registryContract.address;
155
- const membershipId = decodedData.index.toNumber();
156
- return {
157
- identity,
158
- membership: {
159
- address,
160
- treeIndex: membershipId,
161
- chainId: network.chainId
348
+ catch (error) {
349
+ log.error(`Error getting remaining messages: ${error.message}`);
350
+ return 0; // Fail safe: assume no messages remaining on error
351
+ }
352
+ }
353
+ async registerWithPermitAndErase(identity, permit, idCommitmentsToErase) {
354
+ try {
355
+ log.info(`Registering identity with permit and rate limit: ${this.rateLimit} messages/epoch`);
356
+ const txRegisterResponse = await this.contract.registerWithPermit(permit.owner, permit.deadline, permit.v, permit.r, permit.s, identity.IDCommitmentBigInt, this.rateLimit, idCommitmentsToErase.map((id) => BigNumber.from(id)));
357
+ const txRegisterReceipt = await txRegisterResponse.wait();
358
+ const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
359
+ if (!memberRegistered || !memberRegistered.args) {
360
+ log.error("Failed to register membership with permit: No MembershipRegistered event found");
361
+ return undefined;
162
362
  }
163
- };
363
+ const decodedData = {
364
+ idCommitment: memberRegistered.args.idCommitment,
365
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
366
+ index: memberRegistered.args.index
367
+ };
368
+ log.info(`Successfully registered membership with permit. Index: ${decodedData.index}, ` +
369
+ `Rate limit: ${decodedData.membershipRateLimit}, Erased ${idCommitmentsToErase.length} commitments`);
370
+ const network = await this.contract.provider.getNetwork();
371
+ const address = this.contract.address;
372
+ const membershipId = Number(decodedData.index);
373
+ return {
374
+ identity,
375
+ membership: {
376
+ address,
377
+ treeIndex: membershipId,
378
+ chainId: network.chainId
379
+ }
380
+ };
381
+ }
382
+ catch (error) {
383
+ log.error(`Error in registerWithPermitAndErase: ${error.message}`);
384
+ return undefined;
385
+ }
164
386
  }
165
387
  roots() {
166
388
  return this.merkleRootTracker.roots();
167
389
  }
390
+ async withdraw(token, holder) {
391
+ try {
392
+ const tx = await this.contract.withdraw(token, { from: holder });
393
+ await tx.wait();
394
+ }
395
+ catch (error) {
396
+ log.error(`Error in withdraw: ${error.message}`);
397
+ }
398
+ }
399
+ async getMembershipInfo(idCommitment) {
400
+ try {
401
+ const [startBlock, endBlock, rateLimit] = await this.contract.getMembershipInfo(idCommitment);
402
+ const currentBlock = await this.contract.provider.getBlockNumber();
403
+ let state;
404
+ if (currentBlock < startBlock) {
405
+ state = MembershipState.Active;
406
+ }
407
+ else if (currentBlock < endBlock) {
408
+ state = MembershipState.GracePeriod;
409
+ }
410
+ else {
411
+ state = MembershipState.Expired;
412
+ }
413
+ const index = await this.getMemberIndex(idCommitment);
414
+ if (!index)
415
+ return undefined;
416
+ return {
417
+ index,
418
+ idCommitment,
419
+ rateLimit: rateLimit.toNumber(),
420
+ startBlock: startBlock.toNumber(),
421
+ endBlock: endBlock.toNumber(),
422
+ state
423
+ };
424
+ }
425
+ catch (error) {
426
+ return undefined;
427
+ }
428
+ }
429
+ async extendMembership(idCommitment) {
430
+ return this.contract.extendMemberships([idCommitment]);
431
+ }
432
+ async eraseMembership(idCommitment, eraseFromMembershipSet = true) {
433
+ return this.contract.eraseMemberships([idCommitment], eraseFromMembershipSet);
434
+ }
435
+ async registerMembership(idCommitment, rateLimit = DEFAULT_RATE_LIMIT) {
436
+ if (rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
437
+ rateLimit > RATE_LIMIT_PARAMS.MAX_RATE) {
438
+ throw new Error(`Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE}`);
439
+ }
440
+ return this.contract.register(idCommitment, rateLimit, []);
441
+ }
442
+ async getMemberIndex(idCommitment) {
443
+ try {
444
+ const events = await this.contract.queryFilter(this.contract.filters.MembershipRegistered(idCommitment));
445
+ if (events.length === 0)
446
+ return undefined;
447
+ // Get the most recent registration event
448
+ const event = events[events.length - 1];
449
+ return event.args?.index;
450
+ }
451
+ catch (error) {
452
+ return undefined;
453
+ }
454
+ }
168
455
  }
169
- // these value should be tested on other networks
456
+ // These values should be tested on other networks
170
457
  const FETCH_CHUNK = 5;
171
458
  const BLOCK_RANGE = 3000;
172
459
  async function queryFilter(contract, options) {
173
460
  const { fromBlock, membersFilter, fetchRange = BLOCK_RANGE, fetchChunks = FETCH_CHUNK } = options;
174
- if (!fromBlock) {
461
+ if (fromBlock === undefined) {
175
462
  return contract.queryFilter(membersFilter);
176
463
  }
177
- if (!contract.signer.provider) {
178
- throw Error("No provider found on the contract's signer.");
464
+ if (!contract.provider) {
465
+ throw Error("No provider found on the contract.");
179
466
  }
180
- const toBlock = await contract.signer.provider.getBlockNumber();
467
+ const toBlock = await contract.provider.getBlockNumber();
181
468
  if (toBlock - fromBlock < fetchRange) {
182
- return contract.queryFilter(membersFilter);
469
+ return contract.queryFilter(membersFilter, fromBlock, toBlock);
183
470
  }
184
471
  const events = [];
185
472
  const chunks = splitToChunks(fromBlock, toBlock, fetchRange);
@@ -208,11 +495,19 @@ function* takeN(array, size) {
208
495
  start += size;
209
496
  }
210
497
  }
211
- function ignoreErrors(promise, defaultValue) {
212
- return promise.catch((err) => {
213
- log.info(`Ignoring an error during query: ${err?.message}`);
498
+ async function ignoreErrors(promise, defaultValue) {
499
+ try {
500
+ return await promise;
501
+ }
502
+ catch (err) {
503
+ if (err instanceof Error) {
504
+ log.info(`Ignoring an error during query: ${err.message}`);
505
+ }
506
+ else {
507
+ log.info(`Ignoring an unknown error during query`);
508
+ }
214
509
  return defaultValue;
215
- });
510
+ }
216
511
  }
217
512
 
218
- export { RLNContract };
513
+ export { MembershipState, RLNContract };
@@ -17,7 +17,7 @@ class RlnMessage {
17
17
  }
18
18
  verify(roots) {
19
19
  return this.rateLimitProof
20
- ? this.rlnInstance.zerokit.verifyWithRoots(this.rateLimitProof, toRLNSignal(this.msg.contentTopic, this.msg), ...roots) // this.rlnInstance.verifyRLNProof once issue status-im/nwaku#1248 is fixed
20
+ ? this.rlnInstance.zerokit.verifyWithRoots(this.rateLimitProof, toRLNSignal(this.msg.contentTopic, this.msg), roots) // this.rlnInstance.verifyRLNProof once issue status-im/nwaku#1248 is fixed
21
21
  : undefined;
22
22
  }
23
23
  verifyNoRoot() {