-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathviem.ts
More file actions
411 lines (349 loc) · 14.2 KB
/
viem.ts
File metadata and controls
411 lines (349 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import {
SupportedNetwork,
defaultNetwork,
getDeployedContract,
isSupportedNetwork
} from "@semaphore-protocol/utils/networks"
import { SemaphoreABI } from "@semaphore-protocol/utils/constants"
import { requireString } from "@zk-kit/utils/error-handlers"
import {
Address,
createPublicClient,
http,
PublicClient,
getContract,
GetContractReturnType,
zeroAddress,
Transport,
Chain,
Log
} from "viem"
import { GroupResponse, ViemNetwork, ViemOptions } from "./types"
// Define types for the event logs to properly access args
type GroupCreatedLog = Log<bigint, number, boolean, any, any, any, "GroupCreated"> & {
args: {
groupId: bigint
}
}
type MemberRemovedLog = Log<bigint, number, boolean, any, any, any, "MemberRemoved"> & {
args: {
groupId: string
index: bigint
}
}
type MemberUpdatedLog = Log<bigint, number, boolean, any, any, any, "MemberUpdated"> & {
args: {
groupId: string
index: bigint
newIdentityCommitment: string
}
}
type MembersAddedLog = Log<bigint, number, boolean, any, any, any, "MembersAdded"> & {
args: {
groupId: string
startIndex: bigint
identityCommitments: string[]
}
}
type MemberAddedLog = Log<bigint, number, boolean, any, any, any, "MemberAdded"> & {
args: {
groupId: string
index: bigint
identityCommitment: string
}
}
type ProofValidatedLog = Log<bigint, number, boolean, any, any, any, "ProofValidated"> & {
args: {
groupId: string
message: string
merkleTreeRoot: string
merkleTreeDepth: string
scope: string
nullifier: string
x: string
y: string
}
}
/**
* The SemaphoreViem class provides a high-level interface to interact with the Semaphore smart contract
* using the {@link https://viem.sh | viem} library. It encapsulates all necessary functionalities to connect to Ethereum networks,
* manage contract instances, and perform operations such as retrieving group information or checking group memberships.
* This class simplifies the interaction with the Ethereum blockchain by abstracting the details of network connections
* and contract interactions.
*/
export default class SemaphoreViem {
private _network: ViemNetwork | string
private _options: ViemOptions
private _client: PublicClient
private _contract: GetContractReturnType<typeof SemaphoreABI, PublicClient>
/**
* Constructs a new SemaphoreViem instance, initializing it with a network or a custom Ethereum node URL,
* and optional configuration settings for the viem client and contract.
* @param networkOrEthereumURL The Ethereum network name or a custom JSON-RPC URL to connect to.
* @param options Configuration options for the viem client and the Semaphore contract.
*/
constructor(networkOrEthereumURL: ViemNetwork | string = defaultNetwork, options: ViemOptions = {}) {
requireString(networkOrEthereumURL, "networkOrEthereumURL")
if (options.apiKey) {
requireString(options.apiKey, "apiKey")
}
if (isSupportedNetwork(networkOrEthereumURL)) {
const { address, startBlock } = getDeployedContract(networkOrEthereumURL as SupportedNetwork)
options.address ??= address
options.startBlock ??= BigInt(startBlock)
} else {
options.startBlock ??= 0n
}
if (options.address === undefined) {
throw new Error(`Network '${networkOrEthereumURL}' needs a Semaphore contract address`)
}
let transport: Transport
if (options.transport) {
transport = options.transport
} else if (!networkOrEthereumURL.startsWith("http")) {
transport = http()
} else {
transport = http(networkOrEthereumURL)
}
this._network = networkOrEthereumURL
this._options = options
// Create the public client
this._client =
options.publicClient ??
createPublicClient({
transport,
chain: options.chain as Chain
})
// Create the contract instance
this._contract = getContract({
address: options.address as Address,
abi: SemaphoreABI,
client: this._client
})
}
/**
* Retrieves the Ethereum network or custom URL currently used by this instance.
* @returns The network or URL as a string.
*/
get network(): ViemNetwork | string {
return this._network
}
/**
* Retrieves the options used for configuring the viem client and the Semaphore contract.
* @returns The configuration options.
*/
get options(): ViemOptions {
return this._options
}
/**
* Retrieves the viem Contract instance used to interact with the Semaphore contract.
* @returns The Contract instance.
*/
get contract(): GetContractReturnType<typeof SemaphoreABI, PublicClient> {
return this._contract
}
/**
* Retrieves the viem Public Client instance used to interact with the blockchain.
* @returns The Public Client instance.
*/
get client(): PublicClient {
return this._client
}
/**
* Fetches the list of group IDs from the Semaphore contract by querying the "GroupCreated" events.
* @returns A promise that resolves to an array of group IDs as strings.
*/
async getGroupIds(): Promise<string[]> {
const logs = (await this._client.getContractEvents({
address: this._options.address as Address,
abi: SemaphoreABI,
eventName: "GroupCreated",
fromBlock: BigInt(this._options.startBlock || 0)
})) as GroupCreatedLog[]
return logs.map((log) => log.args.groupId.toString())
}
/**
* Retrieves detailed information about a specific group by its ID. This method queries the Semaphore contract
* to get the group's admin, Merkle tree root, depth, and size.
* @param groupId The unique identifier of the group.
* @returns A promise that resolves to a GroupResponse object.
*/
async getGroup(groupId: string): Promise<GroupResponse> {
requireString(groupId, "groupId")
const groupAdmin = await this._contract.read.getGroupAdmin([groupId])
if (groupAdmin === zeroAddress) {
throw new Error(`Group '${groupId}' not found`)
}
const merkleTreeRoot = await this._contract.read.getMerkleTreeRoot([groupId])
const merkleTreeDepth = await this._contract.read.getMerkleTreeDepth([groupId])
const merkleTreeSize = await this._contract.read.getMerkleTreeSize([groupId])
const group: GroupResponse = {
id: groupId,
admin: groupAdmin as string,
merkleTree: {
depth: Number(merkleTreeDepth),
size: Number(merkleTreeSize),
root: merkleTreeRoot ? merkleTreeRoot.toString() : ""
}
}
return group
}
/**
* Fetches a list of members from a specific group. This method queries the Semaphore contract for events
* related to member additions and updates, and constructs the list of current group members.
* @param groupId The unique identifier of the group.
* @returns A promise that resolves to an array of member identity commitments as strings.
*/
async getGroupMembers(groupId: string): Promise<string[]> {
requireString(groupId, "groupId")
const groupAdmin = await this._contract.read.getGroupAdmin([groupId])
if (groupAdmin === zeroAddress) {
throw new Error(`Group '${groupId}' not found`)
}
// Get member removed events
const memberRemovedEvents = (await this._client.getContractEvents({
address: this._options.address as Address,
abi: SemaphoreABI,
eventName: "MemberRemoved",
args: {
groupId: BigInt(groupId)
},
fromBlock: BigInt(this._options.startBlock || 0)
})) as MemberRemovedLog[]
// Get member updated events
const memberUpdatedEvents = (await this._client.getContractEvents({
address: this._options.address as Address,
abi: SemaphoreABI,
eventName: "MemberUpdated",
args: {
groupId: BigInt(groupId)
},
fromBlock: BigInt(this._options.startBlock || 0)
})) as MemberUpdatedLog[]
const memberUpdatedEventsMap = new Map<string, [bigint, string]>()
for (const event of memberUpdatedEvents) {
if (event.args.index && event.args.newIdentityCommitment && event.blockNumber) {
memberUpdatedEventsMap.set(event.args.index.toString(), [
event.blockNumber,
event.args.newIdentityCommitment.toString()
])
}
}
for (const event of memberRemovedEvents) {
if (event.args.index && event.blockNumber) {
const groupUpdate = memberUpdatedEventsMap.get(event.args.index.toString())
if (!groupUpdate || (groupUpdate && groupUpdate[0] < event.blockNumber)) {
memberUpdatedEventsMap.set(event.args.index.toString(), [event.blockNumber, "0"])
}
}
}
// Get members added events (batch additions)
const membersAddedEvents = (await this._client.getContractEvents({
address: this._options.address as Address,
abi: SemaphoreABI,
eventName: "MembersAdded",
args: {
groupId: BigInt(groupId)
},
fromBlock: BigInt(this._options.startBlock || 0)
})) as MembersAddedLog[]
const membersAddedEventsMap = new Map<string, string[]>()
for (const event of membersAddedEvents) {
if (event.args.startIndex && event.args.identityCommitments) {
membersAddedEventsMap.set(
event.args.startIndex.toString(),
event.args.identityCommitments.map((i) => i.toString())
)
}
}
// Get individual member added events
const memberAddedEvents = (await this._client.getContractEvents({
address: this._options.address as Address,
abi: SemaphoreABI,
eventName: "MemberAdded",
args: {
groupId: BigInt(groupId)
},
fromBlock: BigInt(this._options.startBlock || 0)
})) as MemberAddedLog[]
const members: string[] = []
const merkleTreeSize = await this._contract.read.getMerkleTreeSize([groupId])
let index = 0
while (index < Number(merkleTreeSize)) {
const identityCommitments = membersAddedEventsMap.get(index.toString())
if (identityCommitments) {
members.push(...identityCommitments)
index += identityCommitments.length
} else {
const currentIndex = index // Create a closure to capture the current index value
const event = memberAddedEvents.find((e) => Number(e.args.index) === currentIndex)
if (event && event.args.identityCommitment) {
members.push(event.args.identityCommitment.toString())
}
index += 1
}
}
// Apply updates to members
for (let j = 0; j < members.length; j += 1) {
const groupUpdate = memberUpdatedEventsMap.get(j.toString())
if (groupUpdate) {
members[j] = groupUpdate[1].toString()
}
}
return members
}
/**
* Fetches a list of validated proofs for a specific group. This method queries the Semaphore contract for events
* related to proof verification.
* @param groupId The unique identifier of the group.
* @returns A promise that resolves to an array of validated proofs.
*/
async getGroupValidatedProofs(groupId: string): Promise<any> {
requireString(groupId, "groupId")
const groupAdmin = await this._contract.read.getGroupAdmin([groupId])
if (groupAdmin === zeroAddress) {
throw new Error(`Group '${groupId}' not found`)
}
const proofValidatedEvents = (await this._client.getContractEvents({
address: this._options.address as Address,
abi: SemaphoreABI,
eventName: "ProofValidated",
args: {
groupId: BigInt(groupId)
},
fromBlock: BigInt(this._options.startBlock || 0)
})) as ProofValidatedLog[]
return Promise.all(
proofValidatedEvents.map(async (event) => {
let timestamp: string | undefined
if (event.blockNumber !== null && event.blockNumber !== undefined) {
const block = await this._client.getBlock({ blockNumber: event.blockNumber })
if (block?.timestamp !== undefined) {
timestamp = new Date(Number(block.timestamp) * 1000).toISOString()
}
}
return {
message: event.args.message?.toString() || "",
merkleTreeRoot: event.args.merkleTreeRoot?.toString() || "",
merkleTreeDepth: event.args.merkleTreeDepth?.toString() || "",
scope: event.args.scope?.toString() || "",
nullifier: event.args.nullifier?.toString() || "",
points: [event.args.x?.toString() || "", event.args.y?.toString() || ""],
timestamp
}
})
)
}
/**
* Checks if a given identity commitment is a member of a specific group.
* @param groupId The unique identifier of the group.
* @param member The identity commitment to check.
* @returns A promise that resolves to a boolean indicating whether the member is in the group.
*/
async isGroupMember(groupId: string, member: string): Promise<boolean> {
requireString(groupId, "groupId")
requireString(member, "member")
const members = await this.getGroupMembers(groupId)
return members.includes(member)
}
}