@vocdoni/davinci-sdk 0.0.1

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.
@@ -0,0 +1,512 @@
1
+ import { ContractTransactionResponse, ContractRunner } from 'ethers';
2
+ import * as _vocdoni_davinci_contracts_dist_src_ProcessRegistry from '@vocdoni/davinci-contracts/dist/src/ProcessRegistry';
3
+
4
+ /**
5
+ * Interface defining the structure of deployed contract addresses across different networks.
6
+ * Each contract has addresses for both Sepolia testnet and Ethereum mainnet.
7
+ */
8
+ interface DeployedAddresses {
9
+ /** Process Registry contract addresses */
10
+ processRegistry: {
11
+ /** Sepolia testnet address */
12
+ sepolia: string;
13
+ /** Ethereum mainnet address */
14
+ mainnet: string;
15
+ };
16
+ /** Organization Registry contract addresses */
17
+ organizationRegistry: {
18
+ /** Sepolia testnet address */
19
+ sepolia: string;
20
+ /** Ethereum mainnet address */
21
+ mainnet: string;
22
+ };
23
+ /** State Transition Verifier contract addresses */
24
+ stateTransitionVerifierGroth16: {
25
+ /** Sepolia testnet address */
26
+ sepolia: string;
27
+ /** Ethereum mainnet address */
28
+ mainnet: string;
29
+ };
30
+ /** Results Verifier contract addresses */
31
+ resultsVerifierGroth16: {
32
+ /** Sepolia testnet address */
33
+ sepolia: string;
34
+ /** Ethereum mainnet address */
35
+ mainnet: string;
36
+ };
37
+ /** Sequencer Registry contract addresses */
38
+ sequencerRegistry: {
39
+ /** Sepolia testnet address */
40
+ sepolia: string;
41
+ /** Ethereum mainnet address */
42
+ mainnet: string;
43
+ };
44
+ }
45
+ /**
46
+ * Deployed contract addresses imported from @vocdoni/davinci-contracts package.
47
+ * These addresses are used to interact with the Vocdoni voting protocol contracts
48
+ * on different networks.
49
+ */
50
+ declare const deployedAddresses: DeployedAddresses;
51
+ /**
52
+ * Enum representing the possible states of a transaction during its lifecycle.
53
+ * Used to track and report transaction status in the event stream.
54
+ */
55
+ declare enum TxStatus {
56
+ /** Transaction has been submitted and is waiting to be mined */
57
+ Pending = "pending",
58
+ /** Transaction has been successfully mined and executed */
59
+ Completed = "completed",
60
+ /** Transaction was mined but reverted during execution */
61
+ Reverted = "reverted",
62
+ /** Transaction failed before or during submission */
63
+ Failed = "failed"
64
+ }
65
+ /**
66
+ * Union type representing the different events that can occur during a transaction's lifecycle.
67
+ * Each event includes relevant data based on the transaction status.
68
+ *
69
+ * @template T - The type of the successful response data
70
+ */
71
+ type TxStatusEvent<T = any> = {
72
+ status: TxStatus.Pending;
73
+ hash: string;
74
+ } | {
75
+ status: TxStatus.Completed;
76
+ response: T;
77
+ } | {
78
+ status: TxStatus.Reverted;
79
+ reason?: string;
80
+ } | {
81
+ status: TxStatus.Failed;
82
+ error: Error;
83
+ };
84
+ /**
85
+ * Abstract base class providing common functionality for smart contract interactions.
86
+ * Implements transaction handling, status monitoring, and event normalization.
87
+ */
88
+ declare abstract class SmartContractService {
89
+ /**
90
+ * Sends a transaction and yields status events during its lifecycle.
91
+ * This method handles the complete transaction flow from submission to completion,
92
+ * including error handling and status updates.
93
+ *
94
+ * @template T - The type of the successful response data
95
+ * @param txPromise - Promise resolving to the transaction response
96
+ * @param responseHandler - Function to process the successful transaction result
97
+ * @returns AsyncGenerator yielding transaction status events
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * const txStream = await this.sendTx(
102
+ * contract.someMethod(),
103
+ * async () => await contract.getUpdatedValue()
104
+ * );
105
+ *
106
+ * for await (const event of txStream) {
107
+ * switch (event.status) {
108
+ * case TxStatus.Pending:
109
+ * console.log(`Transaction pending: ${event.hash}`);
110
+ * break;
111
+ * case TxStatus.Completed:
112
+ * console.log(`Transaction completed:`, event.response);
113
+ * break;
114
+ * }
115
+ * }
116
+ * ```
117
+ */
118
+ protected sendTx<T>(txPromise: Promise<ContractTransactionResponse>, responseHandler: () => Promise<T>): AsyncGenerator<TxStatusEvent<T>, void, unknown>;
119
+ /**
120
+ * Executes a transaction stream and returns the result or throws an error.
121
+ * This is a convenience method that processes a transaction stream and either
122
+ * returns the successful result or throws an appropriate error.
123
+ *
124
+ * @template T - The type of the successful response data
125
+ * @param stream - AsyncGenerator of transaction status events
126
+ * @returns Promise resolving to the successful response data
127
+ * @throws Error if the transaction fails or reverts
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * try {
132
+ * const result = await SmartContractService.executeTx(
133
+ * contract.someMethod()
134
+ * );
135
+ * console.log('Transaction successful:', result);
136
+ * } catch (error) {
137
+ * console.error('Transaction failed:', error);
138
+ * }
139
+ * ```
140
+ */
141
+ static executeTx<T>(stream: AsyncGenerator<TxStatusEvent<T>>): Promise<T>;
142
+ /**
143
+ * Normalizes event listener arguments between different ethers.js versions.
144
+ * This helper method ensures consistent event argument handling regardless of
145
+ * whether the event payload follows ethers v5 or v6 format.
146
+ *
147
+ * @template Args - Tuple type representing the expected event arguments
148
+ * @param callback - The event callback function to normalize
149
+ * @returns Normalized event listener function
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * contract.on('Transfer', this.normalizeListener((from: string, to: string, amount: BigInt) => {
154
+ * console.log(`Transfer from ${from} to ${to}: ${amount}`);
155
+ * }));
156
+ * ```
157
+ */
158
+ protected normalizeListener<Args extends any[]>(callback: (...args: Args) => void): (...listenerArgs: any[]) => void;
159
+ }
160
+
161
+ /**
162
+ * @fileoverview Standardized error classes for contract services
163
+ *
164
+ * This module provides a consistent error hierarchy for all contract service operations.
165
+ * All errors extend from ContractServiceError and include operation context for better debugging.
166
+ */
167
+ /**
168
+ * Abstract base class for all contract service errors.
169
+ * Provides consistent error structure with operation context.
170
+ */
171
+ declare abstract class ContractServiceError extends Error {
172
+ readonly operation: string;
173
+ /**
174
+ * Creates a new ContractServiceError instance.
175
+ *
176
+ * @param message - The error message describing what went wrong
177
+ * @param operation - The operation that was being performed when the error occurred
178
+ */
179
+ constructor(message: string, operation: string);
180
+ }
181
+ /**
182
+ * Error thrown when organization creation fails.
183
+ */
184
+ declare class OrganizationCreateError extends ContractServiceError {
185
+ }
186
+ /**
187
+ * Error thrown when organization update fails.
188
+ */
189
+ declare class OrganizationUpdateError extends ContractServiceError {
190
+ }
191
+ /**
192
+ * Error thrown when organization deletion fails.
193
+ */
194
+ declare class OrganizationDeleteError extends ContractServiceError {
195
+ }
196
+ /**
197
+ * Error thrown when administrator operations fail.
198
+ */
199
+ declare class OrganizationAdministratorError extends ContractServiceError {
200
+ }
201
+ /**
202
+ * Error thrown when process creation fails.
203
+ */
204
+ declare class ProcessCreateError extends ContractServiceError {
205
+ }
206
+ /**
207
+ * Error thrown when process status change fails.
208
+ */
209
+ declare class ProcessStatusError extends ContractServiceError {
210
+ }
211
+ /**
212
+ * Error thrown when process census update fails.
213
+ */
214
+ declare class ProcessCensusError extends ContractServiceError {
215
+ }
216
+ /**
217
+ * Error thrown when process duration change fails.
218
+ */
219
+ declare class ProcessDurationError extends ContractServiceError {
220
+ }
221
+ /**
222
+ * Error thrown when state transition submission fails.
223
+ */
224
+ declare class ProcessStateTransitionError extends ContractServiceError {
225
+ }
226
+ /**
227
+ * Error thrown when process result setting fails.
228
+ */
229
+ declare class ProcessResultError extends ContractServiceError {
230
+ }
231
+
232
+ /**
233
+ * @fileoverview Standardized types and interfaces for contract services
234
+ *
235
+ * This module provides consistent type definitions for callbacks, interfaces,
236
+ * and common data structures used across contract services.
237
+ */
238
+ /**
239
+ * Generic callback type for contract events.
240
+ * @template T - Tuple type representing the event arguments
241
+ */
242
+ type EntityCallback<T extends any[]> = (...args: T) => void;
243
+ /**
244
+ * Callback for when an organization is created.
245
+ * @param id - The organization ID
246
+ */
247
+ type OrganizationCreatedCallback = EntityCallback<[string]>;
248
+ /**
249
+ * Callback for when an organization is updated.
250
+ * @param id - The organization ID
251
+ * @param updater - Address of the account that updated the organization
252
+ */
253
+ type OrganizationUpdatedCallback = EntityCallback<[string, string]>;
254
+ /**
255
+ * Callback for when an administrator is added to an organization.
256
+ * @param id - The organization ID
257
+ * @param administrator - Address of the administrator that was added
258
+ */
259
+ type OrganizationAdministratorAddedCallback = EntityCallback<[string, string]>;
260
+ /**
261
+ * Callback for when an administrator is removed from an organization.
262
+ * @param id - The organization ID
263
+ * @param administrator - Address of the administrator that was removed
264
+ * @param remover - Address of the account that removed the administrator
265
+ */
266
+ type OrganizationAdministratorRemovedCallback = EntityCallback<[string, string, string]>;
267
+ /**
268
+ * Callback for when a process is created.
269
+ * @param processID - The process ID
270
+ * @param creator - Address of the account that created the process
271
+ */
272
+ type ProcessCreatedCallback = EntityCallback<[string, string]>;
273
+ /**
274
+ * Callback for when a process status changes.
275
+ * @param processID - The process ID
276
+ * @param oldStatus - The previous status
277
+ * @param newStatus - The new status
278
+ */
279
+ type ProcessStatusChangedCallback = EntityCallback<[string, bigint, bigint]>;
280
+ /**
281
+ * Callback for when a process census is updated.
282
+ * @param processID - The process ID
283
+ * @param root - The new census root
284
+ * @param uri - The new census URI
285
+ * @param maxVotes - The maximum number of votes
286
+ */
287
+ type ProcessCensusUpdatedCallback = EntityCallback<[string, string, string, bigint]>;
288
+ /**
289
+ * Callback for when a process duration changes.
290
+ * @param processID - The process ID
291
+ * @param duration - The new duration
292
+ */
293
+ type ProcessDurationChangedCallback = EntityCallback<[string, bigint]>;
294
+ /**
295
+ * Callback for when a process state root is updated.
296
+ * @param processID - The process ID
297
+ * @param sender - Address of the account that updated the state root
298
+ * @param newStateRoot - The new state root
299
+ */
300
+ type ProcessStateRootUpdatedCallback = EntityCallback<[string, string, bigint]>;
301
+ /**
302
+ * Callback for when process results are set.
303
+ * @param processID - The process ID
304
+ * @param sender - Address of the account that set the results
305
+ * @param result - The results array
306
+ */
307
+ type ProcessResultsSetCallback = EntityCallback<[string, string, bigint[]]>;
308
+
309
+ interface OrganizationInfo {
310
+ name: string;
311
+ metadataURI: string;
312
+ }
313
+ declare class OrganizationRegistryService extends SmartContractService {
314
+ private contract;
315
+ constructor(contractAddress: string, runner: ContractRunner);
316
+ getOrganization(id: string): Promise<OrganizationInfo>;
317
+ existsOrganization(id: string): Promise<boolean>;
318
+ isAdministrator(id: string, address: string): Promise<boolean>;
319
+ getOrganizationCount(): Promise<number>;
320
+ createOrganization(name: string, metadataURI: string, administrators: string[]): AsyncGenerator<TxStatusEvent<{
321
+ success: boolean;
322
+ }>, void, unknown>;
323
+ updateOrganization(id: string, name: string, metadataURI: string): AsyncGenerator<TxStatusEvent<{
324
+ success: boolean;
325
+ }>, void, unknown>;
326
+ addAdministrator(id: string, administrator: string): AsyncGenerator<TxStatusEvent<{
327
+ success: boolean;
328
+ }>, void, unknown>;
329
+ removeAdministrator(id: string, administrator: string): AsyncGenerator<TxStatusEvent<{
330
+ success: boolean;
331
+ }>, void, unknown>;
332
+ deleteOrganization(id: string): AsyncGenerator<TxStatusEvent<{
333
+ success: boolean;
334
+ }>, void, unknown>;
335
+ onOrganizationCreated(cb: OrganizationCreatedCallback): void;
336
+ onOrganizationUpdated(cb: OrganizationUpdatedCallback): void;
337
+ onAdministratorAdded(cb: OrganizationAdministratorAddedCallback): void;
338
+ onAdministratorRemoved(cb: OrganizationAdministratorRemovedCallback): void;
339
+ removeAllListeners(): void;
340
+ }
341
+
342
+ /**
343
+ * Census origin types
344
+ */
345
+ declare enum CensusOrigin {
346
+ /** Indicates that the census is derived from a Merkle Tree structure */
347
+ CensusOriginMerkleTree = 1,
348
+ /** Indicates that the census is provided by a Credential Service Provider (CSP) */
349
+ CensusOriginCSP = 2
350
+ }
351
+
352
+ interface BallotMode {
353
+ numFields: number;
354
+ maxValue: string;
355
+ minValue: string;
356
+ uniqueValues: boolean;
357
+ costFromWeight: boolean;
358
+ costExponent: number;
359
+ maxValueSum: string;
360
+ minValueSum: string;
361
+ }
362
+ interface Census {
363
+ censusOrigin: CensusOrigin;
364
+ maxVotes: string;
365
+ censusRoot: string;
366
+ censusURI: string;
367
+ }
368
+ interface EncryptionKey {
369
+ x: string;
370
+ y: string;
371
+ }
372
+
373
+ interface ProofInputs {
374
+ fields: string[];
375
+ num_fields: string;
376
+ unique_values: string;
377
+ max_value: string;
378
+ min_value: string;
379
+ max_value_sum: string;
380
+ min_value_sum: string;
381
+ cost_exponent: string;
382
+ cost_from_weight: string;
383
+ address: string;
384
+ weight: string;
385
+ process_id: string;
386
+ vote_id: string;
387
+ encryption_pubkey: [string, string];
388
+ k: string;
389
+ cipherfields: string[];
390
+ inputs_hash: string;
391
+ }
392
+
393
+ interface DavinciCryptoCiphertext {
394
+ c1: [string, string];
395
+ c2: [string, string];
396
+ }
397
+ interface DavinciCryptoOutput {
398
+ processId: string;
399
+ address: string;
400
+ ballot: {
401
+ curveType: string;
402
+ ciphertexts: DavinciCryptoCiphertext[];
403
+ };
404
+ ballotInputsHash: string;
405
+ voteId: string;
406
+ circomInputs: ProofInputs;
407
+ }
408
+ interface CSPSignOutput {
409
+ censusOrigin: CensusOrigin;
410
+ root: string;
411
+ address: string;
412
+ processId: string;
413
+ publicKey: string;
414
+ signature: string;
415
+ }
416
+ interface RawResult<T = any> {
417
+ error?: string;
418
+ data?: T;
419
+ }
420
+ interface GoDavinciCryptoWasm {
421
+ proofInputs(inputJson: string): RawResult<DavinciCryptoOutput>;
422
+ cspSign(censusOrigin: number, privKey: string, processId: string, address: string): RawResult<CSPSignOutput>;
423
+ cspVerify(cspProof: string): RawResult<boolean>;
424
+ cspCensusRoot(censusOrigin: number, privKey: string): RawResult<{
425
+ root: string;
426
+ }>;
427
+ }
428
+ declare global {
429
+ var Go: new () => {
430
+ importObject: Record<string, any>;
431
+ run(instance: WebAssembly.Instance): Promise<void>;
432
+ };
433
+ var DavinciCrypto: GoDavinciCryptoWasm;
434
+ }
435
+
436
+ declare enum ProcessStatus {
437
+ READY = 0,
438
+ ENDED = 1,
439
+ CANCELED = 2,
440
+ PAUSED = 3,
441
+ RESULTS = 4
442
+ }
443
+ declare class ProcessRegistryService extends SmartContractService {
444
+ private contract;
445
+ constructor(contractAddress: string, runner: ContractRunner);
446
+ getProcess(processID: string): Promise<_vocdoni_davinci_contracts_dist_src_ProcessRegistry.IProcessRegistry.ProcessStructOutput>;
447
+ getProcessCount(): Promise<number>;
448
+ getChainID(): Promise<string>;
449
+ getNextProcessId(organizationId: string): Promise<string>;
450
+ getProcessEndTime(processID: string): Promise<bigint>;
451
+ getRVerifierVKeyHash(): Promise<string>;
452
+ getSTVerifierVKeyHash(): Promise<string>;
453
+ getMaxCensusOrigin(): Promise<bigint>;
454
+ getMaxStatus(): Promise<bigint>;
455
+ getProcessNonce(address: string): Promise<bigint>;
456
+ getProcessDirect(processID: string): Promise<[bigint, string, _vocdoni_davinci_contracts_dist_src_ProcessRegistry.IProcessRegistry.EncryptionKeyStructOutput, bigint, bigint, bigint, bigint, bigint, bigint, bigint, string, _vocdoni_davinci_contracts_dist_src_ProcessRegistry.IProcessRegistry.BallotModeStructOutput, _vocdoni_davinci_contracts_dist_src_ProcessRegistry.IProcessRegistry.CensusStructOutput] & {
457
+ status: bigint;
458
+ organizationId: string;
459
+ encryptionKey: _vocdoni_davinci_contracts_dist_src_ProcessRegistry.IProcessRegistry.EncryptionKeyStructOutput;
460
+ latestStateRoot: bigint;
461
+ startTime: bigint;
462
+ duration: bigint;
463
+ voteCount: bigint;
464
+ voteOverwriteCount: bigint;
465
+ creationBlock: bigint;
466
+ batchNumber: bigint;
467
+ metadataURI: string;
468
+ ballotMode: _vocdoni_davinci_contracts_dist_src_ProcessRegistry.IProcessRegistry.BallotModeStructOutput;
469
+ census: _vocdoni_davinci_contracts_dist_src_ProcessRegistry.IProcessRegistry.CensusStructOutput;
470
+ }>;
471
+ getRVerifier(): Promise<string>;
472
+ getSTVerifier(): Promise<string>;
473
+ newProcess(status: ProcessStatus, startTime: number, duration: number, ballotMode: BallotMode, census: Census, metadata: string, encryptionKey: EncryptionKey, initStateRoot: bigint): AsyncGenerator<TxStatusEvent<{
474
+ success: boolean;
475
+ }>, void, unknown>;
476
+ setProcessStatus(processID: string, newStatus: ProcessStatus): AsyncGenerator<TxStatusEvent<{
477
+ success: boolean;
478
+ }>, void, unknown>;
479
+ setProcessCensus(processID: string, census: Census): AsyncGenerator<TxStatusEvent<{
480
+ success: boolean;
481
+ }>, void, unknown>;
482
+ setProcessDuration(processID: string, duration: number): AsyncGenerator<TxStatusEvent<{
483
+ success: boolean;
484
+ }>, void, unknown>;
485
+ /**
486
+ * Matches the on-chain `submitStateTransition(processId, proof, input)`
487
+ */
488
+ submitStateTransition(processID: string, proof: string, input: string): AsyncGenerator<TxStatusEvent<{
489
+ success: boolean;
490
+ }>, void, unknown>;
491
+ /**
492
+ * Sets the results for a voting process.
493
+ *
494
+ * @param processID - The ID of the process to set results for
495
+ * @param proof - Zero-knowledge proof validating the results
496
+ * @param input - Input data for the proof verification
497
+ * @returns A transaction stream that resolves to success status
498
+ */
499
+ setProcessResults(processID: string, proof: string, input: string): AsyncGenerator<TxStatusEvent<{
500
+ success: boolean;
501
+ }>, void, unknown>;
502
+ onProcessCreated(cb: ProcessCreatedCallback): void;
503
+ onProcessStatusChanged(cb: ProcessStatusChangedCallback): void;
504
+ onCensusUpdated(cb: ProcessCensusUpdatedCallback): void;
505
+ onProcessDurationChanged(cb: ProcessDurationChangedCallback): void;
506
+ onStateRootUpdated(cb: ProcessStateRootUpdatedCallback): void;
507
+ onProcessResultsSet(cb: ProcessResultsSetCallback): void;
508
+ removeAllListeners(): void;
509
+ }
510
+
511
+ export { ContractServiceError, OrganizationAdministratorError, OrganizationCreateError, OrganizationDeleteError, OrganizationRegistryService, OrganizationUpdateError, ProcessCensusError, ProcessCreateError, ProcessDurationError, ProcessRegistryService, ProcessResultError, ProcessStateTransitionError, ProcessStatus, ProcessStatusError, SmartContractService, TxStatus, deployedAddresses };
512
+ export type { DeployedAddresses, EntityCallback, OrganizationAdministratorAddedCallback, OrganizationAdministratorRemovedCallback, OrganizationCreatedCallback, OrganizationInfo, OrganizationUpdatedCallback, ProcessCensusUpdatedCallback, ProcessCreatedCallback, ProcessDurationChangedCallback, ProcessResultsSetCallback, ProcessStateRootUpdatedCallback, ProcessStatusChangedCallback, TxStatusEvent };