@vocdoni/davinci-sdk 0.0.1 → 0.0.3

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/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AxiosInstance, AxiosRequestConfig } from 'axios';
2
- import { ContractTransactionResponse, ContractRunner, Signer, Wallet } from 'ethers';
2
+ import { ContractTransactionResponse, BaseContract, ContractEventName, EventFilter, ContractRunner, Signer, Wallet } from 'ethers';
3
3
  import * as _vocdoni_davinci_contracts_dist_src_ProcessRegistry from '@vocdoni/davinci-contracts/dist/src/ProcessRegistry';
4
4
 
5
5
  type AnyJson = boolean | number | string | null | JsonArray | JsonMap | any;
@@ -113,7 +113,7 @@ declare enum CensusOrigin {
113
113
  /** Indicates that the census is provided by a Credential Service Provider (CSP) */
114
114
  CensusOriginCSP = 2
115
115
  }
116
- interface CensusParticipant {
116
+ interface CensusParticipant$1 {
117
117
  key: string;
118
118
  weight?: string;
119
119
  }
@@ -167,6 +167,22 @@ interface CensusProviders {
167
167
  /** Required provider for CSP census proof generation */
168
168
  csp?: CSPCensusProofProvider;
169
169
  }
170
+ /**
171
+ * Type guard to check if an object is a valid MerkleCensusProof
172
+ */
173
+ declare function isMerkleCensusProof(proof: any): proof is MerkleCensusProof;
174
+ /**
175
+ * Type guard to check if an object is a valid CSPCensusProof
176
+ */
177
+ declare function isCSPCensusProof(proof: any): proof is CSPCensusProof;
178
+ /**
179
+ * Assertion function to validate MerkleCensusProof
180
+ */
181
+ declare function assertMerkleCensusProof(proof: unknown): asserts proof is MerkleCensusProof;
182
+ /**
183
+ * Assertion function to validate CSPCensusProof
184
+ */
185
+ declare function assertCSPCensusProof(proof: unknown): asserts proof is CSPCensusProof;
170
186
  interface PublishCensusResponse {
171
187
  /** The Merkle root of the published census (hex-prefixed). */
172
188
  root: string;
@@ -231,6 +247,10 @@ interface SnapshotsQueryParams {
231
247
  /** Filter by user-defined query name. */
232
248
  queryName?: string;
233
249
  }
250
+ interface CensusSizeResponse {
251
+ /** The number of participants in the census. */
252
+ size: number;
253
+ }
234
254
  interface HealthResponse {
235
255
  /** Service status. */
236
256
  status: string;
@@ -249,8 +269,8 @@ declare class VocdoniCensusService extends BaseService {
249
269
  */
250
270
  getCensusUri(censusRoot: string): string;
251
271
  createCensus(): Promise<string>;
252
- addParticipants(censusId: string, participants: CensusParticipant[]): Promise<void>;
253
- getParticipants(censusId: string): Promise<CensusParticipant[]>;
272
+ addParticipants(censusId: string, participants: CensusParticipant$1[]): Promise<void>;
273
+ getParticipants(censusId: string): Promise<CensusParticipant$1[]>;
254
274
  getCensusRoot(censusId: string): Promise<string>;
255
275
  getCensusSizeById(censusId: string): Promise<number>;
256
276
  getCensusSizeByRoot(censusRoot: string): Promise<number>;
@@ -263,6 +283,168 @@ declare class VocdoniCensusService extends BaseService {
263
283
  getHealth(): Promise<HealthResponse>;
264
284
  }
265
285
 
286
+ /**
287
+ * Census type enumeration
288
+ */
289
+ declare enum CensusType {
290
+ PLAIN = "plain",
291
+ WEIGHTED = "weighted",
292
+ CSP = "csp"
293
+ }
294
+ /**
295
+ * Re-export CensusParticipant from types for convenience
296
+ * Extended to make weight required (base type has optional weight)
297
+ */
298
+ interface CensusParticipant extends CensusParticipant$1 {
299
+ weight: string;
300
+ }
301
+ /**
302
+ * Abstract base class for all census types
303
+ */
304
+ declare abstract class Census {
305
+ protected _censusId: string | null;
306
+ protected _censusRoot: string | null;
307
+ protected _censusURI: string | null;
308
+ protected _type: CensusType;
309
+ protected _size: number | null;
310
+ constructor(type: CensusType);
311
+ get censusId(): string | null;
312
+ get censusRoot(): string | null;
313
+ get censusURI(): string | null;
314
+ get type(): CensusType;
315
+ get size(): number | null;
316
+ get isPublished(): boolean;
317
+ /**
318
+ * Convert CensusType to CensusOrigin enum for API compatibility
319
+ */
320
+ get censusOrigin(): CensusOrigin;
321
+ }
322
+
323
+ /**
324
+ * Plain census where all participants have equal voting power (weight=1)
325
+ * Simpler API - just add addresses without specifying weights
326
+ */
327
+ declare class PlainCensus extends Census {
328
+ private _participants;
329
+ constructor();
330
+ /**
331
+ * Add participant(s) with automatic weight=1
332
+ * @param addresses - Single address or array of addresses
333
+ */
334
+ add(addresses: string | string[]): void;
335
+ /**
336
+ * Remove participant by address
337
+ */
338
+ remove(address: string): void;
339
+ /**
340
+ * Get all participants as CensusParticipant array (for API)
341
+ * All participants have weight="1"
342
+ */
343
+ get participants(): CensusParticipant[];
344
+ /**
345
+ * Get addresses only
346
+ */
347
+ get addresses(): string[];
348
+ private validateAddress;
349
+ /**
350
+ * Internal method called after publishing
351
+ * @internal
352
+ */
353
+ _setPublishedData(root: string, uri: string, size: number, censusId?: string): void;
354
+ }
355
+
356
+ /**
357
+ * Participant with flexible weight type for WeightedCensus
358
+ * Weight can be string, number, or bigint - will be normalized to string internally
359
+ */
360
+ interface WeightedParticipant {
361
+ key: string;
362
+ weight: string | number | bigint;
363
+ }
364
+ /**
365
+ * Weighted census where participants can have different voting power
366
+ * Requires specifying weight for each participant
367
+ */
368
+ declare class WeightedCensus extends Census {
369
+ private _participants;
370
+ constructor();
371
+ /**
372
+ * Add participant(s) with custom weights
373
+ * Weight can be provided as string, number, or bigint - will be converted to string internally
374
+ * @param participant - Single participant or array of participants with custom weights
375
+ */
376
+ add(participant: WeightedParticipant | WeightedParticipant[]): void;
377
+ /**
378
+ * Remove participant by address
379
+ */
380
+ remove(address: string): void;
381
+ /**
382
+ * Get all participants as CensusParticipant array
383
+ */
384
+ get participants(): CensusParticipant[];
385
+ /**
386
+ * Get participant addresses
387
+ */
388
+ get addresses(): string[];
389
+ /**
390
+ * Get weight for specific address
391
+ */
392
+ getWeight(address: string): string | undefined;
393
+ /**
394
+ * Normalizes weight from string, number, or bigint to string
395
+ */
396
+ private normalizeWeight;
397
+ private validateParticipant;
398
+ /**
399
+ * Internal method called after publishing
400
+ * @internal
401
+ */
402
+ _setPublishedData(root: string, uri: string, size: number, censusId?: string): void;
403
+ }
404
+
405
+ /**
406
+ * CSP (Certificate Service Provider) census
407
+ * Uses a public key and CSP server URI instead of a participant list
408
+ */
409
+ declare class CspCensus extends Census {
410
+ private _publicKey;
411
+ private _cspURI;
412
+ constructor(publicKey: string, cspURI: string, size: number);
413
+ get publicKey(): string;
414
+ get cspURI(): string;
415
+ }
416
+
417
+ /**
418
+ * Published census - represents a census that has already been published
419
+ * Use this when you have the census root, URI, and size from a previous publication
420
+ */
421
+ declare class PublishedCensus extends Census {
422
+ constructor(type: CensusType, root: string, uri: string, size: number);
423
+ }
424
+
425
+ /**
426
+ * Orchestrates census creation and publishing
427
+ */
428
+ declare class CensusOrchestrator {
429
+ private censusService;
430
+ constructor(censusService: VocdoniCensusService);
431
+ /**
432
+ * Publishes a PlainCensus or WeightedCensus
433
+ * Creates a working census, adds participants, and publishes it
434
+ */
435
+ publish(census: PlainCensus | WeightedCensus): Promise<void>;
436
+ /**
437
+ * Gets census data for process creation
438
+ * Throws if census is not published
439
+ */
440
+ getCensusData(census: Census): {
441
+ type: CensusOrigin;
442
+ root: string;
443
+ uri: string;
444
+ size: number;
445
+ };
446
+ }
447
+
266
448
  interface BallotMode {
267
449
  numFields: number;
268
450
  maxValue: string;
@@ -273,7 +455,7 @@ interface BallotMode {
273
455
  maxValueSum: string;
274
456
  minValueSum: string;
275
457
  }
276
- interface Census {
458
+ interface CensusData {
277
459
  censusOrigin: CensusOrigin;
278
460
  maxVotes: string;
279
461
  censusRoot: string;
@@ -312,7 +494,7 @@ interface GetProcessResponse {
312
494
  duration: number;
313
495
  metadataURI: string;
314
496
  ballotMode: BallotMode;
315
- census: Census;
497
+ census: CensusData;
316
498
  metadata: {
317
499
  title: Record<string, string>;
318
500
  description: Record<string, string>;
@@ -461,118 +643,6 @@ declare class VocdoniApiService {
461
643
  constructor(config: VocdoniApiServiceConfig);
462
644
  }
463
645
 
464
- /**
465
- * Supported environment types
466
- */
467
- type Environment = 'dev' | 'stg' | 'prod';
468
- /**
469
- * URL configuration for each service
470
- */
471
- interface ServiceUrls {
472
- /** Sequencer API URL */
473
- sequencer: string;
474
- /** Census API URL */
475
- census: string;
476
- }
477
- /**
478
- * Chain configuration for each environment
479
- */
480
- interface ChainConfig {
481
- /** Chain name/ID */
482
- chain: 'sepolia' | 'mainnet';
483
- }
484
- /**
485
- * Environment-based URL configuration
486
- */
487
- interface EnvironmentConfig {
488
- dev: ServiceUrls & ChainConfig;
489
- stg: ServiceUrls & ChainConfig;
490
- prod: ServiceUrls & ChainConfig;
491
- }
492
- /**
493
- * Configuration options for environment setup
494
- */
495
- interface EnvironmentOptions {
496
- /** Environment to use (defaults to 'prod') */
497
- environment?: Environment;
498
- /** Custom URLs to override defaults */
499
- customUrls?: Partial<ServiceUrls>;
500
- /** Custom chain to override default */
501
- customChain?: ChainConfig['chain'];
502
- }
503
-
504
- /**
505
- * Default URL and chain configuration for all environments
506
- */
507
- declare const DEFAULT_ENVIRONMENT_URLS: EnvironmentConfig;
508
- /**
509
- * Get URLs and chain configuration for a specific environment
510
- */
511
- declare function getEnvironmentConfig(environment: Environment): ServiceUrls & ChainConfig;
512
- /**
513
- * Get only URLs for a specific environment
514
- */
515
- declare function getEnvironmentUrls(environment: Environment): ServiceUrls;
516
- /**
517
- * Get chain configuration for a specific environment
518
- */
519
- declare function getEnvironmentChain(environment: Environment): ChainConfig['chain'];
520
- /**
521
- * Resolve URLs and chain based on environment and custom overrides
522
- */
523
- declare function resolveConfiguration(options?: EnvironmentOptions): ServiceUrls & ChainConfig;
524
- /**
525
- * Resolve only URLs based on environment and custom overrides
526
- */
527
- declare function resolveUrls(options?: EnvironmentOptions): ServiceUrls;
528
-
529
- /**
530
- * Interface defining the structure of deployed contract addresses across different networks.
531
- * Each contract has addresses for both Sepolia testnet and Ethereum mainnet.
532
- */
533
- interface DeployedAddresses {
534
- /** Process Registry contract addresses */
535
- processRegistry: {
536
- /** Sepolia testnet address */
537
- sepolia: string;
538
- /** Ethereum mainnet address */
539
- mainnet: string;
540
- };
541
- /** Organization Registry contract addresses */
542
- organizationRegistry: {
543
- /** Sepolia testnet address */
544
- sepolia: string;
545
- /** Ethereum mainnet address */
546
- mainnet: string;
547
- };
548
- /** State Transition Verifier contract addresses */
549
- stateTransitionVerifierGroth16: {
550
- /** Sepolia testnet address */
551
- sepolia: string;
552
- /** Ethereum mainnet address */
553
- mainnet: string;
554
- };
555
- /** Results Verifier contract addresses */
556
- resultsVerifierGroth16: {
557
- /** Sepolia testnet address */
558
- sepolia: string;
559
- /** Ethereum mainnet address */
560
- mainnet: string;
561
- };
562
- /** Sequencer Registry contract addresses */
563
- sequencerRegistry: {
564
- /** Sepolia testnet address */
565
- sepolia: string;
566
- /** Ethereum mainnet address */
567
- mainnet: string;
568
- };
569
- }
570
- /**
571
- * Deployed contract addresses imported from @vocdoni/davinci-contracts package.
572
- * These addresses are used to interact with the Vocdoni voting protocol contracts
573
- * on different networks.
574
- */
575
- declare const deployedAddresses: DeployedAddresses;
576
646
  /**
577
647
  * Enum representing the possible states of a transaction during its lifecycle.
578
648
  * Used to track and report transaction status in the event stream.
@@ -608,9 +678,14 @@ type TxStatusEvent<T = any> = {
608
678
  };
609
679
  /**
610
680
  * Abstract base class providing common functionality for smart contract interactions.
611
- * Implements transaction handling, status monitoring, and event normalization.
681
+ * Implements transaction handling, status monitoring, event normalization, and
682
+ * event listener management with automatic fallback for RPCs that don't support eth_newFilter.
612
683
  */
613
684
  declare abstract class SmartContractService {
685
+ /** Active polling intervals for event listeners using fallback mode */
686
+ private pollingIntervals;
687
+ /** Default polling interval in milliseconds for event listener fallback */
688
+ protected eventPollingInterval: number;
614
689
  /**
615
690
  * Sends a transaction and yields status events during its lifecycle.
616
691
  * This method handles the complete transaction flow from submission to completion,
@@ -681,6 +756,59 @@ declare abstract class SmartContractService {
681
756
  * ```
682
757
  */
683
758
  protected normalizeListener<Args extends any[]>(callback: (...args: Args) => void): (...listenerArgs: any[]) => void;
759
+ /**
760
+ * Sets up an event listener with automatic fallback for RPCs that don't support eth_newFilter.
761
+ * First attempts to use contract.on() which relies on eth_newFilter. If the RPC doesn't support
762
+ * this method (error code -32601), automatically falls back to polling with queryFilter.
763
+ *
764
+ * @template Args - Tuple type representing the event arguments
765
+ * @param contract - The contract instance to listen to
766
+ * @param eventFilter - The event filter to listen for
767
+ * @param callback - The callback function to invoke when the event occurs
768
+ *
769
+ * @example
770
+ * ```typescript
771
+ * this.setupEventListener(
772
+ * this.contract,
773
+ * this.contract.filters.Transfer(),
774
+ * (from: string, to: string, amount: bigint) => {
775
+ * console.log(`Transfer: ${from} -> ${to}: ${amount}`);
776
+ * }
777
+ * );
778
+ * ```
779
+ */
780
+ protected setupEventListener<Args extends any[]>(contract: BaseContract, eventFilter: ContractEventName | EventFilter, callback: (...args: Args) => void): Promise<void>;
781
+ /**
782
+ * Checks if an error indicates that the RPC method is unsupported or filter operations are not working.
783
+ * This includes:
784
+ * - Method not found (-32601): RPC doesn't support eth_newFilter
785
+ * - Filter not found (-32000): RPC doesn't properly maintain filters
786
+ *
787
+ * @param error - The error to check
788
+ * @returns true if the error indicates unsupported or broken filter functionality
789
+ */
790
+ private isUnsupportedMethodError;
791
+ /**
792
+ * Sets up a polling-based event listener as fallback when eth_newFilter is not supported.
793
+ * Periodically queries for new events and invokes the callback for each new event found.
794
+ *
795
+ * @template Args - Tuple type representing the event arguments
796
+ * @param contract - The contract instance to poll
797
+ * @param eventFilter - The event filter to poll for
798
+ * @param callback - The callback function to invoke for each event
799
+ */
800
+ private setupPollingListener;
801
+ /**
802
+ * Clears all active polling intervals.
803
+ * Should be called when removing all listeners or cleaning up the service.
804
+ */
805
+ protected clearPollingIntervals(): void;
806
+ /**
807
+ * Sets the polling interval for event listeners using the fallback mechanism.
808
+ *
809
+ * @param intervalMs - Polling interval in milliseconds
810
+ */
811
+ setEventPollingInterval(intervalMs: number): void;
684
812
  }
685
813
 
686
814
  /**
@@ -797,13 +925,13 @@ declare class ProcessRegistryService extends SmartContractService {
797
925
  }>;
798
926
  getRVerifier(): Promise<string>;
799
927
  getSTVerifier(): Promise<string>;
800
- newProcess(status: ProcessStatus, startTime: number, duration: number, ballotMode: BallotMode, census: Census, metadata: string, encryptionKey: EncryptionKey, initStateRoot: bigint): AsyncGenerator<TxStatusEvent<{
928
+ newProcess(status: ProcessStatus, startTime: number, duration: number, ballotMode: BallotMode, census: CensusData, metadata: string, encryptionKey: EncryptionKey, initStateRoot: bigint): AsyncGenerator<TxStatusEvent<{
801
929
  success: boolean;
802
930
  }>, void, unknown>;
803
931
  setProcessStatus(processID: string, newStatus: ProcessStatus): AsyncGenerator<TxStatusEvent<{
804
932
  success: boolean;
805
933
  }>, void, unknown>;
806
- setProcessCensus(processID: string, census: Census): AsyncGenerator<TxStatusEvent<{
934
+ setProcessCensus(processID: string, census: CensusData): AsyncGenerator<TxStatusEvent<{
807
935
  success: boolean;
808
936
  }>, void, unknown>;
809
937
  setProcessDuration(processID: string, duration: number): AsyncGenerator<TxStatusEvent<{
@@ -1096,7 +1224,22 @@ interface BaseProcess {
1096
1224
  /**
1097
1225
  * Configuration for creating a process
1098
1226
  */
1099
- interface ProcessConfig extends BaseProcess {
1227
+ interface ProcessConfig extends Omit<BaseProcess, 'census'> {
1228
+ /**
1229
+ * Census - either a Census object (PlainCensus, WeightedCensus, CspCensus, PublishedCensus)
1230
+ * or manual configuration. If a Census object is provided and not published, it will be
1231
+ * automatically published.
1232
+ */
1233
+ census: Census | {
1234
+ /** Census type - MerkleTree or CSP */
1235
+ type: CensusOrigin;
1236
+ /** Census root */
1237
+ root: string;
1238
+ /** Census size */
1239
+ size: number;
1240
+ /** Census URI */
1241
+ uri: string;
1242
+ };
1100
1243
  /** Process timing - use either duration-based or date-based configuration */
1101
1244
  timing: {
1102
1245
  /** Start date/time (Date object, ISO string, or Unix timestamp, default: now + 60 seconds) */
@@ -1154,7 +1297,13 @@ declare class ProcessOrchestrationService {
1154
1297
  private organizationRegistry;
1155
1298
  private getCrypto;
1156
1299
  private signer;
1300
+ private censusOrchestrator;
1157
1301
  constructor(processRegistry: ProcessRegistryService, apiService: VocdoniApiService, organizationRegistry: OrganizationRegistryService, getCrypto: () => Promise<DavinciCrypto>, signer: Signer);
1302
+ /**
1303
+ * Handles census - auto-publishes if needed and returns census config
1304
+ * @private
1305
+ */
1306
+ private handleCensus;
1158
1307
  /**
1159
1308
  * Gets user-friendly process information by transforming raw contract data
1160
1309
  * @param processId - The process ID to fetch
@@ -1162,10 +1311,65 @@ declare class ProcessOrchestrationService {
1162
1311
  */
1163
1312
  getProcess(processId: string): Promise<ProcessInfo>;
1164
1313
  /**
1165
- * Creates a complete voting process with minimal configuration
1166
- * This method handles all the complex orchestration internally
1314
+ * Creates a complete voting process and returns an async generator that yields transaction status events.
1315
+ * This method allows you to monitor the transaction progress in real-time.
1316
+ *
1317
+ * @param config - Process configuration
1318
+ * @returns AsyncGenerator yielding transaction status events with ProcessCreationResult
1319
+ *
1320
+ * @example
1321
+ * ```typescript
1322
+ * const stream = sdk.createProcessStream({
1323
+ * title: "My Election",
1324
+ * description: "A simple election",
1325
+ * census: { ... },
1326
+ * ballot: { ... },
1327
+ * timing: { ... },
1328
+ * questions: [ ... ]
1329
+ * });
1330
+ *
1331
+ * for await (const event of stream) {
1332
+ * switch (event.status) {
1333
+ * case "pending":
1334
+ * console.log("Transaction pending:", event.hash);
1335
+ * break;
1336
+ * case "completed":
1337
+ * console.log("Process created:", event.response.processId);
1338
+ * console.log("Transaction hash:", event.response.transactionHash);
1339
+ * break;
1340
+ * case "failed":
1341
+ * console.error("Transaction failed:", event.error);
1342
+ * break;
1343
+ * case "reverted":
1344
+ * console.error("Transaction reverted:", event.reason);
1345
+ * break;
1346
+ * }
1347
+ * }
1348
+ * ```
1349
+ */
1350
+ createProcessStream(config: ProcessConfig): AsyncGenerator<TxStatusEvent<ProcessCreationResult>>;
1351
+ /**
1352
+ * Creates a complete voting process with minimal configuration.
1353
+ * This is the ultra-easy method for end users that handles all the complex orchestration internally.
1354
+ *
1355
+ * For real-time transaction status updates, use createProcessStream() instead.
1356
+ *
1357
+ * The method automatically:
1358
+ * - Gets encryption keys and initial state root from the sequencer
1359
+ * - Handles process creation signatures
1360
+ * - Coordinates between sequencer API and on-chain contract calls
1361
+ * - Creates and pushes metadata
1362
+ * - Submits the on-chain transaction
1363
+ *
1364
+ * @param config - Simplified process configuration
1365
+ * @returns Promise resolving to the process creation result
1167
1366
  */
1168
1367
  createProcess(config: ProcessConfig): Promise<ProcessCreationResult>;
1368
+ /**
1369
+ * Prepares all data needed for process creation
1370
+ * @private
1371
+ */
1372
+ private prepareProcessCreation;
1169
1373
  /**
1170
1374
  * Validates and calculates timing parameters
1171
1375
  */
@@ -1178,85 +1382,326 @@ declare class ProcessOrchestrationService {
1178
1382
  * Creates metadata from the simplified configuration
1179
1383
  */
1180
1384
  private createMetadata;
1181
- }
1182
-
1183
- /**
1184
- * Simplified vote configuration interface for end users
1185
- */
1186
- interface VoteConfig {
1187
- /** The process ID to vote in */
1188
- processId: string;
1189
- /** The voter's choices - array of selected values for each question */
1190
- choices: number[];
1191
- /** Optional: Custom randomness for vote encryption (will be generated if not provided) */
1192
- randomness?: string;
1193
- }
1194
- /**
1195
- * Result of vote submission
1196
- */
1197
- interface VoteResult {
1198
- /** The unique vote ID */
1199
- voteId: string;
1200
- /** The transaction signature */
1201
- signature: string;
1202
- /** The voter's address */
1203
- voterAddress: string;
1204
- /** The process ID */
1205
- processId: string;
1206
- /** Current vote status */
1207
- status: VoteStatus;
1208
- }
1209
- /**
1210
- * Vote status information
1211
- */
1212
- interface VoteStatusInfo {
1213
- /** The vote ID */
1214
- voteId: string;
1215
- /** Current status of the vote */
1216
- status: VoteStatus;
1217
- /** The process ID */
1218
- processId: string;
1219
- }
1220
- /**
1221
- * Service that orchestrates the complete voting workflow
1222
- * Handles all the complex cryptographic operations and API calls internally
1223
- */
1224
- declare class VoteOrchestrationService {
1225
- private apiService;
1226
- private getCrypto;
1227
- private signer;
1228
- private censusProviders;
1229
- constructor(apiService: VocdoniApiService, getCrypto: () => Promise<DavinciCrypto>, signer: Signer, censusProviders?: CensusProviders);
1230
1385
  /**
1231
- * Submit a vote with simplified configuration
1232
- * This method handles all the complex orchestration internally:
1233
- * - Fetches process information and encryption keys
1234
- * - Gets census proof (Merkle or CSP)
1235
- * - Generates cryptographic proofs
1236
- * - Signs and submits the vote
1386
+ * Ends a voting process by setting its status to ENDED.
1387
+ * Returns an async generator that yields transaction status events.
1237
1388
  *
1238
- * @param config - Simplified vote configuration
1239
- * @returns Promise resolving to vote submission result
1389
+ * @param processId - The process ID to end
1390
+ * @returns AsyncGenerator yielding transaction status events
1391
+ *
1392
+ * @example
1393
+ * ```typescript
1394
+ * const stream = sdk.endProcessStream("0x1234567890abcdef...");
1395
+ *
1396
+ * for await (const event of stream) {
1397
+ * switch (event.status) {
1398
+ * case "pending":
1399
+ * console.log("Transaction pending:", event.hash);
1400
+ * break;
1401
+ * case "completed":
1402
+ * console.log("Process ended successfully");
1403
+ * break;
1404
+ * case "failed":
1405
+ * console.error("Transaction failed:", event.error);
1406
+ * break;
1407
+ * case "reverted":
1408
+ * console.error("Transaction reverted:", event.reason);
1409
+ * break;
1410
+ * }
1411
+ * }
1412
+ * ```
1240
1413
  */
1241
- submitVote(config: VoteConfig): Promise<VoteResult>;
1414
+ endProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
1415
+ success: boolean;
1416
+ }>>;
1242
1417
  /**
1243
- * Get the status of a submitted vote
1418
+ * Ends a voting process by setting its status to ENDED.
1419
+ * This is a simplified method that waits for transaction completion.
1244
1420
  *
1245
- * @param processId - The process ID
1246
- * @param voteId - The vote ID
1247
- * @returns Promise resolving to vote status information
1421
+ * For real-time transaction status updates, use endProcessStream() instead.
1422
+ *
1423
+ * @param processId - The process ID to end
1424
+ * @returns Promise resolving when the process is ended
1425
+ *
1426
+ * @example
1427
+ * ```typescript
1428
+ * await sdk.endProcess("0x1234567890abcdef...");
1429
+ * console.log("Process ended successfully");
1430
+ * ```
1248
1431
  */
1249
- getVoteStatus(processId: string, voteId: string): Promise<VoteStatusInfo>;
1432
+ endProcess(processId: string): Promise<void>;
1250
1433
  /**
1251
- * Check if an address has voted in a process
1434
+ * Pauses a voting process by setting its status to PAUSED.
1435
+ * Returns an async generator that yields transaction status events.
1252
1436
  *
1253
- * @param processId - The process ID
1254
- * @param address - The voter's address
1255
- * @returns Promise resolving to boolean indicating if the address has voted
1437
+ * @param processId - The process ID to pause
1438
+ * @returns AsyncGenerator yielding transaction status events
1439
+ *
1440
+ * @example
1441
+ * ```typescript
1442
+ * const stream = sdk.pauseProcessStream("0x1234567890abcdef...");
1443
+ *
1444
+ * for await (const event of stream) {
1445
+ * switch (event.status) {
1446
+ * case "pending":
1447
+ * console.log("Transaction pending:", event.hash);
1448
+ * break;
1449
+ * case "completed":
1450
+ * console.log("Process paused successfully");
1451
+ * break;
1452
+ * case "failed":
1453
+ * console.error("Transaction failed:", event.error);
1454
+ * break;
1455
+ * case "reverted":
1456
+ * console.error("Transaction reverted:", event.reason);
1457
+ * break;
1458
+ * }
1459
+ * }
1460
+ * ```
1461
+ */
1462
+ pauseProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
1463
+ success: boolean;
1464
+ }>>;
1465
+ /**
1466
+ * Pauses a voting process by setting its status to PAUSED.
1467
+ * This is a simplified method that waits for transaction completion.
1468
+ *
1469
+ * For real-time transaction status updates, use pauseProcessStream() instead.
1470
+ *
1471
+ * @param processId - The process ID to pause
1472
+ * @returns Promise resolving when the process is paused
1473
+ *
1474
+ * @example
1475
+ * ```typescript
1476
+ * await sdk.pauseProcess("0x1234567890abcdef...");
1477
+ * console.log("Process paused successfully");
1478
+ * ```
1479
+ */
1480
+ pauseProcess(processId: string): Promise<void>;
1481
+ /**
1482
+ * Cancels a voting process by setting its status to CANCELED.
1483
+ * Returns an async generator that yields transaction status events.
1484
+ *
1485
+ * @param processId - The process ID to cancel
1486
+ * @returns AsyncGenerator yielding transaction status events
1487
+ *
1488
+ * @example
1489
+ * ```typescript
1490
+ * const stream = sdk.cancelProcessStream("0x1234567890abcdef...");
1491
+ *
1492
+ * for await (const event of stream) {
1493
+ * switch (event.status) {
1494
+ * case "pending":
1495
+ * console.log("Transaction pending:", event.hash);
1496
+ * break;
1497
+ * case "completed":
1498
+ * console.log("Process canceled successfully");
1499
+ * break;
1500
+ * case "failed":
1501
+ * console.error("Transaction failed:", event.error);
1502
+ * break;
1503
+ * case "reverted":
1504
+ * console.error("Transaction reverted:", event.reason);
1505
+ * break;
1506
+ * }
1507
+ * }
1508
+ * ```
1509
+ */
1510
+ cancelProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
1511
+ success: boolean;
1512
+ }>>;
1513
+ /**
1514
+ * Cancels a voting process by setting its status to CANCELED.
1515
+ * This is a simplified method that waits for transaction completion.
1516
+ *
1517
+ * For real-time transaction status updates, use cancelProcessStream() instead.
1518
+ *
1519
+ * @param processId - The process ID to cancel
1520
+ * @returns Promise resolving when the process is canceled
1521
+ *
1522
+ * @example
1523
+ * ```typescript
1524
+ * await sdk.cancelProcess("0x1234567890abcdef...");
1525
+ * console.log("Process canceled successfully");
1526
+ * ```
1527
+ */
1528
+ cancelProcess(processId: string): Promise<void>;
1529
+ /**
1530
+ * Resumes a voting process by setting its status to READY.
1531
+ * This is typically used to resume a paused process.
1532
+ * Returns an async generator that yields transaction status events.
1533
+ *
1534
+ * @param processId - The process ID to resume
1535
+ * @returns AsyncGenerator yielding transaction status events
1536
+ *
1537
+ * @example
1538
+ * ```typescript
1539
+ * const stream = sdk.resumeProcessStream("0x1234567890abcdef...");
1540
+ *
1541
+ * for await (const event of stream) {
1542
+ * switch (event.status) {
1543
+ * case "pending":
1544
+ * console.log("Transaction pending:", event.hash);
1545
+ * break;
1546
+ * case "completed":
1547
+ * console.log("Process resumed successfully");
1548
+ * break;
1549
+ * case "failed":
1550
+ * console.error("Transaction failed:", event.error);
1551
+ * break;
1552
+ * case "reverted":
1553
+ * console.error("Transaction reverted:", event.reason);
1554
+ * break;
1555
+ * }
1556
+ * }
1557
+ * ```
1558
+ */
1559
+ resumeProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
1560
+ success: boolean;
1561
+ }>>;
1562
+ /**
1563
+ * Resumes a voting process by setting its status to READY.
1564
+ * This is typically used to resume a paused process.
1565
+ * This is a simplified method that waits for transaction completion.
1566
+ *
1567
+ * For real-time transaction status updates, use resumeProcessStream() instead.
1568
+ *
1569
+ * @param processId - The process ID to resume
1570
+ * @returns Promise resolving when the process is resumed
1571
+ *
1572
+ * @example
1573
+ * ```typescript
1574
+ * await sdk.resumeProcess("0x1234567890abcdef...");
1575
+ * console.log("Process resumed successfully");
1576
+ * ```
1577
+ */
1578
+ resumeProcess(processId: string): Promise<void>;
1579
+ }
1580
+
1581
+ /**
1582
+ * Simplified vote configuration interface for end users
1583
+ */
1584
+ interface VoteConfig {
1585
+ /** The process ID to vote in */
1586
+ processId: string;
1587
+ /** The voter's choices - array of selected values for each question */
1588
+ choices: number[];
1589
+ /** Optional: Custom randomness for vote encryption (will be generated if not provided) */
1590
+ randomness?: string;
1591
+ }
1592
+ /**
1593
+ * Result of vote submission
1594
+ */
1595
+ interface VoteResult {
1596
+ /** The unique vote ID */
1597
+ voteId: string;
1598
+ /** The transaction signature */
1599
+ signature: string;
1600
+ /** The voter's address */
1601
+ voterAddress: string;
1602
+ /** The process ID */
1603
+ processId: string;
1604
+ /** Current vote status */
1605
+ status: VoteStatus;
1606
+ }
1607
+ /**
1608
+ * Vote status information
1609
+ */
1610
+ interface VoteStatusInfo {
1611
+ /** The vote ID */
1612
+ voteId: string;
1613
+ /** Current status of the vote */
1614
+ status: VoteStatus;
1615
+ /** The process ID */
1616
+ processId: string;
1617
+ }
1618
+ /**
1619
+ * Configuration options for VoteOrchestrationService
1620
+ */
1621
+ interface VoteOrchestrationConfig {
1622
+ /** Whether to verify downloaded circuit files match expected hashes (default: true) */
1623
+ verifyCircuitFiles?: boolean;
1624
+ /** Whether to verify the generated proof is valid before submission (default: true) */
1625
+ verifyProof?: boolean;
1626
+ }
1627
+ /**
1628
+ * Service that orchestrates the complete voting workflow
1629
+ * Handles all the complex cryptographic operations and API calls internally
1630
+ */
1631
+ declare class VoteOrchestrationService {
1632
+ private apiService;
1633
+ private getCrypto;
1634
+ private signer;
1635
+ private censusProviders;
1636
+ private readonly verifyCircuitFiles;
1637
+ private readonly verifyProof;
1638
+ constructor(apiService: VocdoniApiService, getCrypto: () => Promise<DavinciCrypto>, signer: Signer, censusProviders?: CensusProviders, config?: VoteOrchestrationConfig);
1639
+ /**
1640
+ * Submit a vote with simplified configuration
1641
+ * This method handles all the complex orchestration internally:
1642
+ * - Fetches process information and encryption keys
1643
+ * - Gets census proof (Merkle or CSP)
1644
+ * - Generates cryptographic proofs
1645
+ * - Signs and submits the vote
1646
+ *
1647
+ * @param config - Simplified vote configuration
1648
+ * @returns Promise resolving to vote submission result
1649
+ */
1650
+ submitVote(config: VoteConfig): Promise<VoteResult>;
1651
+ /**
1652
+ * Get the status of a submitted vote
1653
+ *
1654
+ * @param processId - The process ID
1655
+ * @param voteId - The vote ID
1656
+ * @returns Promise resolving to vote status information
1657
+ */
1658
+ getVoteStatus(processId: string, voteId: string): Promise<VoteStatusInfo>;
1659
+ /**
1660
+ * Check if an address has voted in a process
1661
+ *
1662
+ * @param processId - The process ID
1663
+ * @param address - The voter's address
1664
+ * @returns Promise resolving to boolean indicating if the address has voted
1256
1665
  */
1257
1666
  hasAddressVoted(processId: string, address: string): Promise<boolean>;
1258
1667
  /**
1259
- * Wait for a vote to reach a specific status
1668
+ * Watch vote status changes in real-time using an async generator.
1669
+ * Yields each status change as it happens, allowing for reactive UI updates.
1670
+ *
1671
+ * @param processId - The process ID
1672
+ * @param voteId - The vote ID
1673
+ * @param options - Optional configuration
1674
+ * @returns AsyncGenerator yielding vote status updates
1675
+ *
1676
+ * @example
1677
+ * ```typescript
1678
+ * const vote = await sdk.submitVote({ processId, choices: [1] });
1679
+ *
1680
+ * for await (const statusInfo of sdk.watchVoteStatus(vote.processId, vote.voteId)) {
1681
+ * console.log(`Vote status: ${statusInfo.status}`);
1682
+ *
1683
+ * switch (statusInfo.status) {
1684
+ * case VoteStatus.Pending:
1685
+ * console.log("⏳ Processing...");
1686
+ * break;
1687
+ * case VoteStatus.Verified:
1688
+ * console.log("✓ Verified");
1689
+ * break;
1690
+ * case VoteStatus.Settled:
1691
+ * console.log("✅ Settled");
1692
+ * break;
1693
+ * }
1694
+ * }
1695
+ * ```
1696
+ */
1697
+ watchVoteStatus(processId: string, voteId: string, options?: {
1698
+ targetStatus?: VoteStatus;
1699
+ timeoutMs?: number;
1700
+ pollIntervalMs?: number;
1701
+ }): AsyncGenerator<VoteStatusInfo>;
1702
+ /**
1703
+ * Wait for a vote to reach a specific status.
1704
+ * This is a simpler alternative to watchVoteStatus() that returns only the final status.
1260
1705
  *
1261
1706
  * @param processId - The process ID
1262
1707
  * @param voteId - The vote ID
@@ -1384,5 +1829,682 @@ declare function signProcessCreation(processId: string, signer: Signer | Wallet)
1384
1829
  */
1385
1830
  declare function validateProcessId(processId: string): boolean;
1386
1831
 
1387
- export { BaseService, CircomProof, ContractServiceError, DEFAULT_ENVIRONMENT_URLS, DavinciCrypto, ElectionMetadataTemplate, ElectionResultsTypeNames, OrganizationAdministratorError, OrganizationCreateError, OrganizationDeleteError, OrganizationRegistryService, OrganizationUpdateError, ProcessCensusError, ProcessCreateError, ProcessDurationError, ProcessOrchestrationService, ProcessRegistryService, ProcessResultError, ProcessStateTransitionError, ProcessStatus, ProcessStatusError, SmartContractService, TxStatus, VocdoniApiService, VocdoniSequencerService, VoteOrchestrationService, VoteStatus, createProcessSignatureMessage, deployedAddresses, getElectionMetadataTemplate, getEnvironmentChain, getEnvironmentConfig, getEnvironmentUrls, resolveConfiguration, resolveUrls, signProcessCreation, validateProcessId };
1388
- export type { AbstainProperties, AnyJson, ApiError, ApprovalProperties, BallotMode, BaseProcess, BudgetProperties, CSPSignOutput, Census, ChainConfig, Choice, ChoiceProperties, CircomProofOptions, CreateProcessRequest, CreateProcessResponse, CustomMeta, DavinciCryptoCiphertext, DavinciCryptoInputs, DavinciCryptoOptions, DavinciCryptoOutput, DeployedAddresses, ElectionMetadata, ElectionResultsType, EncryptionKey, EntityCallback, Environment, EnvironmentConfig, EnvironmentOptions, GetProcessResponse, Groth16Proof, IChoice, IQuestion, InfoResponse, JsonArray, JsonMap, ListProcessesResponse, MultiLanguage, OrganizationAdministratorAddedCallback, OrganizationAdministratorRemovedCallback, OrganizationCreatedCallback, OrganizationInfo, OrganizationUpdatedCallback, ProcessCensusUpdatedCallback, ProcessConfig, ProcessCreatedCallback, ProcessCreationResult, ProcessDurationChangedCallback, ProcessInfo, ProcessResultsSetCallback, ProcessStateRootUpdatedCallback, ProcessStatusChangedCallback, ProofInputs, ProtocolVersion, QuadraticProperties, Question, SequencerStats, ServiceUrls, TxStatusEvent, VocdoniApiServiceConfig, VoteBallot, VoteCiphertext, VoteConfig, VoteProof, VoteRequest, VoteResult, VoteStatusInfo, VoteStatusResponse, WorkerStats, WorkersResponse };
1832
+ /**
1833
+ * Configuration interface for the DavinciSDK
1834
+ */
1835
+ interface DavinciSDKConfig {
1836
+ /**
1837
+ * Ethers.js Signer for signing operations.
1838
+ * - For voting only: Can be a bare Wallet (no provider needed)
1839
+ * - For process/organization operations: Must be connected to a provider
1840
+ */
1841
+ signer: Signer;
1842
+ /** Sequencer API URL for Vocdoni services (required) */
1843
+ sequencerUrl: string;
1844
+ /** Census API URL for census management (optional, only needed when creating censuses from scratch) */
1845
+ censusUrl?: string;
1846
+ /** Custom contract addresses (optional, fetched from sequencer if not provided) */
1847
+ addresses?: {
1848
+ processRegistry?: string;
1849
+ organizationRegistry?: string;
1850
+ stateTransitionVerifier?: string;
1851
+ resultsVerifier?: string;
1852
+ sequencerRegistry?: string;
1853
+ };
1854
+ /** Custom census proof providers (optional) */
1855
+ censusProviders?: CensusProviders;
1856
+ /** Whether to verify downloaded circuit files match expected hashes (optional, defaults to true) */
1857
+ verifyCircuitFiles?: boolean;
1858
+ /** Whether to verify the generated proof is valid before submission (optional, defaults to true) */
1859
+ verifyProof?: boolean;
1860
+ }
1861
+ /**
1862
+ * Internal configuration interface
1863
+ */
1864
+ interface InternalDavinciSDKConfig {
1865
+ signer: Signer;
1866
+ sequencerUrl: string;
1867
+ censusUrl?: string;
1868
+ customAddresses: {
1869
+ processRegistry?: string;
1870
+ organizationRegistry?: string;
1871
+ stateTransitionVerifier?: string;
1872
+ resultsVerifier?: string;
1873
+ sequencerRegistry?: string;
1874
+ };
1875
+ fetchAddressesFromSequencer: boolean;
1876
+ verifyCircuitFiles: boolean;
1877
+ verifyProof: boolean;
1878
+ }
1879
+ /**
1880
+ * Simplified SDK class that encapsulates all Vocdoni DaVinci functionality
1881
+ */
1882
+ declare class DavinciSDK {
1883
+ private config;
1884
+ private apiService;
1885
+ private _processRegistry?;
1886
+ private _organizationRegistry?;
1887
+ private _processOrchestrator?;
1888
+ private _voteOrchestrator?;
1889
+ private davinciCrypto?;
1890
+ private initialized;
1891
+ private censusProviders;
1892
+ constructor(config: DavinciSDKConfig);
1893
+ /**
1894
+ * Initialize the SDK and all its components
1895
+ * This must be called before using any SDK functionality
1896
+ */
1897
+ init(): Promise<void>;
1898
+ /**
1899
+ * Get the API service for direct access to sequencer and census APIs
1900
+ */
1901
+ get api(): VocdoniApiService;
1902
+ /**
1903
+ * Get the process registry service for process management.
1904
+ * Requires a signer with a provider for blockchain interactions.
1905
+ *
1906
+ * @throws Error if signer does not have a provider
1907
+ */
1908
+ get processes(): ProcessRegistryService;
1909
+ /**
1910
+ * Get the organization registry service for organization management.
1911
+ * Requires a signer with a provider for blockchain interactions.
1912
+ *
1913
+ * @throws Error if signer does not have a provider
1914
+ */
1915
+ get organizations(): OrganizationRegistryService;
1916
+ /**
1917
+ * Get or initialize the DavinciCrypto service for cryptographic operations
1918
+ */
1919
+ getCrypto(): Promise<DavinciCrypto>;
1920
+ /**
1921
+ * Get the process orchestration service for simplified process creation.
1922
+ * Requires a signer with a provider for blockchain interactions.
1923
+ *
1924
+ * @throws Error if signer does not have a provider
1925
+ */
1926
+ get processOrchestrator(): ProcessOrchestrationService;
1927
+ /**
1928
+ * Get the vote orchestration service for simplified voting
1929
+ */
1930
+ get voteOrchestrator(): VoteOrchestrationService;
1931
+ /**
1932
+ * Gets user-friendly process information from the blockchain.
1933
+ * This method fetches raw contract data and transforms it into a user-friendly format
1934
+ * that matches the ProcessConfig interface used for creation, plus additional runtime data.
1935
+ *
1936
+ * Requires a signer with a provider for blockchain interactions.
1937
+ *
1938
+ * @param processId - The process ID to fetch
1939
+ * @returns Promise resolving to user-friendly process information
1940
+ * @throws Error if signer does not have a provider
1941
+ *
1942
+ * @example
1943
+ * ```typescript
1944
+ * const processInfo = await sdk.getProcess("0x1234567890abcdef...");
1945
+ *
1946
+ * // Access the same fields as ProcessConfig
1947
+ * console.log("Title:", processInfo.title);
1948
+ * console.log("Description:", processInfo.description);
1949
+ * console.log("Questions:", processInfo.questions);
1950
+ * console.log("Census size:", processInfo.census.size);
1951
+ * console.log("Ballot config:", processInfo.ballot);
1952
+ *
1953
+ * // Plus additional runtime information
1954
+ * console.log("Status:", processInfo.status);
1955
+ * console.log("Creator:", processInfo.creator);
1956
+ * console.log("Start date:", processInfo.startDate);
1957
+ * console.log("End date:", processInfo.endDate);
1958
+ * console.log("Duration:", processInfo.duration, "seconds");
1959
+ * console.log("Time remaining:", processInfo.timeRemaining, "seconds");
1960
+ *
1961
+ * // Access raw contract data if needed
1962
+ * console.log("Raw data:", processInfo.raw);
1963
+ * ```
1964
+ */
1965
+ getProcess(processId: string): Promise<ProcessInfo>;
1966
+ /**
1967
+ * Creates a complete voting process and returns an async generator that yields transaction status events.
1968
+ * This method allows you to monitor the transaction progress in real-time, including pending, completed,
1969
+ * failed, and reverted states.
1970
+ *
1971
+ * Requires a signer with a provider for blockchain interactions.
1972
+ *
1973
+ * @param config - Simplified process configuration
1974
+ * @returns AsyncGenerator yielding transaction status events
1975
+ * @throws Error if signer does not have a provider
1976
+ *
1977
+ * @example
1978
+ * ```typescript
1979
+ * const stream = sdk.createProcessStream({
1980
+ * title: "My Election",
1981
+ * description: "A simple election",
1982
+ * census: {
1983
+ * type: CensusOrigin.CensusOriginMerkleTree,
1984
+ * root: "0x1234...",
1985
+ * size: 100,
1986
+ * uri: "ipfs://..."
1987
+ * },
1988
+ * ballot: {
1989
+ * numFields: 2,
1990
+ * maxValue: "3",
1991
+ * minValue: "0",
1992
+ * uniqueValues: false,
1993
+ * costFromWeight: false,
1994
+ * costExponent: 10000,
1995
+ * maxValueSum: "6",
1996
+ * minValueSum: "0"
1997
+ * },
1998
+ * timing: {
1999
+ * startDate: new Date("2024-12-01T10:00:00Z"),
2000
+ * duration: 3600 * 24
2001
+ * },
2002
+ * questions: [
2003
+ * {
2004
+ * title: "What is your favorite color?",
2005
+ * choices: [
2006
+ * { title: "Red", value: 0 },
2007
+ * { title: "Blue", value: 1 }
2008
+ * ]
2009
+ * }
2010
+ * ]
2011
+ * });
2012
+ *
2013
+ * // Monitor transaction progress
2014
+ * for await (const event of stream) {
2015
+ * switch (event.status) {
2016
+ * case TxStatus.Pending:
2017
+ * console.log("Transaction pending:", event.hash);
2018
+ * // Update UI to show pending state
2019
+ * break;
2020
+ * case TxStatus.Completed:
2021
+ * console.log("Process created:", event.response.processId);
2022
+ * console.log("Transaction hash:", event.response.transactionHash);
2023
+ * // Update UI to show success
2024
+ * break;
2025
+ * case TxStatus.Failed:
2026
+ * console.error("Transaction failed:", event.error);
2027
+ * // Update UI to show error
2028
+ * break;
2029
+ * case TxStatus.Reverted:
2030
+ * console.error("Transaction reverted:", event.reason);
2031
+ * // Update UI to show revert reason
2032
+ * break;
2033
+ * }
2034
+ * }
2035
+ * ```
2036
+ */
2037
+ createProcessStream(config: ProcessConfig): AsyncGenerator<TxStatusEvent<ProcessCreationResult>, any, any>;
2038
+ /**
2039
+ * Creates a complete voting process with minimal configuration.
2040
+ * This is the ultra-easy method for end users that handles all the complex orchestration internally.
2041
+ *
2042
+ * For real-time transaction status updates, use createProcessStream() instead.
2043
+ *
2044
+ * Requires a signer with a provider for blockchain interactions.
2045
+ *
2046
+ * The method automatically:
2047
+ * - Gets encryption keys and initial state root from the sequencer
2048
+ * - Handles process creation signatures
2049
+ * - Coordinates between sequencer API and on-chain contract calls
2050
+ * - Creates and pushes metadata
2051
+ * - Submits the on-chain transaction
2052
+ *
2053
+ * @param config - Simplified process configuration
2054
+ * @returns Promise resolving to the process creation result
2055
+ * @throws Error if signer does not have a provider
2056
+ *
2057
+ * @example
2058
+ * ```typescript
2059
+ * // Option 1: Using duration (traditional approach)
2060
+ * const result1 = await sdk.createProcess({
2061
+ * title: "My Election",
2062
+ * description: "A simple election",
2063
+ * census: {
2064
+ * type: CensusOrigin.CensusOriginMerkleTree,
2065
+ * root: "0x1234...",
2066
+ * size: 100,
2067
+ * uri: "ipfs://your-census-uri"
2068
+ * },
2069
+ * ballot: {
2070
+ * numFields: 2,
2071
+ * maxValue: "3",
2072
+ * minValue: "0",
2073
+ * uniqueValues: false,
2074
+ * costFromWeight: false,
2075
+ * costExponent: 10000,
2076
+ * maxValueSum: "6",
2077
+ * minValueSum: "0"
2078
+ * },
2079
+ * timing: {
2080
+ * startDate: new Date("2024-12-01T10:00:00Z"),
2081
+ * duration: 3600 * 24
2082
+ * },
2083
+ * questions: [
2084
+ * {
2085
+ * title: "What is your favorite color?",
2086
+ * choices: [
2087
+ * { title: "Red", value: 0 },
2088
+ * { title: "Blue", value: 1 }
2089
+ * ]
2090
+ * }
2091
+ * ]
2092
+ * });
2093
+ *
2094
+ * // Option 2: Using start and end dates
2095
+ * const result2 = await sdk.createProcess({
2096
+ * title: "Weekend Vote",
2097
+ * timing: {
2098
+ * startDate: "2024-12-07T09:00:00Z",
2099
+ * endDate: "2024-12-08T18:00:00Z"
2100
+ * }
2101
+ * });
2102
+ * ```
2103
+ */
2104
+ createProcess(config: ProcessConfig): Promise<ProcessCreationResult>;
2105
+ /**
2106
+ * Submit a vote with simplified configuration.
2107
+ * This is the ultra-easy method for end users that handles all the complex voting workflow internally.
2108
+ *
2109
+ * Does NOT require a provider - can be used with a bare Wallet for signing only.
2110
+ * IMPORTANT: Requires censusUrl to be configured in the SDK for fetching census proofs (unless using custom census providers).
2111
+ *
2112
+ * The method automatically:
2113
+ * - Fetches process information and validates voting is allowed
2114
+ * - Gets census proof (Merkle tree based)
2115
+ * - Generates cryptographic proofs and encrypts the vote
2116
+ * - Signs and submits the vote to the sequencer
2117
+ *
2118
+ * @param config - Simplified vote configuration
2119
+ * @returns Promise resolving to vote submission result
2120
+ * @throws Error if censusUrl is not configured (unless using custom census providers)
2121
+ *
2122
+ * @example
2123
+ * ```typescript
2124
+ * // Submit a vote with voter's private key
2125
+ * const voteResult = await sdk.submitVote({
2126
+ * processId: "0x1234567890abcdef...",
2127
+ * choices: [1, 0], // Vote for option 1 in question 1, option 0 in question 2
2128
+ * voterKey: "0x1234567890abcdef..." // Voter's private key
2129
+ * });
2130
+ *
2131
+ * console.log("Vote ID:", voteResult.voteId);
2132
+ * console.log("Status:", voteResult.status);
2133
+ *
2134
+ * // Submit a vote with a Wallet instance
2135
+ * import { Wallet } from "ethers";
2136
+ * const voterWallet = new Wallet("0x...");
2137
+ *
2138
+ * const voteResult2 = await sdk.submitVote({
2139
+ * processId: "0x1234567890abcdef...",
2140
+ * choices: [2], // Single question vote
2141
+ * voterKey: voterWallet
2142
+ * });
2143
+ * ```
2144
+ */
2145
+ submitVote(config: VoteConfig): Promise<VoteResult>;
2146
+ /**
2147
+ * Get the status of a submitted vote.
2148
+ *
2149
+ * Does NOT require a provider - uses API calls only.
2150
+ *
2151
+ * @param processId - The process ID
2152
+ * @param voteId - The vote ID returned from submitVote()
2153
+ * @returns Promise resolving to vote status information
2154
+ *
2155
+ * @example
2156
+ * ```typescript
2157
+ * const statusInfo = await sdk.getVoteStatus(processId, voteId);
2158
+ * console.log("Vote status:", statusInfo.status);
2159
+ * // Possible statuses: "pending", "verified", "aggregated", "processed", "settled", "error"
2160
+ * ```
2161
+ */
2162
+ getVoteStatus(processId: string, voteId: string): Promise<VoteStatusInfo>;
2163
+ /**
2164
+ * Check if an address has voted in a process.
2165
+ *
2166
+ * Does NOT require a provider - uses API calls only.
2167
+ *
2168
+ * @param processId - The process ID
2169
+ * @param address - The voter's address
2170
+ * @returns Promise resolving to boolean indicating if the address has voted
2171
+ *
2172
+ * @example
2173
+ * ```typescript
2174
+ * const hasVoted = await sdk.hasAddressVoted(processId, "0x1234567890abcdef...");
2175
+ * if (hasVoted) {
2176
+ * console.log("This address has already voted");
2177
+ * }
2178
+ * ```
2179
+ */
2180
+ hasAddressVoted(processId: string, address: string): Promise<boolean>;
2181
+ /**
2182
+ * Watch vote status changes in real-time using an async generator.
2183
+ * This method yields each status change as it happens, perfect for showing
2184
+ * progress indicators in UI applications.
2185
+ *
2186
+ * Does NOT require a provider - uses API calls only.
2187
+ *
2188
+ * @param processId - The process ID
2189
+ * @param voteId - The vote ID
2190
+ * @param options - Optional configuration
2191
+ * @returns AsyncGenerator yielding vote status updates
2192
+ *
2193
+ * @example
2194
+ * ```typescript
2195
+ * // Submit vote
2196
+ * const voteResult = await sdk.submitVote({
2197
+ * processId: "0x1234567890abcdef...",
2198
+ * choices: [1]
2199
+ * });
2200
+ *
2201
+ * // Watch status changes in real-time
2202
+ * for await (const statusInfo of sdk.watchVoteStatus(voteResult.processId, voteResult.voteId)) {
2203
+ * console.log(`Vote status: ${statusInfo.status}`);
2204
+ *
2205
+ * switch (statusInfo.status) {
2206
+ * case VoteStatus.Pending:
2207
+ * console.log("⏳ Processing...");
2208
+ * break;
2209
+ * case VoteStatus.Verified:
2210
+ * console.log("✓ Vote verified");
2211
+ * break;
2212
+ * case VoteStatus.Aggregated:
2213
+ * console.log("📊 Vote aggregated");
2214
+ * break;
2215
+ * case VoteStatus.Settled:
2216
+ * console.log("✅ Vote settled");
2217
+ * break;
2218
+ * }
2219
+ * }
2220
+ * ```
2221
+ */
2222
+ watchVoteStatus(processId: string, voteId: string, options?: {
2223
+ targetStatus?: VoteStatus;
2224
+ timeoutMs?: number;
2225
+ pollIntervalMs?: number;
2226
+ }): AsyncGenerator<VoteStatusInfo, any, any>;
2227
+ /**
2228
+ * Wait for a vote to reach a specific status.
2229
+ * This is a simpler alternative to watchVoteStatus() that returns only the final status.
2230
+ * Useful for waiting for vote confirmation and processing without needing to handle each intermediate status.
2231
+ *
2232
+ * Does NOT require a provider - uses API calls only.
2233
+ *
2234
+ * @param processId - The process ID
2235
+ * @param voteId - The vote ID
2236
+ * @param targetStatus - The target status to wait for (default: "settled")
2237
+ * @param timeoutMs - Maximum time to wait in milliseconds (default: 300000 = 5 minutes)
2238
+ * @param pollIntervalMs - Polling interval in milliseconds (default: 5000 = 5 seconds)
2239
+ * @returns Promise resolving to final vote status
2240
+ *
2241
+ * @example
2242
+ * ```typescript
2243
+ * // Submit vote and wait for it to be settled
2244
+ * const voteResult = await sdk.submitVote({
2245
+ * processId: "0x1234567890abcdef...",
2246
+ * choices: [1]
2247
+ * });
2248
+ *
2249
+ * // Wait for the vote to be fully processed
2250
+ * const finalStatus = await sdk.waitForVoteStatus(
2251
+ * voteResult.processId,
2252
+ * voteResult.voteId,
2253
+ * VoteStatus.Settled, // Wait until vote is settled
2254
+ * 300000, // 5 minute timeout
2255
+ * 5000 // Check every 5 seconds
2256
+ * );
2257
+ *
2258
+ * console.log("Vote final status:", finalStatus.status);
2259
+ * ```
2260
+ */
2261
+ waitForVoteStatus(processId: string, voteId: string, targetStatus?: VoteStatus, timeoutMs?: number, pollIntervalMs?: number): Promise<VoteStatusInfo>;
2262
+ /**
2263
+ * Ends a voting process by setting its status to ENDED and returns an async generator
2264
+ * that yields transaction status events. This method allows you to monitor the
2265
+ * transaction progress in real-time.
2266
+ *
2267
+ * Requires a signer with a provider for blockchain interactions.
2268
+ *
2269
+ * @param processId - The process ID to end
2270
+ * @returns AsyncGenerator yielding transaction status events
2271
+ * @throws Error if signer does not have a provider
2272
+ *
2273
+ * @example
2274
+ * ```typescript
2275
+ * const stream = sdk.endProcessStream("0x1234567890abcdef...");
2276
+ *
2277
+ * for await (const event of stream) {
2278
+ * switch (event.status) {
2279
+ * case TxStatus.Pending:
2280
+ * console.log("Transaction pending:", event.hash);
2281
+ * break;
2282
+ * case TxStatus.Completed:
2283
+ * console.log("Process ended successfully");
2284
+ * break;
2285
+ * case TxStatus.Failed:
2286
+ * console.error("Transaction failed:", event.error);
2287
+ * break;
2288
+ * case TxStatus.Reverted:
2289
+ * console.error("Transaction reverted:", event.reason);
2290
+ * break;
2291
+ * }
2292
+ * }
2293
+ * ```
2294
+ */
2295
+ endProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
2296
+ success: boolean;
2297
+ }>, any, any>;
2298
+ /**
2299
+ * Ends a voting process by setting its status to ENDED.
2300
+ * This is the simplified method that waits for transaction completion.
2301
+ *
2302
+ * For real-time transaction status updates, use endProcessStream() instead.
2303
+ *
2304
+ * Requires a signer with a provider for blockchain interactions.
2305
+ *
2306
+ * @param processId - The process ID to end
2307
+ * @returns Promise resolving when the process is ended
2308
+ * @throws Error if signer does not have a provider
2309
+ *
2310
+ * @example
2311
+ * ```typescript
2312
+ * await sdk.endProcess("0x1234567890abcdef...");
2313
+ * console.log("Process ended successfully");
2314
+ * ```
2315
+ */
2316
+ endProcess(processId: string): Promise<void>;
2317
+ /**
2318
+ * Pauses a voting process by setting its status to PAUSED and returns an async generator
2319
+ * that yields transaction status events. This method allows you to monitor the
2320
+ * transaction progress in real-time.
2321
+ *
2322
+ * Requires a signer with a provider for blockchain interactions.
2323
+ *
2324
+ * @param processId - The process ID to pause
2325
+ * @returns AsyncGenerator yielding transaction status events
2326
+ * @throws Error if signer does not have a provider
2327
+ *
2328
+ * @example
2329
+ * ```typescript
2330
+ * const stream = sdk.pauseProcessStream("0x1234567890abcdef...");
2331
+ *
2332
+ * for await (const event of stream) {
2333
+ * switch (event.status) {
2334
+ * case TxStatus.Pending:
2335
+ * console.log("Transaction pending:", event.hash);
2336
+ * break;
2337
+ * case TxStatus.Completed:
2338
+ * console.log("Process paused successfully");
2339
+ * break;
2340
+ * case TxStatus.Failed:
2341
+ * console.error("Transaction failed:", event.error);
2342
+ * break;
2343
+ * case TxStatus.Reverted:
2344
+ * console.error("Transaction reverted:", event.reason);
2345
+ * break;
2346
+ * }
2347
+ * }
2348
+ * ```
2349
+ */
2350
+ pauseProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
2351
+ success: boolean;
2352
+ }>, any, any>;
2353
+ /**
2354
+ * Pauses a voting process by setting its status to PAUSED.
2355
+ * This is the simplified method that waits for transaction completion.
2356
+ *
2357
+ * For real-time transaction status updates, use pauseProcessStream() instead.
2358
+ *
2359
+ * Requires a signer with a provider for blockchain interactions.
2360
+ *
2361
+ * @param processId - The process ID to pause
2362
+ * @returns Promise resolving when the process is paused
2363
+ * @throws Error if signer does not have a provider
2364
+ *
2365
+ * @example
2366
+ * ```typescript
2367
+ * await sdk.pauseProcess("0x1234567890abcdef...");
2368
+ * console.log("Process paused successfully");
2369
+ * ```
2370
+ */
2371
+ pauseProcess(processId: string): Promise<void>;
2372
+ /**
2373
+ * Cancels a voting process by setting its status to CANCELED and returns an async generator
2374
+ * that yields transaction status events. This method allows you to monitor the
2375
+ * transaction progress in real-time.
2376
+ *
2377
+ * Requires a signer with a provider for blockchain interactions.
2378
+ *
2379
+ * @param processId - The process ID to cancel
2380
+ * @returns AsyncGenerator yielding transaction status events
2381
+ * @throws Error if signer does not have a provider
2382
+ *
2383
+ * @example
2384
+ * ```typescript
2385
+ * const stream = sdk.cancelProcessStream("0x1234567890abcdef...");
2386
+ *
2387
+ * for await (const event of stream) {
2388
+ * switch (event.status) {
2389
+ * case TxStatus.Pending:
2390
+ * console.log("Transaction pending:", event.hash);
2391
+ * break;
2392
+ * case TxStatus.Completed:
2393
+ * console.log("Process canceled successfully");
2394
+ * break;
2395
+ * case TxStatus.Failed:
2396
+ * console.error("Transaction failed:", event.error);
2397
+ * break;
2398
+ * case TxStatus.Reverted:
2399
+ * console.error("Transaction reverted:", event.reason);
2400
+ * break;
2401
+ * }
2402
+ * }
2403
+ * ```
2404
+ */
2405
+ cancelProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
2406
+ success: boolean;
2407
+ }>, any, any>;
2408
+ /**
2409
+ * Cancels a voting process by setting its status to CANCELED.
2410
+ * This is the simplified method that waits for transaction completion.
2411
+ *
2412
+ * For real-time transaction status updates, use cancelProcessStream() instead.
2413
+ *
2414
+ * Requires a signer with a provider for blockchain interactions.
2415
+ *
2416
+ * @param processId - The process ID to cancel
2417
+ * @returns Promise resolving when the process is canceled
2418
+ * @throws Error if signer does not have a provider
2419
+ *
2420
+ * @example
2421
+ * ```typescript
2422
+ * await sdk.cancelProcess("0x1234567890abcdef...");
2423
+ * console.log("Process canceled successfully");
2424
+ * ```
2425
+ */
2426
+ cancelProcess(processId: string): Promise<void>;
2427
+ /**
2428
+ * Resumes a voting process by setting its status to READY and returns an async generator
2429
+ * that yields transaction status events. This is typically used to resume a paused process.
2430
+ *
2431
+ * Requires a signer with a provider for blockchain interactions.
2432
+ *
2433
+ * @param processId - The process ID to resume
2434
+ * @returns AsyncGenerator yielding transaction status events
2435
+ * @throws Error if signer does not have a provider
2436
+ *
2437
+ * @example
2438
+ * ```typescript
2439
+ * const stream = sdk.resumeProcessStream("0x1234567890abcdef...");
2440
+ *
2441
+ * for await (const event of stream) {
2442
+ * switch (event.status) {
2443
+ * case TxStatus.Pending:
2444
+ * console.log("Transaction pending:", event.hash);
2445
+ * break;
2446
+ * case TxStatus.Completed:
2447
+ * console.log("Process resumed successfully");
2448
+ * break;
2449
+ * case TxStatus.Failed:
2450
+ * console.error("Transaction failed:", event.error);
2451
+ * break;
2452
+ * case TxStatus.Reverted:
2453
+ * console.error("Transaction reverted:", event.reason);
2454
+ * break;
2455
+ * }
2456
+ * }
2457
+ * ```
2458
+ */
2459
+ resumeProcessStream(processId: string): AsyncGenerator<TxStatusEvent<{
2460
+ success: boolean;
2461
+ }>, any, any>;
2462
+ /**
2463
+ * Resumes a voting process by setting its status to READY.
2464
+ * This is typically used to resume a paused process.
2465
+ * This is the simplified method that waits for transaction completion.
2466
+ *
2467
+ * For real-time transaction status updates, use resumeProcessStream() instead.
2468
+ *
2469
+ * Requires a signer with a provider for blockchain interactions.
2470
+ *
2471
+ * @param processId - The process ID to resume
2472
+ * @returns Promise resolving when the process is resumed
2473
+ * @throws Error if signer does not have a provider
2474
+ *
2475
+ * @example
2476
+ * ```typescript
2477
+ * await sdk.resumeProcess("0x1234567890abcdef...");
2478
+ * console.log("Process resumed successfully");
2479
+ * ```
2480
+ */
2481
+ resumeProcess(processId: string): Promise<void>;
2482
+ /**
2483
+ * Resolve contract address based on configuration priority:
2484
+ * 1. Custom addresses from user config (if provided)
2485
+ * 2. Addresses from sequencer (fetched during init if no custom addresses provided)
2486
+ */
2487
+ private resolveContractAddress;
2488
+ /**
2489
+ * Fetch contract addresses from sequencer info
2490
+ * This is called during init() if custom addresses are not provided
2491
+ */
2492
+ private fetchContractAddressesFromSequencer;
2493
+ /**
2494
+ * Get the current configuration
2495
+ */
2496
+ getConfig(): Readonly<InternalDavinciSDKConfig>;
2497
+ /**
2498
+ * Check if the SDK has been initialized
2499
+ */
2500
+ isInitialized(): boolean;
2501
+ /**
2502
+ * Ensures that the signer has a provider for blockchain operations.
2503
+ * @throws Error if the signer does not have a provider
2504
+ * @private
2505
+ */
2506
+ private ensureProvider;
2507
+ }
2508
+
2509
+ export { BaseService, Census, CensusOrchestrator, CensusOrigin, CensusType, CircomProof, ContractServiceError, CspCensus, DavinciCrypto, DavinciSDK, ElectionMetadataTemplate, ElectionResultsTypeNames, OrganizationAdministratorError, OrganizationCreateError, OrganizationDeleteError, OrganizationRegistryService, OrganizationUpdateError, PlainCensus, ProcessCensusError, ProcessCreateError, ProcessDurationError, ProcessOrchestrationService, ProcessRegistryService, ProcessResultError, ProcessStateTransitionError, ProcessStatus, ProcessStatusError, PublishedCensus, SmartContractService, TxStatus, VocdoniApiService, VocdoniCensusService, VocdoniSequencerService, VoteOrchestrationService, VoteStatus, WeightedCensus, assertCSPCensusProof, assertMerkleCensusProof, createProcessSignatureMessage, getElectionMetadataTemplate, isCSPCensusProof, isMerkleCensusProof, signProcessCreation, validateProcessId };
2510
+ export type { AbstainProperties, AnyJson, ApiError, ApprovalProperties, BallotMode, BaseCensusProof, BaseProcess, BudgetProperties, CSPCensusProof, CSPCensusProofProvider, CSPSignOutput, CensusData, CensusParticipant$1 as CensusParticipant, CensusProof, CensusProviders, CensusSizeResponse, Choice, ChoiceProperties, CircomProofOptions, CreateProcessRequest, CreateProcessResponse, CustomMeta, DavinciCryptoCiphertext, DavinciCryptoInputs, DavinciCryptoOptions, DavinciCryptoOutput, DavinciSDKConfig, ElectionMetadata, ElectionResultsType, EncryptionKey, EntityCallback, GetProcessResponse, Groth16Proof, HealthResponse, IChoice, IQuestion, InfoResponse, JsonArray, JsonMap, ListProcessesResponse, MerkleCensusProof, MerkleCensusProofProvider, MultiLanguage, OrganizationAdministratorAddedCallback, OrganizationAdministratorRemovedCallback, OrganizationCreatedCallback, OrganizationInfo, OrganizationUpdatedCallback, ProcessCensusUpdatedCallback, ProcessConfig, ProcessCreatedCallback, ProcessCreationResult, ProcessDurationChangedCallback, ProcessInfo, ProcessResultsSetCallback, ProcessStateRootUpdatedCallback, ProcessStatusChangedCallback, ProofInputs, ProtocolVersion, PublishCensusResponse, QuadraticProperties, Question, SequencerStats, Snapshot, SnapshotsQueryParams, SnapshotsResponse, TxStatusEvent, VocdoniApiServiceConfig, VoteBallot, VoteCiphertext, VoteConfig, VoteOrchestrationConfig, VoteProof, VoteRequest, VoteResult, VoteStatusInfo, VoteStatusResponse, WeightedParticipant, WorkerStats, WorkersResponse };