@waku/rln 0.0.2-09108d9.0 → 0.0.2-3670e82.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.
- package/bundle/_virtual/utils.js +2 -2
- package/bundle/_virtual/utils2.js +2 -2
- package/bundle/index.js +2 -1
- package/bundle/packages/rln/dist/contract/abi.js +648 -0
- package/bundle/packages/rln/dist/contract/constants.js +25 -65
- package/bundle/packages/rln/dist/contract/rln_contract.js +365 -74
- package/bundle/packages/rln/dist/message.js +1 -1
- package/bundle/packages/rln/dist/rln.js +36 -20
- package/bundle/packages/rln/dist/zerokit.js +34 -14
- package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/random.js +1 -1
- package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/utils.js +2 -2
- package/bundle/packages/rln/node_modules/@noble/hashes/_sha2.js +1 -1
- package/bundle/packages/rln/node_modules/@noble/hashes/hmac.js +1 -1
- package/bundle/packages/rln/node_modules/@noble/hashes/pbkdf2.js +1 -1
- package/bundle/packages/rln/node_modules/@noble/hashes/scrypt.js +1 -1
- package/bundle/packages/rln/node_modules/@noble/hashes/sha256.js +1 -1
- package/bundle/packages/rln/node_modules/@noble/hashes/sha512.js +1 -1
- package/bundle/packages/rln/node_modules/@noble/hashes/utils.js +1 -1
- package/dist/.tsbuildinfo +1 -1
- package/dist/contract/abi.d.ts +46 -0
- package/dist/contract/abi.js +647 -0
- package/dist/contract/abi.js.map +1 -0
- package/dist/contract/constants.d.ts +63 -3
- package/dist/contract/constants.js +23 -64
- package/dist/contract/constants.js.map +1 -1
- package/dist/contract/rln_contract.d.ts +100 -17
- package/dist/contract/rln_contract.js +364 -72
- package/dist/contract/rln_contract.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/message.js +1 -1
- package/dist/message.js.map +1 -1
- package/dist/rln.d.ts +5 -1
- package/dist/rln.js +36 -19
- package/dist/rln.js.map +1 -1
- package/dist/zerokit.d.ts +10 -6
- package/dist/zerokit.js +34 -14
- package/dist/zerokit.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/abi.ts +646 -0
- package/src/contract/constants.ts +26 -65
- package/src/contract/rln_contract.ts +578 -108
- package/src/index.ts +4 -9
- package/src/message.ts +1 -1
- package/src/rln.ts +57 -21
- package/src/zerokit.ts +74 -15
@@ -1,68 +1,28 @@
|
|
1
|
-
|
2
|
-
|
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:
|
64
|
-
|
65
|
-
|
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 {
|
28
|
+
export { DEFAULT_RATE_LIMIT, RATE_LIMIT_PARAMS, RATE_LIMIT_TIERS, SEPOLIA_CONTRACT };
|
@@ -5,56 +5,122 @@ 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 '
|
9
|
-
import {
|
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 {
|
11
|
+
import { BigNumber } from '../../../../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js';
|
12
12
|
|
13
|
+
/* eslint-disable no-console */
|
13
14
|
const log = new Logger("waku:rln:contract");
|
15
|
+
var MembershipState;
|
16
|
+
(function (MembershipState) {
|
17
|
+
MembershipState["Active"] = "Active";
|
18
|
+
MembershipState["GracePeriod"] = "GracePeriod";
|
19
|
+
MembershipState["Expired"] = "Expired";
|
20
|
+
MembershipState["ErasedAwaitsWithdrawal"] = "ErasedAwaitsWithdrawal";
|
21
|
+
})(MembershipState || (MembershipState = {}));
|
14
22
|
class RLNContract {
|
15
|
-
|
23
|
+
contract;
|
16
24
|
merkleRootTracker;
|
17
25
|
deployBlock;
|
18
|
-
|
19
|
-
storageContract;
|
20
|
-
_membersFilter;
|
26
|
+
rateLimit;
|
21
27
|
_members = new Map();
|
28
|
+
_membersFilter;
|
29
|
+
_membersRemovedFilter;
|
30
|
+
_membersExpiredFilter;
|
31
|
+
/**
|
32
|
+
* Asynchronous initializer for RLNContract.
|
33
|
+
* Allows injecting a mocked contract for testing purposes.
|
34
|
+
*/
|
22
35
|
static async init(rlnInstance, options) {
|
23
36
|
const rlnContract = new RLNContract(rlnInstance, options);
|
24
|
-
await rlnContract.initStorageContract(options.signer);
|
25
37
|
await rlnContract.fetchMembers(rlnInstance);
|
26
38
|
rlnContract.subscribeToMembers(rlnInstance);
|
27
39
|
return rlnContract;
|
28
40
|
}
|
29
|
-
constructor(rlnInstance,
|
41
|
+
constructor(rlnInstance, options) {
|
42
|
+
const { address, signer, rateLimit = DEFAULT_RATE_LIMIT, contract } = options;
|
43
|
+
if (rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
|
44
|
+
rateLimit > RATE_LIMIT_PARAMS.MAX_RATE) {
|
45
|
+
throw new Error(`Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE} messages per epoch`);
|
46
|
+
}
|
47
|
+
this.rateLimit = rateLimit;
|
30
48
|
const initialRoot = rlnInstance.zerokit.getMerkleRoot();
|
31
|
-
|
49
|
+
// Use the injected contract if provided; otherwise, instantiate a new one.
|
50
|
+
this.contract = contract || new Contract(address, RLN_ABI, signer);
|
32
51
|
this.merkleRootTracker = new MerkleRootTracker(5, initialRoot);
|
52
|
+
// Initialize event filters
|
53
|
+
this._membersFilter = this.contract.filters.MembershipRegistered();
|
54
|
+
this._membersRemovedFilter = this.contract.filters.MembershipErased();
|
55
|
+
this._membersExpiredFilter = this.contract.filters.MembershipExpired();
|
33
56
|
}
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
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();
|
57
|
+
/**
|
58
|
+
* Gets the current rate limit for this contract instance
|
59
|
+
*/
|
60
|
+
getRateLimit() {
|
61
|
+
return this.rateLimit;
|
46
62
|
}
|
47
|
-
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
return this.
|
63
|
+
/**
|
64
|
+
* Gets the contract address
|
65
|
+
*/
|
66
|
+
get address() {
|
67
|
+
return this.contract.address;
|
52
68
|
}
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
return this.
|
69
|
+
/**
|
70
|
+
* Gets the contract provider
|
71
|
+
*/
|
72
|
+
get provider() {
|
73
|
+
return this.contract.provider;
|
74
|
+
}
|
75
|
+
/**
|
76
|
+
* Gets the minimum allowed rate limit from the contract
|
77
|
+
* @returns Promise<number> The minimum rate limit in messages per epoch
|
78
|
+
*/
|
79
|
+
async getMinRateLimit() {
|
80
|
+
const minRate = await this.contract.minMembershipRateLimit();
|
81
|
+
return minRate.toNumber();
|
82
|
+
}
|
83
|
+
/**
|
84
|
+
* Gets the maximum allowed rate limit from the contract
|
85
|
+
* @returns Promise<number> The maximum rate limit in messages per epoch
|
86
|
+
*/
|
87
|
+
async getMaxRateLimit() {
|
88
|
+
const maxRate = await this.contract.maxMembershipRateLimit();
|
89
|
+
return maxRate.toNumber();
|
90
|
+
}
|
91
|
+
/**
|
92
|
+
* Gets the maximum total rate limit across all memberships
|
93
|
+
* @returns Promise<number> The maximum total rate limit in messages per epoch
|
94
|
+
*/
|
95
|
+
async getMaxTotalRateLimit() {
|
96
|
+
const maxTotalRate = await this.contract.maxTotalRateLimit();
|
97
|
+
return maxTotalRate.toNumber();
|
98
|
+
}
|
99
|
+
/**
|
100
|
+
* Gets the current total rate limit usage across all memberships
|
101
|
+
* @returns Promise<number> The current total rate limit usage in messages per epoch
|
102
|
+
*/
|
103
|
+
async getCurrentTotalRateLimit() {
|
104
|
+
const currentTotal = await this.contract.currentTotalRateLimit();
|
105
|
+
return currentTotal.toNumber();
|
106
|
+
}
|
107
|
+
/**
|
108
|
+
* Gets the remaining available total rate limit that can be allocated
|
109
|
+
* @returns Promise<number> The remaining rate limit that can be allocated
|
110
|
+
*/
|
111
|
+
async getRemainingTotalRateLimit() {
|
112
|
+
const [maxTotal, currentTotal] = await Promise.all([
|
113
|
+
this.contract.maxTotalRateLimit(),
|
114
|
+
this.contract.currentTotalRateLimit()
|
115
|
+
]);
|
116
|
+
return maxTotal.sub(currentTotal).toNumber();
|
117
|
+
}
|
118
|
+
/**
|
119
|
+
* Updates the rate limit for future registrations
|
120
|
+
* @param newRateLimit The new rate limit to use
|
121
|
+
*/
|
122
|
+
async setRateLimit(newRateLimit) {
|
123
|
+
this.rateLimit = newRateLimit;
|
58
124
|
}
|
59
125
|
get members() {
|
60
126
|
const sortedMembers = Array.from(this._members.values()).sort((left, right) => left.index.toNumber() - right.index.toNumber());
|
@@ -66,13 +132,40 @@ class RLNContract {
|
|
66
132
|
}
|
67
133
|
return this._membersFilter;
|
68
134
|
}
|
135
|
+
get membersRemovedFilter() {
|
136
|
+
if (!this._membersRemovedFilter) {
|
137
|
+
throw Error("MembersErased filter was not initialized.");
|
138
|
+
}
|
139
|
+
return this._membersRemovedFilter;
|
140
|
+
}
|
141
|
+
get membersExpiredFilter() {
|
142
|
+
if (!this._membersExpiredFilter) {
|
143
|
+
throw Error("MembersExpired filter was not initialized.");
|
144
|
+
}
|
145
|
+
return this._membersExpiredFilter;
|
146
|
+
}
|
69
147
|
async fetchMembers(rlnInstance, options = {}) {
|
70
148
|
const registeredMemberEvents = await queryFilter(this.contract, {
|
71
149
|
fromBlock: this.deployBlock,
|
72
150
|
...options,
|
73
151
|
membersFilter: this.membersFilter
|
74
152
|
});
|
75
|
-
this.
|
153
|
+
const removedMemberEvents = await queryFilter(this.contract, {
|
154
|
+
fromBlock: this.deployBlock,
|
155
|
+
...options,
|
156
|
+
membersFilter: this.membersRemovedFilter
|
157
|
+
});
|
158
|
+
const expiredMemberEvents = await queryFilter(this.contract, {
|
159
|
+
fromBlock: this.deployBlock,
|
160
|
+
...options,
|
161
|
+
membersFilter: this.membersExpiredFilter
|
162
|
+
});
|
163
|
+
const events = [
|
164
|
+
...registeredMemberEvents,
|
165
|
+
...removedMemberEvents,
|
166
|
+
...expiredMemberEvents
|
167
|
+
];
|
168
|
+
this.processEvents(rlnInstance, events);
|
76
169
|
}
|
77
170
|
processEvents(rlnInstance, events) {
|
78
171
|
const toRemoveTable = new Map();
|
@@ -81,8 +174,17 @@ class RLNContract {
|
|
81
174
|
if (!evt.args) {
|
82
175
|
return;
|
83
176
|
}
|
84
|
-
if (evt.
|
85
|
-
|
177
|
+
if (evt.event === "MembershipErased" ||
|
178
|
+
evt.event === "MembershipExpired") {
|
179
|
+
// Both MembershipErased and MembershipExpired events should remove members
|
180
|
+
let index = evt.args.index;
|
181
|
+
if (!index) {
|
182
|
+
return;
|
183
|
+
}
|
184
|
+
// Convert index to ethers.BigNumber if it's not already
|
185
|
+
if (typeof index === "number" || typeof index === "string") {
|
186
|
+
index = BigNumber.from(index);
|
187
|
+
}
|
86
188
|
const toRemoveVal = toRemoveTable.get(evt.blockNumber);
|
87
189
|
if (toRemoveVal != undefined) {
|
88
190
|
toRemoveVal.push(index.toNumber());
|
@@ -92,7 +194,7 @@ class RLNContract {
|
|
92
194
|
toRemoveTable.set(evt.blockNumber, [index.toNumber()]);
|
93
195
|
}
|
94
196
|
}
|
95
|
-
else {
|
197
|
+
else if (evt.event === "MembershipRegistered") {
|
96
198
|
let eventsPerBlock = toInsertTable.get(evt.blockNumber);
|
97
199
|
if (eventsPerBlock == undefined) {
|
98
200
|
eventsPerBlock = [];
|
@@ -107,16 +209,25 @@ class RLNContract {
|
|
107
209
|
insertMembers(rlnInstance, toInsert) {
|
108
210
|
toInsert.forEach((events, blockNumber) => {
|
109
211
|
events.forEach((evt) => {
|
110
|
-
|
111
|
-
|
212
|
+
if (!evt.args)
|
213
|
+
return;
|
214
|
+
const _idCommitment = evt.args.idCommitment;
|
215
|
+
let index = evt.args.index;
|
216
|
+
// Ensure index is an ethers.BigNumber
|
112
217
|
if (!_idCommitment || !index) {
|
113
218
|
return;
|
114
219
|
}
|
115
|
-
|
220
|
+
// Convert index to ethers.BigNumber if it's not already
|
221
|
+
if (typeof index === "number" || typeof index === "string") {
|
222
|
+
index = BigNumber.from(index);
|
223
|
+
}
|
224
|
+
const idCommitment = zeroPadLE(hexToBytes(_idCommitment), 32);
|
116
225
|
rlnInstance.zerokit.insertMember(idCommitment);
|
117
|
-
|
118
|
-
|
119
|
-
|
226
|
+
// Always store the numeric index as the key, but the BigNumber as the value
|
227
|
+
const numericIndex = index.toNumber();
|
228
|
+
this._members.set(numericIndex, {
|
229
|
+
index, // This is always a BigNumber
|
230
|
+
idCommitment: _idCommitment
|
120
231
|
});
|
121
232
|
});
|
122
233
|
const currentRoot = rlnInstance.zerokit.getMerkleRoot();
|
@@ -124,7 +235,7 @@ class RLNContract {
|
|
124
235
|
});
|
125
236
|
}
|
126
237
|
removeMembers(rlnInstance, toRemove) {
|
127
|
-
const removeDescending = new Map([...toRemove].
|
238
|
+
const removeDescending = new Map([...toRemove].reverse());
|
128
239
|
removeDescending.forEach((indexes, blockNumber) => {
|
129
240
|
indexes.forEach((index) => {
|
130
241
|
if (this._members.has(index)) {
|
@@ -136,50 +247,222 @@ class RLNContract {
|
|
136
247
|
});
|
137
248
|
}
|
138
249
|
subscribeToMembers(rlnInstance) {
|
139
|
-
this.contract.on(this.membersFilter, (
|
250
|
+
this.contract.on(this.membersFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
|
251
|
+
this.processEvents(rlnInstance, [event]);
|
252
|
+
});
|
253
|
+
this.contract.on(this.membersRemovedFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
|
254
|
+
this.processEvents(rlnInstance, [event]);
|
255
|
+
});
|
256
|
+
this.contract.on(this.membersExpiredFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
|
257
|
+
this.processEvents(rlnInstance, [event]);
|
258
|
+
});
|
140
259
|
}
|
141
260
|
async registerWithIdentity(identity) {
|
142
|
-
|
143
|
-
|
144
|
-
|
145
|
-
|
146
|
-
|
147
|
-
|
148
|
-
|
149
|
-
|
261
|
+
try {
|
262
|
+
console.log("registerWithIdentity - starting registration process");
|
263
|
+
console.log("registerWithIdentity - identity:", identity);
|
264
|
+
console.log("registerWithIdentity - IDCommitmentBigInt:", identity.IDCommitmentBigInt.toString());
|
265
|
+
console.log("registerWithIdentity - rate limit:", this.rateLimit);
|
266
|
+
log.info(`Registering identity with rate limit: ${this.rateLimit} messages/epoch`);
|
267
|
+
console.log("registerWithIdentity - calling contract.register");
|
268
|
+
const txRegisterResponse = await this.contract.register(identity.IDCommitmentBigInt, this.rateLimit, [], { gasLimit: 300000 });
|
269
|
+
console.log("registerWithIdentity - txRegisterResponse:", txRegisterResponse);
|
270
|
+
console.log("registerWithIdentity - hash:", txRegisterResponse.hash);
|
271
|
+
console.log("registerWithIdentity - waiting for transaction confirmation...");
|
272
|
+
const txRegisterReceipt = await txRegisterResponse.wait();
|
273
|
+
console.log("registerWithIdentity - txRegisterReceipt:", txRegisterReceipt);
|
274
|
+
console.log("registerWithIdentity - transaction status:", txRegisterReceipt.status);
|
275
|
+
console.log("registerWithIdentity - block number:", txRegisterReceipt.blockNumber);
|
276
|
+
console.log("registerWithIdentity - gas used:", txRegisterReceipt.gasUsed.toString());
|
277
|
+
const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
|
278
|
+
console.log("registerWithIdentity - memberRegistered event:", memberRegistered);
|
279
|
+
if (!memberRegistered || !memberRegistered.args) {
|
280
|
+
console.log("registerWithIdentity - ERROR: no memberRegistered event found");
|
281
|
+
console.log("registerWithIdentity - all events:", txRegisterReceipt.events);
|
282
|
+
log.error("Failed to register membership: No MembershipRegistered event found");
|
283
|
+
return undefined;
|
284
|
+
}
|
285
|
+
console.log("registerWithIdentity - memberRegistered args:", memberRegistered.args);
|
286
|
+
const decodedData = {
|
287
|
+
idCommitment: memberRegistered.args.idCommitment,
|
288
|
+
membershipRateLimit: memberRegistered.args.membershipRateLimit,
|
289
|
+
index: memberRegistered.args.index
|
290
|
+
};
|
291
|
+
console.log("registerWithIdentity - decodedData:", decodedData);
|
292
|
+
console.log("registerWithIdentity - index:", decodedData.index.toString());
|
293
|
+
console.log("registerWithIdentity - membershipRateLimit:", decodedData.membershipRateLimit.toString());
|
294
|
+
log.info(`Successfully registered membership with index ${decodedData.index} ` +
|
295
|
+
`and rate limit ${decodedData.membershipRateLimit}`);
|
296
|
+
console.log("registerWithIdentity - getting network information");
|
297
|
+
const network = await this.contract.provider.getNetwork();
|
298
|
+
console.log("registerWithIdentity - network:", network);
|
299
|
+
console.log("registerWithIdentity - chainId:", network.chainId);
|
300
|
+
const address = this.contract.address;
|
301
|
+
console.log("registerWithIdentity - contract address:", address);
|
302
|
+
const membershipId = decodedData.index.toNumber();
|
303
|
+
console.log("registerWithIdentity - membershipId:", membershipId);
|
304
|
+
const result = {
|
305
|
+
identity,
|
306
|
+
membership: {
|
307
|
+
address,
|
308
|
+
treeIndex: membershipId,
|
309
|
+
chainId: network.chainId
|
310
|
+
}
|
311
|
+
};
|
312
|
+
console.log("registerWithIdentity - returning result:", result);
|
313
|
+
return result;
|
314
|
+
}
|
315
|
+
catch (error) {
|
316
|
+
console.log("registerWithIdentity - ERROR:", error);
|
317
|
+
console.log("registerWithIdentity - error message:", error.message);
|
318
|
+
console.log("registerWithIdentity - error stack:", error.stack);
|
319
|
+
log.error(`Error in registerWithIdentity: ${error.message}`);
|
150
320
|
return undefined;
|
151
321
|
}
|
152
|
-
|
153
|
-
|
154
|
-
|
155
|
-
|
156
|
-
|
157
|
-
|
158
|
-
|
159
|
-
|
160
|
-
|
161
|
-
|
322
|
+
}
|
323
|
+
/**
|
324
|
+
* Helper method to get remaining messages in current epoch
|
325
|
+
* @param membershipId The ID of the membership to check
|
326
|
+
* @returns number of remaining messages allowed in current epoch
|
327
|
+
*/
|
328
|
+
async getRemainingMessages(membershipId) {
|
329
|
+
try {
|
330
|
+
const [startTime, , rateLimit] = await this.contract.getMembershipInfo(membershipId);
|
331
|
+
// Calculate current epoch
|
332
|
+
const currentTime = Math.floor(Date.now() / 1000);
|
333
|
+
const epochsPassed = Math.floor((currentTime - startTime) / RATE_LIMIT_PARAMS.EPOCH_LENGTH);
|
334
|
+
const currentEpochStart = startTime + epochsPassed * RATE_LIMIT_PARAMS.EPOCH_LENGTH;
|
335
|
+
// Get message count in current epoch using contract's function
|
336
|
+
const messageCount = await this.contract.getMessageCount(membershipId, currentEpochStart);
|
337
|
+
return Math.max(0, rateLimit.sub(messageCount).toNumber());
|
338
|
+
}
|
339
|
+
catch (error) {
|
340
|
+
log.error(`Error getting remaining messages: ${error.message}`);
|
341
|
+
return 0; // Fail safe: assume no messages remaining on error
|
342
|
+
}
|
343
|
+
}
|
344
|
+
async registerWithPermitAndErase(identity, permit, idCommitmentsToErase) {
|
345
|
+
try {
|
346
|
+
log.info(`Registering identity with permit and rate limit: ${this.rateLimit} messages/epoch`);
|
347
|
+
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)));
|
348
|
+
const txRegisterReceipt = await txRegisterResponse.wait();
|
349
|
+
const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
|
350
|
+
if (!memberRegistered || !memberRegistered.args) {
|
351
|
+
log.error("Failed to register membership with permit: No MembershipRegistered event found");
|
352
|
+
return undefined;
|
162
353
|
}
|
163
|
-
|
354
|
+
const decodedData = {
|
355
|
+
idCommitment: memberRegistered.args.idCommitment,
|
356
|
+
membershipRateLimit: memberRegistered.args.membershipRateLimit,
|
357
|
+
index: memberRegistered.args.index
|
358
|
+
};
|
359
|
+
log.info(`Successfully registered membership with permit. Index: ${decodedData.index}, ` +
|
360
|
+
`Rate limit: ${decodedData.membershipRateLimit}, Erased ${idCommitmentsToErase.length} commitments`);
|
361
|
+
const network = await this.contract.provider.getNetwork();
|
362
|
+
const address = this.contract.address;
|
363
|
+
const membershipId = decodedData.index.toNumber();
|
364
|
+
return {
|
365
|
+
identity,
|
366
|
+
membership: {
|
367
|
+
address,
|
368
|
+
treeIndex: membershipId,
|
369
|
+
chainId: network.chainId
|
370
|
+
}
|
371
|
+
};
|
372
|
+
}
|
373
|
+
catch (error) {
|
374
|
+
log.error(`Error in registerWithPermitAndErase: ${error.message}`);
|
375
|
+
return undefined;
|
376
|
+
}
|
164
377
|
}
|
165
378
|
roots() {
|
166
379
|
return this.merkleRootTracker.roots();
|
167
380
|
}
|
381
|
+
async withdraw(token, holder) {
|
382
|
+
try {
|
383
|
+
const tx = await this.contract.withdraw(token, { from: holder });
|
384
|
+
await tx.wait();
|
385
|
+
}
|
386
|
+
catch (error) {
|
387
|
+
log.error(`Error in withdraw: ${error.message}`);
|
388
|
+
}
|
389
|
+
}
|
390
|
+
async getMembershipInfo(idCommitment) {
|
391
|
+
try {
|
392
|
+
const [startBlock, endBlock, rateLimit] = await this.contract.getMembershipInfo(idCommitment);
|
393
|
+
const currentBlock = await this.contract.provider.getBlockNumber();
|
394
|
+
let state;
|
395
|
+
if (currentBlock < startBlock) {
|
396
|
+
state = MembershipState.Active;
|
397
|
+
}
|
398
|
+
else if (currentBlock < endBlock) {
|
399
|
+
state = MembershipState.GracePeriod;
|
400
|
+
}
|
401
|
+
else {
|
402
|
+
state = MembershipState.Expired;
|
403
|
+
}
|
404
|
+
const index = await this.getMemberIndex(idCommitment);
|
405
|
+
if (!index)
|
406
|
+
return undefined;
|
407
|
+
return {
|
408
|
+
index,
|
409
|
+
idCommitment,
|
410
|
+
rateLimit: rateLimit.toNumber(),
|
411
|
+
startBlock: startBlock.toNumber(),
|
412
|
+
endBlock: endBlock.toNumber(),
|
413
|
+
state
|
414
|
+
};
|
415
|
+
}
|
416
|
+
catch (error) {
|
417
|
+
return undefined;
|
418
|
+
}
|
419
|
+
}
|
420
|
+
async extendMembership(idCommitment) {
|
421
|
+
const tx = await this.contract.extendMemberships([idCommitment]);
|
422
|
+
return await tx.wait();
|
423
|
+
}
|
424
|
+
async eraseMembership(idCommitment, eraseFromMembershipSet = true) {
|
425
|
+
const tx = await this.contract.eraseMemberships([idCommitment], eraseFromMembershipSet);
|
426
|
+
return await tx.wait();
|
427
|
+
}
|
428
|
+
async registerMembership(idCommitment, rateLimit = DEFAULT_RATE_LIMIT) {
|
429
|
+
if (rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
|
430
|
+
rateLimit > RATE_LIMIT_PARAMS.MAX_RATE) {
|
431
|
+
throw new Error(`Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE}`);
|
432
|
+
}
|
433
|
+
console.log("registering membership", idCommitment, rateLimit);
|
434
|
+
const txn = this.contract.register(idCommitment, rateLimit, []);
|
435
|
+
console.log("txn", txn);
|
436
|
+
return txn;
|
437
|
+
}
|
438
|
+
async getMemberIndex(idCommitment) {
|
439
|
+
try {
|
440
|
+
const events = await this.contract.queryFilter(this.contract.filters.MembershipRegistered(idCommitment));
|
441
|
+
if (events.length === 0)
|
442
|
+
return undefined;
|
443
|
+
// Get the most recent registration event
|
444
|
+
const event = events[events.length - 1];
|
445
|
+
return event.args?.index;
|
446
|
+
}
|
447
|
+
catch (error) {
|
448
|
+
return undefined;
|
449
|
+
}
|
450
|
+
}
|
168
451
|
}
|
169
|
-
//
|
452
|
+
// These values should be tested on other networks
|
170
453
|
const FETCH_CHUNK = 5;
|
171
454
|
const BLOCK_RANGE = 3000;
|
172
455
|
async function queryFilter(contract, options) {
|
173
456
|
const { fromBlock, membersFilter, fetchRange = BLOCK_RANGE, fetchChunks = FETCH_CHUNK } = options;
|
174
|
-
if (
|
457
|
+
if (fromBlock === undefined) {
|
175
458
|
return contract.queryFilter(membersFilter);
|
176
459
|
}
|
177
|
-
if (!contract.
|
178
|
-
throw Error("No provider found on the contract
|
460
|
+
if (!contract.provider) {
|
461
|
+
throw Error("No provider found on the contract.");
|
179
462
|
}
|
180
|
-
const toBlock = await contract.
|
463
|
+
const toBlock = await contract.provider.getBlockNumber();
|
181
464
|
if (toBlock - fromBlock < fetchRange) {
|
182
|
-
return contract.queryFilter(membersFilter);
|
465
|
+
return contract.queryFilter(membersFilter, fromBlock, toBlock);
|
183
466
|
}
|
184
467
|
const events = [];
|
185
468
|
const chunks = splitToChunks(fromBlock, toBlock, fetchRange);
|
@@ -208,11 +491,19 @@ function* takeN(array, size) {
|
|
208
491
|
start += size;
|
209
492
|
}
|
210
493
|
}
|
211
|
-
function ignoreErrors(promise, defaultValue) {
|
212
|
-
|
213
|
-
|
494
|
+
async function ignoreErrors(promise, defaultValue) {
|
495
|
+
try {
|
496
|
+
return await promise;
|
497
|
+
}
|
498
|
+
catch (err) {
|
499
|
+
if (err instanceof Error) {
|
500
|
+
log.info(`Ignoring an error during query: ${err.message}`);
|
501
|
+
}
|
502
|
+
else {
|
503
|
+
log.info(`Ignoring an unknown error during query`);
|
504
|
+
}
|
214
505
|
return defaultValue;
|
215
|
-
}
|
506
|
+
}
|
216
507
|
}
|
217
508
|
|
218
|
-
export { RLNContract };
|
509
|
+
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),
|
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() {
|