@vocdoni/davinci-sdk 0.0.5 → 0.0.7

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.mjs CHANGED
@@ -192,18 +192,20 @@ class VocdoniCensusService extends BaseService {
192
192
  }
193
193
 
194
194
  var CensusOrigin = /* @__PURE__ */ ((CensusOrigin2) => {
195
- CensusOrigin2[CensusOrigin2["CensusOriginMerkleTree"] = 1] = "CensusOriginMerkleTree";
196
- CensusOrigin2[CensusOrigin2["CensusOriginCSP"] = 2] = "CensusOriginCSP";
195
+ CensusOrigin2[CensusOrigin2["OffchainStatic"] = 1] = "OffchainStatic";
196
+ CensusOrigin2[CensusOrigin2["OffchainDynamic"] = 2] = "OffchainDynamic";
197
+ CensusOrigin2[CensusOrigin2["Onchain"] = 3] = "Onchain";
198
+ CensusOrigin2[CensusOrigin2["CSP"] = 4] = "CSP";
197
199
  return CensusOrigin2;
198
200
  })(CensusOrigin || {});
199
201
  function isBaseCensusProof(proof) {
200
202
  return !!proof && typeof proof.root === "string" && typeof proof.address === "string" && typeof proof.censusOrigin === "number" && Object.values(CensusOrigin).includes(proof.censusOrigin);
201
203
  }
202
204
  function isMerkleCensusProof(proof) {
203
- return isBaseCensusProof(proof) && proof.censusOrigin === 1 /* CensusOriginMerkleTree */ && typeof proof.weight === "string" && typeof proof.value === "string" && typeof proof.siblings === "string";
205
+ return isBaseCensusProof(proof) && (proof.censusOrigin === 1 /* OffchainStatic */ || proof.censusOrigin === 2 /* OffchainDynamic */ || proof.censusOrigin === 3 /* Onchain */) && typeof proof.weight === "string" && typeof proof.value === "string" && typeof proof.siblings === "string";
204
206
  }
205
207
  function isCSPCensusProof(proof) {
206
- return isBaseCensusProof(proof) && proof.censusOrigin === 2 /* CensusOriginCSP */ && typeof proof.weight === "string" && typeof proof.processId === "string" && typeof proof.publicKey === "string" && typeof proof.signature === "string";
208
+ return isBaseCensusProof(proof) && proof.censusOrigin === 4 /* CSP */ && typeof proof.weight === "string" && typeof proof.processId === "string" && typeof proof.publicKey === "string" && typeof proof.signature === "string";
207
209
  }
208
210
  function assertMerkleCensusProof(proof) {
209
211
  if (!isMerkleCensusProof(proof)) {
@@ -223,12 +225,27 @@ var CensusType = /* @__PURE__ */ ((CensusType2) => {
223
225
  return CensusType2;
224
226
  })(CensusType || {});
225
227
  class Census {
226
- constructor(type) {
228
+ constructor(type, censusOrigin) {
227
229
  this._censusId = null;
228
230
  this._censusRoot = null;
229
231
  this._censusURI = null;
230
232
  this._size = null;
231
233
  this._type = type;
234
+ if (censusOrigin !== void 0) {
235
+ this._censusOrigin = censusOrigin;
236
+ } else {
237
+ switch (type) {
238
+ case "plain" /* PLAIN */:
239
+ case "weighted" /* WEIGHTED */:
240
+ this._censusOrigin = CensusOrigin.OffchainStatic;
241
+ break;
242
+ case "csp" /* CSP */:
243
+ this._censusOrigin = CensusOrigin.CSP;
244
+ break;
245
+ default:
246
+ throw new Error(`Unknown census type: ${type}`);
247
+ }
248
+ }
232
249
  }
233
250
  get censusId() {
234
251
  return this._censusId;
@@ -249,24 +266,20 @@ class Census {
249
266
  return this._censusRoot !== null && this._censusURI !== null;
250
267
  }
251
268
  /**
252
- * Convert CensusType to CensusOrigin enum for API compatibility
269
+ * Get the census origin (OffchainStatic, OffchainDynamic, Onchain, or CSP)
253
270
  */
254
271
  get censusOrigin() {
255
- switch (this._type) {
256
- case "plain" /* PLAIN */:
257
- case "weighted" /* WEIGHTED */:
258
- return CensusOrigin.CensusOriginMerkleTree;
259
- case "csp" /* CSP */:
260
- return CensusOrigin.CensusOriginCSP;
261
- default:
262
- throw new Error(`Unknown census type: ${this._type}`);
263
- }
272
+ return this._censusOrigin;
264
273
  }
265
274
  }
266
275
 
267
276
  class PlainCensus extends Census {
268
- constructor() {
269
- super(CensusType.PLAIN);
277
+ /**
278
+ * Creates a new PlainCensus
279
+ * @param censusOrigin - The census origin (defaults to OffchainStatic for backward compatibility)
280
+ */
281
+ constructor(censusOrigin) {
282
+ super(CensusType.PLAIN, censusOrigin);
270
283
  this._participants = /* @__PURE__ */ new Set();
271
284
  }
272
285
  /**
@@ -324,8 +337,12 @@ class PlainCensus extends Census {
324
337
  }
325
338
 
326
339
  class WeightedCensus extends Census {
327
- constructor() {
328
- super(CensusType.WEIGHTED);
340
+ /**
341
+ * Creates a new WeightedCensus
342
+ * @param censusOrigin - The census origin (defaults to OffchainStatic for backward compatibility)
343
+ */
344
+ constructor(censusOrigin) {
345
+ super(CensusType.WEIGHTED, censusOrigin);
329
346
  this._participants = /* @__PURE__ */ new Map();
330
347
  }
331
348
  /**
@@ -417,7 +434,7 @@ class WeightedCensus extends Census {
417
434
 
418
435
  class CspCensus extends Census {
419
436
  constructor(publicKey, cspURI, size) {
420
- super(CensusType.CSP);
437
+ super(CensusType.CSP, CensusOrigin.CSP);
421
438
  if (!/^(0x)?[0-9a-fA-F]+$/.test(publicKey)) {
422
439
  throw new Error("Public key is missing or invalid");
423
440
  }
@@ -441,8 +458,16 @@ class CspCensus extends Census {
441
458
  }
442
459
 
443
460
  class PublishedCensus extends Census {
444
- constructor(type, root, uri, size) {
445
- super(type);
461
+ /**
462
+ * Creates a PublishedCensus from existing census data
463
+ * @param type - The census type (PLAIN, WEIGHTED, or CSP)
464
+ * @param root - The census root
465
+ * @param uri - The census URI
466
+ * @param size - The census size (number of participants)
467
+ * @param censusOrigin - The census origin (optional - defaults based on type if not provided)
468
+ */
469
+ constructor(type, root, uri, size, censusOrigin) {
470
+ super(type, censusOrigin);
446
471
  this._censusRoot = root;
447
472
  this._censusURI = uri;
448
473
  this._size = size;
@@ -941,6 +966,8 @@ class ProcessStatusError extends ContractServiceError {
941
966
  }
942
967
  class ProcessCensusError extends ContractServiceError {
943
968
  }
969
+ class CensusNotUpdatable extends ContractServiceError {
970
+ }
944
971
  class ProcessDurationError extends ContractServiceError {
945
972
  }
946
973
  class ProcessStateTransitionError extends ContractServiceError {
@@ -1004,7 +1031,7 @@ class ProcessRegistryService extends SmartContractService {
1004
1031
  return this.contract.stVerifier();
1005
1032
  }
1006
1033
  // ─── WRITES ────────────────────────────────────────────────────────
1007
- newProcess(status, startTime, duration, ballotMode, census, metadata, encryptionKey, initStateRoot) {
1034
+ newProcess(status, startTime, duration, maxVoters, ballotMode, census, metadata, encryptionKey, initStateRoot) {
1008
1035
  const contractCensus = {
1009
1036
  censusOrigin: BigInt(census.censusOrigin),
1010
1037
  censusRoot: census.censusRoot,
@@ -1015,6 +1042,7 @@ class ProcessRegistryService extends SmartContractService {
1015
1042
  status,
1016
1043
  startTime,
1017
1044
  duration,
1045
+ maxVoters,
1018
1046
  ballotMode,
1019
1047
  contractCensus,
1020
1048
  metadata,
@@ -1055,6 +1083,14 @@ class ProcessRegistryService extends SmartContractService {
1055
1083
  async () => ({ success: true })
1056
1084
  );
1057
1085
  }
1086
+ setProcessMaxVoters(processID, maxVoters) {
1087
+ return this.sendTx(
1088
+ this.contract.setProcessMaxVoters(processID, maxVoters).catch((e) => {
1089
+ throw new ProcessDurationError(e.message, "setMaxVoters");
1090
+ }),
1091
+ async () => ({ success: true })
1092
+ );
1093
+ }
1058
1094
  /**
1059
1095
  * Matches the on-chain `submitStateTransition(processId, proof, input)`
1060
1096
  */
@@ -1111,12 +1147,12 @@ class ProcessRegistryService extends SmartContractService {
1111
1147
  cb
1112
1148
  ).catch((err) => console.error("Error setting up ProcessDurationChanged listener:", err));
1113
1149
  }
1114
- onStateRootUpdated(cb) {
1150
+ onStateTransitioned(cb) {
1115
1151
  this.setupEventListener(
1116
1152
  this.contract,
1117
- this.contract.filters.ProcessStateRootUpdated(),
1153
+ this.contract.filters.ProcessStateTransitioned(),
1118
1154
  cb
1119
- ).catch((err) => console.error("Error setting up StateRootUpdated listener:", err));
1155
+ ).catch((err) => console.error("Error setting up ProcessStateTransitioned listener:", err));
1120
1156
  }
1121
1157
  onProcessResultsSet(cb) {
1122
1158
  this.setupEventListener(
@@ -1125,6 +1161,13 @@ class ProcessRegistryService extends SmartContractService {
1125
1161
  cb
1126
1162
  ).catch((err) => console.error("Error setting up ProcessResultsSet listener:", err));
1127
1163
  }
1164
+ onProcessMaxVotersChanged(cb) {
1165
+ this.setupEventListener(
1166
+ this.contract,
1167
+ this.contract.filters.ProcessMaxVotersChanged(),
1168
+ cb
1169
+ ).catch((err) => console.error("Error setting up ProcessMaxVotersChanged listener:", err));
1170
+ }
1128
1171
  removeAllListeners() {
1129
1172
  this.contract.removeAllListeners();
1130
1173
  this.clearPollingIntervals();
@@ -1230,6 +1273,7 @@ class ProcessOrchestrationService {
1230
1273
  endDate: new Date(endTime * 1e3),
1231
1274
  duration,
1232
1275
  timeRemaining,
1276
+ maxVoters: Number(rawProcess.maxVoters),
1233
1277
  result: rawProcess.result,
1234
1278
  votersCount: Number(rawProcess.votersCount),
1235
1279
  overwrittenVotesCount: Number(rawProcess.overwrittenVotesCount),
@@ -1284,6 +1328,7 @@ class ProcessOrchestrationService {
1284
1328
  ProcessStatus.READY,
1285
1329
  data.startTime,
1286
1330
  data.duration,
1331
+ data.maxVoters,
1287
1332
  data.ballotMode,
1288
1333
  data.census,
1289
1334
  data.metadataUri,
@@ -1371,6 +1416,7 @@ class ProcessOrchestrationService {
1371
1416
  ballotMode,
1372
1417
  signature
1373
1418
  });
1419
+ const maxVoters = config.maxVoters ?? censusConfig.size;
1374
1420
  const census = {
1375
1421
  censusOrigin: censusConfig.type,
1376
1422
  censusRoot,
@@ -1380,6 +1426,7 @@ class ProcessOrchestrationService {
1380
1426
  processId,
1381
1427
  startTime,
1382
1428
  duration,
1429
+ maxVoters,
1383
1430
  censusRoot,
1384
1431
  ballotMode,
1385
1432
  metadataUri,
@@ -1766,6 +1813,84 @@ class ProcessOrchestrationService {
1766
1813
  }
1767
1814
  throw new Error("Resume process stream ended unexpectedly");
1768
1815
  }
1816
+ /**
1817
+ * Sets the maximum number of voters for a process.
1818
+ * Returns an async generator that yields transaction status events.
1819
+ *
1820
+ * @param processId - The process ID
1821
+ * @param maxVoters - The new maximum number of voters
1822
+ * @returns AsyncGenerator yielding transaction status events
1823
+ *
1824
+ * @example
1825
+ * ```typescript
1826
+ * const stream = sdk.setProcessMaxVotersStream("0x1234567890abcdef...", 500);
1827
+ *
1828
+ * for await (const event of stream) {
1829
+ * switch (event.status) {
1830
+ * case "pending":
1831
+ * console.log("Transaction pending:", event.hash);
1832
+ * break;
1833
+ * case "completed":
1834
+ * console.log("MaxVoters updated successfully");
1835
+ * break;
1836
+ * case "failed":
1837
+ * console.error("Transaction failed:", event.error);
1838
+ * break;
1839
+ * case "reverted":
1840
+ * console.error("Transaction reverted:", event.reason);
1841
+ * break;
1842
+ * }
1843
+ * }
1844
+ * ```
1845
+ */
1846
+ async *setProcessMaxVotersStream(processId, maxVoters) {
1847
+ const txStream = this.processRegistry.setProcessMaxVoters(processId, maxVoters);
1848
+ for await (const event of txStream) {
1849
+ if (event.status === TxStatus.Pending) {
1850
+ yield { status: TxStatus.Pending, hash: event.hash };
1851
+ } else if (event.status === TxStatus.Completed) {
1852
+ yield {
1853
+ status: TxStatus.Completed,
1854
+ response: { success: true }
1855
+ };
1856
+ break;
1857
+ } else if (event.status === TxStatus.Failed) {
1858
+ yield { status: TxStatus.Failed, error: event.error };
1859
+ break;
1860
+ } else if (event.status === TxStatus.Reverted) {
1861
+ yield { status: TxStatus.Reverted, reason: event.reason };
1862
+ break;
1863
+ }
1864
+ }
1865
+ }
1866
+ /**
1867
+ * Sets the maximum number of voters for a process.
1868
+ * This is a simplified method that waits for transaction completion.
1869
+ *
1870
+ * For real-time transaction status updates, use setProcessMaxVotersStream() instead.
1871
+ *
1872
+ * @param processId - The process ID
1873
+ * @param maxVoters - The new maximum number of voters
1874
+ * @returns Promise resolving when the maxVoters is updated
1875
+ *
1876
+ * @example
1877
+ * ```typescript
1878
+ * await sdk.setProcessMaxVoters("0x1234567890abcdef...", 500);
1879
+ * console.log("MaxVoters updated successfully");
1880
+ * ```
1881
+ */
1882
+ async setProcessMaxVoters(processId, maxVoters) {
1883
+ for await (const event of this.setProcessMaxVotersStream(processId, maxVoters)) {
1884
+ if (event.status === "completed") {
1885
+ return;
1886
+ } else if (event.status === "failed") {
1887
+ throw event.error;
1888
+ } else if (event.status === "reverted") {
1889
+ throw new Error(`Transaction reverted: ${event.reason || "unknown reason"}`);
1890
+ }
1891
+ }
1892
+ throw new Error("Set process maxVoters stream ended unexpectedly");
1893
+ }
1769
1894
  }
1770
1895
 
1771
1896
  class CircomProof {
@@ -1921,7 +2046,7 @@ class VoteOrchestrationService {
1921
2046
  signature,
1922
2047
  voteId
1923
2048
  };
1924
- if (process.census.censusOrigin === CensusOrigin.CensusOriginCSP) {
2049
+ if (process.census.censusOrigin === CensusOrigin.CSP) {
1925
2050
  voteRequest.censusProof = censusProof;
1926
2051
  }
1927
2052
  await this.submitVoteRequest(voteRequest);
@@ -2037,7 +2162,7 @@ class VoteOrchestrationService {
2037
2162
  * Get census proof based on census origin type
2038
2163
  */
2039
2164
  async getCensusProof(censusOrigin, censusRoot, voterAddress, processId) {
2040
- if (censusOrigin === CensusOrigin.CensusOriginMerkleTree) {
2165
+ if (censusOrigin === CensusOrigin.OffchainStatic || censusOrigin === CensusOrigin.OffchainDynamic || censusOrigin === CensusOrigin.Onchain) {
2041
2166
  if (this.censusProviders.merkle) {
2042
2167
  const proof = await this.censusProviders.merkle({
2043
2168
  censusRoot,
@@ -2051,13 +2176,13 @@ class VoteOrchestrationService {
2051
2176
  root: censusRoot,
2052
2177
  address: voterAddress,
2053
2178
  weight,
2054
- censusOrigin: CensusOrigin.CensusOriginMerkleTree,
2179
+ censusOrigin,
2055
2180
  value: "",
2056
2181
  siblings: ""
2057
2182
  };
2058
2183
  }
2059
2184
  }
2060
- if (censusOrigin === CensusOrigin.CensusOriginCSP) {
2185
+ if (censusOrigin === CensusOrigin.CSP) {
2061
2186
  if (!this.censusProviders.csp) {
2062
2187
  throw new Error(
2063
2188
  "CSP voting requires a CSP census proof provider. Pass one via VoteOrchestrationService(..., { csp: yourFn })."
@@ -2631,7 +2756,7 @@ class DavinciSDK {
2631
2756
  * title: "My Election",
2632
2757
  * description: "A simple election",
2633
2758
  * census: {
2634
- * type: CensusOrigin.CensusOriginMerkleTree,
2759
+ * type: CensusOrigin.OffchainStatic,
2635
2760
  * root: "0x1234...",
2636
2761
  * size: 100,
2637
2762
  * uri: "ipfs://..."
@@ -2718,7 +2843,7 @@ class DavinciSDK {
2718
2843
  * title: "My Election",
2719
2844
  * description: "A simple election",
2720
2845
  * census: {
2721
- * type: CensusOrigin.CensusOriginMerkleTree,
2846
+ * type: CensusOrigin.OffchainStatic,
2722
2847
  * root: "0x1234...",
2723
2848
  * size: 100,
2724
2849
  * uri: "ipfs://your-census-uri"
@@ -3270,6 +3395,77 @@ class DavinciSDK {
3270
3395
  this.ensureProvider();
3271
3396
  return this.processOrchestrator.resumeProcess(processId);
3272
3397
  }
3398
+ /**
3399
+ * Sets the maximum number of voters for a process and returns an async generator
3400
+ * that yields transaction status events. This allows you to change the voter limit
3401
+ * after process creation.
3402
+ *
3403
+ * Requires a signer with a provider for blockchain interactions.
3404
+ *
3405
+ * @param processId - The process ID
3406
+ * @param maxVoters - The new maximum number of voters
3407
+ * @returns AsyncGenerator yielding transaction status events
3408
+ * @throws Error if signer does not have a provider
3409
+ *
3410
+ * @example
3411
+ * ```typescript
3412
+ * const stream = sdk.setProcessMaxVotersStream("0x1234567890abcdef...", 500);
3413
+ *
3414
+ * for await (const event of stream) {
3415
+ * switch (event.status) {
3416
+ * case TxStatus.Pending:
3417
+ * console.log("Transaction pending:", event.hash);
3418
+ * break;
3419
+ * case TxStatus.Completed:
3420
+ * console.log("MaxVoters updated successfully");
3421
+ * break;
3422
+ * case TxStatus.Failed:
3423
+ * console.error("Transaction failed:", event.error);
3424
+ * break;
3425
+ * case TxStatus.Reverted:
3426
+ * console.error("Transaction reverted:", event.reason);
3427
+ * break;
3428
+ * }
3429
+ * }
3430
+ * ```
3431
+ */
3432
+ setProcessMaxVotersStream(processId, maxVoters) {
3433
+ if (!this.initialized) {
3434
+ throw new Error(
3435
+ "SDK must be initialized before setting process maxVoters. Call sdk.init() first."
3436
+ );
3437
+ }
3438
+ this.ensureProvider();
3439
+ return this.processOrchestrator.setProcessMaxVotersStream(processId, maxVoters);
3440
+ }
3441
+ /**
3442
+ * Sets the maximum number of voters for a process.
3443
+ * This is the simplified method that waits for transaction completion.
3444
+ *
3445
+ * For real-time transaction status updates, use setProcessMaxVotersStream() instead.
3446
+ *
3447
+ * Requires a signer with a provider for blockchain interactions.
3448
+ *
3449
+ * @param processId - The process ID
3450
+ * @param maxVoters - The new maximum number of voters
3451
+ * @returns Promise resolving when the maxVoters is updated
3452
+ * @throws Error if signer does not have a provider
3453
+ *
3454
+ * @example
3455
+ * ```typescript
3456
+ * await sdk.setProcessMaxVoters("0x1234567890abcdef...", 500);
3457
+ * console.log("MaxVoters updated successfully");
3458
+ * ```
3459
+ */
3460
+ async setProcessMaxVoters(processId, maxVoters) {
3461
+ if (!this.initialized) {
3462
+ throw new Error(
3463
+ "SDK must be initialized before setting process maxVoters. Call sdk.init() first."
3464
+ );
3465
+ }
3466
+ this.ensureProvider();
3467
+ return this.processOrchestrator.setProcessMaxVoters(processId, maxVoters);
3468
+ }
3273
3469
  /**
3274
3470
  * Resolve contract address based on configuration priority:
3275
3471
  * 1. Custom addresses from user config (if provided)
@@ -3344,5 +3540,5 @@ class DavinciSDK {
3344
3540
  }
3345
3541
  }
3346
3542
 
3347
- 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 };
3543
+ export { BaseService, Census, CensusNotUpdatable, 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 };
3348
3544
  //# sourceMappingURL=index.mjs.map